1 //===-- DWARFUnit.cpp -----------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "DWARFUnit.h"
10 
11 #include "lldb/Core/Module.h"
12 #include "lldb/Host/StringConvert.h"
13 #include "lldb/Symbol/ObjectFile.h"
14 #include "lldb/Utility/LLDBAssert.h"
15 #include "lldb/Utility/StreamString.h"
16 #include "lldb/Utility/Timer.h"
17 #include "llvm/Object/Error.h"
18 
19 #include "DWARFCompileUnit.h"
20 #include "DWARFDebugAranges.h"
21 #include "DWARFDebugInfo.h"
22 #include "DWARFTypeUnit.h"
23 #include "LogChannelDWARF.h"
24 #include "SymbolFileDWARFDwo.h"
25 
26 using namespace lldb;
27 using namespace lldb_private;
28 using namespace std;
29 
30 extern int g_verbose;
31 
32 DWARFUnit::DWARFUnit(SymbolFileDWARF &dwarf, lldb::user_id_t uid,
33                      const DWARFUnitHeader &header,
34                      const DWARFAbbreviationDeclarationSet &abbrevs,
35                      DIERef::Section section, bool is_dwo)
36     : UserID(uid), m_dwarf(dwarf), m_header(header), m_abbrevs(&abbrevs),
37       m_cancel_scopes(false), m_section(section), m_is_dwo(is_dwo),
38       m_dwo_id(header.GetDWOId()) {}
39 
40 DWARFUnit::~DWARFUnit() = default;
41 
42 // Parses first DIE of a compile unit.
43 void DWARFUnit::ExtractUnitDIEIfNeeded() {
44   {
45     llvm::sys::ScopedReader lock(m_first_die_mutex);
46     if (m_first_die)
47       return; // Already parsed
48   }
49   llvm::sys::ScopedWriter lock(m_first_die_mutex);
50   if (m_first_die)
51     return; // Already parsed
52 
53   LLDB_SCOPED_TIMERF("%8.8x: DWARFUnit::ExtractUnitDIEIfNeeded()", GetOffset());
54 
55   // Set the offset to that of the first DIE and calculate the start of the
56   // next compilation unit header.
57   lldb::offset_t offset = GetFirstDIEOffset();
58 
59   // We are in our compile unit, parse starting at the offset we were told to
60   // parse
61   const DWARFDataExtractor &data = GetData();
62   if (offset < GetNextUnitOffset() &&
63       m_first_die.Extract(data, this, &offset)) {
64     AddUnitDIE(m_first_die);
65     return;
66   }
67 }
68 
69 // Parses a compile unit and indexes its DIEs if it hasn't already been done.
70 // It will leave this compile unit extracted forever.
71 void DWARFUnit::ExtractDIEsIfNeeded() {
72   m_cancel_scopes = true;
73 
74   {
75     llvm::sys::ScopedReader lock(m_die_array_mutex);
76     if (!m_die_array.empty())
77       return; // Already parsed
78   }
79   llvm::sys::ScopedWriter lock(m_die_array_mutex);
80   if (!m_die_array.empty())
81     return; // Already parsed
82 
83   ExtractDIEsRWLocked();
84 }
85 
86 // Parses a compile unit and indexes its DIEs if it hasn't already been done.
87 // It will clear this compile unit after returned instance gets out of scope,
88 // no other ScopedExtractDIEs instance is running for this compile unit
89 // and no ExtractDIEsIfNeeded() has been executed during this ScopedExtractDIEs
90 // lifetime.
91 DWARFUnit::ScopedExtractDIEs DWARFUnit::ExtractDIEsScoped() {
92   ScopedExtractDIEs scoped(*this);
93 
94   {
95     llvm::sys::ScopedReader lock(m_die_array_mutex);
96     if (!m_die_array.empty())
97       return scoped; // Already parsed
98   }
99   llvm::sys::ScopedWriter lock(m_die_array_mutex);
100   if (!m_die_array.empty())
101     return scoped; // Already parsed
102 
103   // Otherwise m_die_array would be already populated.
104   lldbassert(!m_cancel_scopes);
105 
106   ExtractDIEsRWLocked();
107   scoped.m_clear_dies = true;
108   return scoped;
109 }
110 
111 DWARFUnit::ScopedExtractDIEs::ScopedExtractDIEs(DWARFUnit &cu) : m_cu(&cu) {
112   m_cu->m_die_array_scoped_mutex.lock_shared();
113 }
114 
115 DWARFUnit::ScopedExtractDIEs::~ScopedExtractDIEs() {
116   if (!m_cu)
117     return;
118   m_cu->m_die_array_scoped_mutex.unlock_shared();
119   if (!m_clear_dies || m_cu->m_cancel_scopes)
120     return;
121   // Be sure no other ScopedExtractDIEs is running anymore.
122   llvm::sys::ScopedWriter lock_scoped(m_cu->m_die_array_scoped_mutex);
123   llvm::sys::ScopedWriter lock(m_cu->m_die_array_mutex);
124   if (m_cu->m_cancel_scopes)
125     return;
126   m_cu->ClearDIEsRWLocked();
127 }
128 
129 DWARFUnit::ScopedExtractDIEs::ScopedExtractDIEs(ScopedExtractDIEs &&rhs)
130     : m_cu(rhs.m_cu), m_clear_dies(rhs.m_clear_dies) {
131   rhs.m_cu = nullptr;
132 }
133 
134 DWARFUnit::ScopedExtractDIEs &DWARFUnit::ScopedExtractDIEs::operator=(
135     DWARFUnit::ScopedExtractDIEs &&rhs) {
136   m_cu = rhs.m_cu;
137   rhs.m_cu = nullptr;
138   m_clear_dies = rhs.m_clear_dies;
139   return *this;
140 }
141 
142 // Parses a compile unit and indexes its DIEs, m_die_array_mutex must be
143 // held R/W and m_die_array must be empty.
144 void DWARFUnit::ExtractDIEsRWLocked() {
145   llvm::sys::ScopedWriter first_die_lock(m_first_die_mutex);
146 
147   LLDB_SCOPED_TIMERF("%8.8x: DWARFUnit::ExtractDIEsIfNeeded()", GetOffset());
148 
149   // Set the offset to that of the first DIE and calculate the start of the
150   // next compilation unit header.
151   lldb::offset_t offset = GetFirstDIEOffset();
152   lldb::offset_t next_cu_offset = GetNextUnitOffset();
153 
154   DWARFDebugInfoEntry die;
155 
156   // We are in our compile unit, parse starting at the offset we were told to
157   // parse
158   const DWARFDataExtractor &data = GetData();
159   std::vector<uint32_t> die_index_stack;
160   die_index_stack.reserve(32);
161   bool prev_die_had_children = false;
162   while (offset < next_cu_offset && die.Extract(data, this, &offset)) {
163     const bool null_die = die.IsNULL();
164     if (die_index_stack.size() == 0) {
165       assert(m_die_array.empty() && "Compile unit DIE already added");
166 
167       // The average bytes per DIE entry has been seen to be around 14-20 so
168       // lets pre-reserve half of that since we are now stripping the NULL
169       // tags.
170 
171       // Only reserve the memory if we are adding children of the main
172       // compile unit DIE. The compile unit DIE is always the first entry, so
173       // if our size is 1, then we are adding the first compile unit child
174       // DIE and should reserve the memory.
175       m_die_array.reserve(GetDebugInfoSize() / 24);
176       m_die_array.push_back(die);
177 
178       if (!m_first_die)
179         AddUnitDIE(m_die_array.front());
180 
181       // With -fsplit-dwarf-inlining, clang will emit non-empty skeleton compile
182       // units. We are not able to access these DIE *and* the dwo file
183       // simultaneously. We also don't need to do that as the dwo file will
184       // contain a superset of information. So, we don't even attempt to parse
185       // any remaining DIEs.
186       if (m_dwo) {
187         m_die_array.front().SetHasChildren(false);
188         break;
189       }
190 
191     } else {
192       if (null_die) {
193         if (prev_die_had_children) {
194           // This will only happen if a DIE says is has children but all it
195           // contains is a NULL tag. Since we are removing the NULL DIEs from
196           // the list (saves up to 25% in C++ code), we need a way to let the
197           // DIE know that it actually doesn't have children.
198           if (!m_die_array.empty())
199             m_die_array.back().SetHasChildren(false);
200         }
201       } else {
202         die.SetParentIndex(m_die_array.size() - die_index_stack.rbegin()[1]);
203 
204         if (die_index_stack.back())
205           m_die_array[die_index_stack.back()].SetSiblingIndex(
206               m_die_array.size() - die_index_stack.back());
207         die_index_stack.back() = m_die_array.size();
208 
209         // Only push the DIE if it isn't a NULL DIE
210         m_die_array.push_back(die);
211       }
212     }
213 
214     if (null_die) {
215       // NULL DIE.
216       if (!die_index_stack.empty()) {
217         die_index_stack.pop_back();
218         prev_die_had_children = false;
219       }
220     } else {
221       // Normal DIE
222       const bool die_has_children = die.HasChildren();
223       if (die_has_children)
224         die_index_stack.push_back(0);
225       prev_die_had_children = die_has_children;
226     }
227 
228     if (die_index_stack.size() == 0)
229       break; // We are done with this compile unit!
230   }
231 
232   if (!m_die_array.empty()) {
233     if (m_first_die) {
234       // Only needed for the assertion.
235       m_first_die.SetHasChildren(m_die_array.front().HasChildren());
236       lldbassert(m_first_die == m_die_array.front());
237     }
238     m_first_die = m_die_array.front();
239   }
240 
241   m_die_array.shrink_to_fit();
242 
243   if (m_dwo)
244     m_dwo->ExtractDIEsIfNeeded();
245 }
246 
247 // This is used when a split dwarf is enabled.
248 // A skeleton compilation unit may contain the DW_AT_str_offsets_base attribute
249 // that points to the first string offset of the CU contribution to the
250 // .debug_str_offsets. At the same time, the corresponding split debug unit also
251 // may use DW_FORM_strx* forms pointing to its own .debug_str_offsets.dwo and
252 // for that case, we should find the offset (skip the section header).
253 void DWARFUnit::SetDwoStrOffsetsBase() {
254   lldb::offset_t baseOffset = 0;
255 
256   if (const llvm::DWARFUnitIndex::Entry *entry = m_header.GetIndexEntry()) {
257     if (const auto *contribution =
258             entry->getContribution(llvm::DW_SECT_STR_OFFSETS))
259       baseOffset = contribution->Offset;
260     else
261       return;
262   }
263 
264   if (GetVersion() >= 5) {
265     const DWARFDataExtractor &strOffsets =
266         GetSymbolFileDWARF().GetDWARFContext().getOrLoadStrOffsetsData();
267     uint64_t length = strOffsets.GetU32(&baseOffset);
268     if (length == 0xffffffff)
269       length = strOffsets.GetU64(&baseOffset);
270 
271     // Check version.
272     if (strOffsets.GetU16(&baseOffset) < 5)
273       return;
274 
275     // Skip padding.
276     baseOffset += 2;
277   }
278 
279   SetStrOffsetsBase(baseOffset);
280 }
281 
282 uint64_t DWARFUnit::GetDWOId() {
283   ExtractUnitDIEIfNeeded();
284   return m_dwo_id;
285 }
286 
287 // m_die_array_mutex must be already held as read/write.
288 void DWARFUnit::AddUnitDIE(const DWARFDebugInfoEntry &cu_die) {
289   llvm::Optional<uint64_t> addr_base, gnu_addr_base, gnu_ranges_base;
290 
291   DWARFAttributes attributes;
292   size_t num_attributes = cu_die.GetAttributes(this, attributes);
293 
294   // Extract DW_AT_addr_base first, as other attributes may need it.
295   for (size_t i = 0; i < num_attributes; ++i) {
296     if (attributes.AttributeAtIndex(i) != DW_AT_addr_base)
297       continue;
298     DWARFFormValue form_value;
299     if (attributes.ExtractFormValueAtIndex(i, form_value)) {
300       addr_base = form_value.Unsigned();
301       SetAddrBase(*addr_base);
302       break;
303     }
304   }
305 
306   for (size_t i = 0; i < num_attributes; ++i) {
307     dw_attr_t attr = attributes.AttributeAtIndex(i);
308     DWARFFormValue form_value;
309     if (!attributes.ExtractFormValueAtIndex(i, form_value))
310       continue;
311     switch (attr) {
312     case DW_AT_loclists_base:
313       SetLoclistsBase(form_value.Unsigned());
314       break;
315     case DW_AT_rnglists_base:
316       SetRangesBase(form_value.Unsigned());
317       break;
318     case DW_AT_str_offsets_base:
319       SetStrOffsetsBase(form_value.Unsigned());
320       break;
321     case DW_AT_low_pc:
322       SetBaseAddress(form_value.Address());
323       break;
324     case DW_AT_entry_pc:
325       // If the value was already set by DW_AT_low_pc, don't update it.
326       if (m_base_addr == LLDB_INVALID_ADDRESS)
327         SetBaseAddress(form_value.Address());
328       break;
329     case DW_AT_stmt_list:
330       m_line_table_offset = form_value.Unsigned();
331       break;
332     case DW_AT_GNU_addr_base:
333       gnu_addr_base = form_value.Unsigned();
334       break;
335     case DW_AT_GNU_ranges_base:
336       gnu_ranges_base = form_value.Unsigned();
337       break;
338     case DW_AT_GNU_dwo_id:
339       m_dwo_id = form_value.Unsigned();
340       break;
341     }
342   }
343 
344   if (m_is_dwo) {
345     SetDwoStrOffsetsBase();
346     return;
347   }
348 
349   std::shared_ptr<SymbolFileDWARFDwo> dwo_symbol_file =
350       m_dwarf.GetDwoSymbolFileForCompileUnit(*this, cu_die);
351   if (!dwo_symbol_file)
352     return;
353 
354   DWARFUnit *dwo_cu = dwo_symbol_file->GetDWOCompileUnitForHash(m_dwo_id);
355 
356   if (!dwo_cu)
357     return; // Can't fetch the compile unit from the dwo file.
358   dwo_cu->SetUserData(this);
359 
360   DWARFBaseDIE dwo_cu_die = dwo_cu->GetUnitDIEOnly();
361   if (!dwo_cu_die.IsValid())
362     return; // Can't fetch the compile unit DIE from the dwo file.
363 
364   // Here for DWO CU we want to use the address base set in the skeleton unit
365   // (DW_AT_addr_base) if it is available and use the DW_AT_GNU_addr_base
366   // otherwise. We do that because pre-DWARF v5 could use the DW_AT_GNU_*
367   // attributes which were applicable to the DWO units. The corresponding
368   // DW_AT_* attributes standardized in DWARF v5 are also applicable to the main
369   // unit in contrast.
370   if (addr_base)
371     dwo_cu->SetAddrBase(*addr_base);
372   else if (gnu_addr_base)
373     dwo_cu->SetAddrBase(*gnu_addr_base);
374 
375   if (GetVersion() <= 4 && gnu_ranges_base)
376     dwo_cu->SetRangesBase(*gnu_ranges_base);
377   else if (dwo_symbol_file->GetDWARFContext()
378                .getOrLoadRngListsData()
379                .GetByteSize() > 0)
380     dwo_cu->SetRangesBase(llvm::DWARFListTableHeader::getHeaderSize(DWARF32));
381 
382   if (GetVersion() >= 5 &&
383       dwo_symbol_file->GetDWARFContext().getOrLoadLocListsData().GetByteSize() >
384           0)
385     dwo_cu->SetLoclistsBase(llvm::DWARFListTableHeader::getHeaderSize(DWARF32));
386   dwo_cu->SetBaseAddress(GetBaseAddress());
387 
388   m_dwo = std::shared_ptr<DWARFUnit>(std::move(dwo_symbol_file), dwo_cu);
389 }
390 
391 size_t DWARFUnit::GetDebugInfoSize() const {
392   return GetLengthByteSize() + GetLength() - GetHeaderByteSize();
393 }
394 
395 const DWARFAbbreviationDeclarationSet *DWARFUnit::GetAbbreviations() const {
396   return m_abbrevs;
397 }
398 
399 dw_offset_t DWARFUnit::GetAbbrevOffset() const {
400   return m_abbrevs ? m_abbrevs->GetOffset() : DW_INVALID_OFFSET;
401 }
402 
403 dw_offset_t DWARFUnit::GetLineTableOffset() {
404   ExtractUnitDIEIfNeeded();
405   return m_line_table_offset;
406 }
407 
408 void DWARFUnit::SetAddrBase(dw_addr_t addr_base) { m_addr_base = addr_base; }
409 
410 // Parse the rangelist table header, including the optional array of offsets
411 // following it (DWARF v5 and later).
412 template <typename ListTableType>
413 static llvm::Expected<ListTableType>
414 ParseListTableHeader(const llvm::DWARFDataExtractor &data, uint64_t offset,
415                      DwarfFormat format) {
416   // We are expected to be called with Offset 0 or pointing just past the table
417   // header. Correct Offset in the latter case so that it points to the start
418   // of the header.
419   if (offset > 0) {
420     uint64_t HeaderSize = llvm::DWARFListTableHeader::getHeaderSize(format);
421     if (offset < HeaderSize)
422       return llvm::createStringError(errc::invalid_argument,
423                                      "did not detect a valid"
424                                      " list table with base = 0x%" PRIx64 "\n",
425                                      offset);
426     offset -= HeaderSize;
427   }
428   ListTableType Table;
429   if (llvm::Error E = Table.extractHeaderAndOffsets(data, &offset))
430     return std::move(E);
431   return Table;
432 }
433 
434 void DWARFUnit::SetLoclistsBase(dw_addr_t loclists_base) {
435   m_loclists_base = loclists_base;
436 
437   uint64_t header_size = llvm::DWARFListTableHeader::getHeaderSize(DWARF32);
438   if (loclists_base < header_size)
439     return;
440 
441   m_loclist_table_header.emplace(".debug_loclists", "locations");
442   uint64_t offset = loclists_base - header_size;
443   if (llvm::Error E = m_loclist_table_header->extract(
444           m_dwarf.GetDWARFContext().getOrLoadLocListsData().GetAsLLVM(),
445           &offset)) {
446     GetSymbolFileDWARF().GetObjectFile()->GetModule()->ReportError(
447         "Failed to extract location list table at offset 0x%" PRIx64 ": %s",
448         loclists_base, toString(std::move(E)).c_str());
449   }
450 }
451 
452 std::unique_ptr<llvm::DWARFLocationTable>
453 DWARFUnit::GetLocationTable(const DataExtractor &data) const {
454   llvm::DWARFDataExtractor llvm_data(
455       data.GetData(), data.GetByteOrder() == lldb::eByteOrderLittle,
456       data.GetAddressByteSize());
457 
458   if (m_is_dwo || GetVersion() >= 5)
459     return std::make_unique<llvm::DWARFDebugLoclists>(llvm_data, GetVersion());
460   return std::make_unique<llvm::DWARFDebugLoc>(llvm_data);
461 }
462 
463 DWARFDataExtractor DWARFUnit::GetLocationData() const {
464   DWARFContext &Ctx = GetSymbolFileDWARF().GetDWARFContext();
465   const DWARFDataExtractor &data =
466       GetVersion() >= 5 ? Ctx.getOrLoadLocListsData() : Ctx.getOrLoadLocData();
467   if (const llvm::DWARFUnitIndex::Entry *entry = m_header.GetIndexEntry()) {
468     if (const auto *contribution = entry->getContribution(llvm::DW_SECT_EXT_LOC))
469       return DWARFDataExtractor(data, contribution->Offset,
470                                 contribution->Length);
471     return DWARFDataExtractor();
472   }
473   return data;
474 }
475 
476 void DWARFUnit::SetRangesBase(dw_addr_t ranges_base) {
477   m_ranges_base = ranges_base;
478 
479   if (GetVersion() < 5)
480     return;
481 
482   if (auto table_or_error = ParseListTableHeader<llvm::DWARFDebugRnglistTable>(
483           m_dwarf.GetDWARFContext().getOrLoadRngListsData().GetAsLLVM(),
484           ranges_base, DWARF32))
485     m_rnglist_table = std::move(table_or_error.get());
486   else
487     GetSymbolFileDWARF().GetObjectFile()->GetModule()->ReportError(
488         "Failed to extract range list table at offset 0x%" PRIx64 ": %s",
489         ranges_base, toString(table_or_error.takeError()).c_str());
490 }
491 
492 void DWARFUnit::SetStrOffsetsBase(dw_offset_t str_offsets_base) {
493   m_str_offsets_base = str_offsets_base;
494 }
495 
496 // It may be called only with m_die_array_mutex held R/W.
497 void DWARFUnit::ClearDIEsRWLocked() {
498   m_die_array.clear();
499   m_die_array.shrink_to_fit();
500 
501   if (m_dwo)
502     m_dwo->ClearDIEsRWLocked();
503 }
504 
505 lldb::ByteOrder DWARFUnit::GetByteOrder() const {
506   return m_dwarf.GetObjectFile()->GetByteOrder();
507 }
508 
509 void DWARFUnit::SetBaseAddress(dw_addr_t base_addr) { m_base_addr = base_addr; }
510 
511 // Compare function DWARFDebugAranges::Range structures
512 static bool CompareDIEOffset(const DWARFDebugInfoEntry &die,
513                              const dw_offset_t die_offset) {
514   return die.GetOffset() < die_offset;
515 }
516 
517 // GetDIE()
518 //
519 // Get the DIE (Debug Information Entry) with the specified offset by first
520 // checking if the DIE is contained within this compile unit and grabbing the
521 // DIE from this compile unit. Otherwise we grab the DIE from the DWARF file.
522 DWARFDIE
523 DWARFUnit::GetDIE(dw_offset_t die_offset) {
524   if (die_offset == DW_INVALID_OFFSET)
525     return DWARFDIE(); // Not found
526 
527   if (!ContainsDIEOffset(die_offset)) {
528     GetSymbolFileDWARF().GetObjectFile()->GetModule()->ReportError(
529         "GetDIE for DIE 0x%" PRIx32 " is outside of its CU 0x%" PRIx32,
530         die_offset, GetOffset());
531     return DWARFDIE(); // Not found
532   }
533 
534   ExtractDIEsIfNeeded();
535   DWARFDebugInfoEntry::const_iterator end = m_die_array.cend();
536   DWARFDebugInfoEntry::const_iterator pos =
537       lower_bound(m_die_array.cbegin(), end, die_offset, CompareDIEOffset);
538 
539   if (pos != end && die_offset == (*pos).GetOffset())
540     return DWARFDIE(this, &(*pos));
541   return DWARFDIE(); // Not found
542 }
543 
544 DWARFUnit &DWARFUnit::GetNonSkeletonUnit() {
545   ExtractUnitDIEIfNeeded();
546   if (m_dwo)
547     return *m_dwo;
548   return *this;
549 }
550 
551 uint8_t DWARFUnit::GetAddressByteSize(const DWARFUnit *cu) {
552   if (cu)
553     return cu->GetAddressByteSize();
554   return DWARFUnit::GetDefaultAddressSize();
555 }
556 
557 uint8_t DWARFUnit::GetDefaultAddressSize() { return 4; }
558 
559 void *DWARFUnit::GetUserData() const { return m_user_data; }
560 
561 void DWARFUnit::SetUserData(void *d) { m_user_data = d; }
562 
563 bool DWARFUnit::Supports_DW_AT_APPLE_objc_complete_type() {
564   return GetProducer() != eProducerLLVMGCC;
565 }
566 
567 bool DWARFUnit::DW_AT_decl_file_attributes_are_invalid() {
568   // llvm-gcc makes completely invalid decl file attributes and won't ever be
569   // fixed, so we need to know to ignore these.
570   return GetProducer() == eProducerLLVMGCC;
571 }
572 
573 bool DWARFUnit::Supports_unnamed_objc_bitfields() {
574   if (GetProducer() == eProducerClang) {
575     const uint32_t major_version = GetProducerVersionMajor();
576     return major_version > 425 ||
577            (major_version == 425 && GetProducerVersionUpdate() >= 13);
578   }
579   return true; // Assume all other compilers didn't have incorrect ObjC bitfield
580                // info
581 }
582 
583 void DWARFUnit::ParseProducerInfo() {
584   m_producer_version_major = UINT32_MAX;
585   m_producer_version_minor = UINT32_MAX;
586   m_producer_version_update = UINT32_MAX;
587 
588   const DWARFDebugInfoEntry *die = GetUnitDIEPtrOnly();
589   if (die) {
590 
591     const char *producer_cstr =
592         die->GetAttributeValueAsString(this, DW_AT_producer, nullptr);
593     if (producer_cstr) {
594       RegularExpression llvm_gcc_regex(
595           llvm::StringRef("^4\\.[012]\\.[01] \\(Based on Apple "
596                           "Inc\\. build [0-9]+\\) \\(LLVM build "
597                           "[\\.0-9]+\\)$"));
598       if (llvm_gcc_regex.Execute(llvm::StringRef(producer_cstr))) {
599         m_producer = eProducerLLVMGCC;
600       } else if (strstr(producer_cstr, "clang")) {
601         static RegularExpression g_clang_version_regex(
602             llvm::StringRef("clang-([0-9]+)\\.([0-9]+)\\.([0-9]+)"));
603         llvm::SmallVector<llvm::StringRef, 4> matches;
604         if (g_clang_version_regex.Execute(llvm::StringRef(producer_cstr),
605                                           &matches)) {
606           m_producer_version_major =
607               StringConvert::ToUInt32(matches[1].str().c_str(), UINT32_MAX, 10);
608           m_producer_version_minor =
609               StringConvert::ToUInt32(matches[2].str().c_str(), UINT32_MAX, 10);
610           m_producer_version_update =
611               StringConvert::ToUInt32(matches[3].str().c_str(), UINT32_MAX, 10);
612         }
613         m_producer = eProducerClang;
614       } else if (strstr(producer_cstr, "GNU"))
615         m_producer = eProducerGCC;
616     }
617   }
618   if (m_producer == eProducerInvalid)
619     m_producer = eProcucerOther;
620 }
621 
622 DWARFProducer DWARFUnit::GetProducer() {
623   if (m_producer == eProducerInvalid)
624     ParseProducerInfo();
625   return m_producer;
626 }
627 
628 uint32_t DWARFUnit::GetProducerVersionMajor() {
629   if (m_producer_version_major == 0)
630     ParseProducerInfo();
631   return m_producer_version_major;
632 }
633 
634 uint32_t DWARFUnit::GetProducerVersionMinor() {
635   if (m_producer_version_minor == 0)
636     ParseProducerInfo();
637   return m_producer_version_minor;
638 }
639 
640 uint32_t DWARFUnit::GetProducerVersionUpdate() {
641   if (m_producer_version_update == 0)
642     ParseProducerInfo();
643   return m_producer_version_update;
644 }
645 
646 uint64_t DWARFUnit::GetDWARFLanguageType() {
647   if (m_language_type)
648     return *m_language_type;
649 
650   const DWARFDebugInfoEntry *die = GetUnitDIEPtrOnly();
651   if (!die)
652     m_language_type = 0;
653   else
654     m_language_type = die->GetAttributeValueAsUnsigned(this, DW_AT_language, 0);
655   return *m_language_type;
656 }
657 
658 bool DWARFUnit::GetIsOptimized() {
659   if (m_is_optimized == eLazyBoolCalculate) {
660     const DWARFDebugInfoEntry *die = GetUnitDIEPtrOnly();
661     if (die) {
662       m_is_optimized = eLazyBoolNo;
663       if (die->GetAttributeValueAsUnsigned(this, DW_AT_APPLE_optimized, 0) ==
664           1) {
665         m_is_optimized = eLazyBoolYes;
666       }
667     }
668   }
669   return m_is_optimized == eLazyBoolYes;
670 }
671 
672 FileSpec::Style DWARFUnit::GetPathStyle() {
673   if (!m_comp_dir)
674     ComputeCompDirAndGuessPathStyle();
675   return m_comp_dir->GetPathStyle();
676 }
677 
678 const FileSpec &DWARFUnit::GetCompilationDirectory() {
679   if (!m_comp_dir)
680     ComputeCompDirAndGuessPathStyle();
681   return *m_comp_dir;
682 }
683 
684 const FileSpec &DWARFUnit::GetAbsolutePath() {
685   if (!m_file_spec)
686     ComputeAbsolutePath();
687   return *m_file_spec;
688 }
689 
690 FileSpec DWARFUnit::GetFile(size_t file_idx) {
691   return m_dwarf.GetFile(*this, file_idx);
692 }
693 
694 // DWARF2/3 suggests the form hostname:pathname for compilation directory.
695 // Remove the host part if present.
696 static llvm::StringRef
697 removeHostnameFromPathname(llvm::StringRef path_from_dwarf) {
698   if (!path_from_dwarf.contains(':'))
699     return path_from_dwarf;
700   llvm::StringRef host, path;
701   std::tie(host, path) = path_from_dwarf.split(':');
702 
703   if (host.contains('/'))
704     return path_from_dwarf;
705 
706   // check whether we have a windows path, and so the first character is a
707   // drive-letter not a hostname.
708   if (host.size() == 1 && llvm::isAlpha(host[0]) && path.startswith("\\"))
709     return path_from_dwarf;
710 
711   return path;
712 }
713 
714 void DWARFUnit::ComputeCompDirAndGuessPathStyle() {
715   m_comp_dir = FileSpec();
716   const DWARFDebugInfoEntry *die = GetUnitDIEPtrOnly();
717   if (!die)
718     return;
719 
720   llvm::StringRef comp_dir = removeHostnameFromPathname(
721       die->GetAttributeValueAsString(this, DW_AT_comp_dir, nullptr));
722   if (!comp_dir.empty()) {
723     FileSpec::Style comp_dir_style =
724         FileSpec::GuessPathStyle(comp_dir).getValueOr(FileSpec::Style::native);
725     m_comp_dir = FileSpec(comp_dir, comp_dir_style);
726   } else {
727     // Try to detect the style based on the DW_AT_name attribute, but just store
728     // the detected style in the m_comp_dir field.
729     const char *name =
730         die->GetAttributeValueAsString(this, DW_AT_name, nullptr);
731     m_comp_dir = FileSpec(
732         "", FileSpec::GuessPathStyle(name).getValueOr(FileSpec::Style::native));
733   }
734 }
735 
736 void DWARFUnit::ComputeAbsolutePath() {
737   m_file_spec = FileSpec();
738   const DWARFDebugInfoEntry *die = GetUnitDIEPtrOnly();
739   if (!die)
740     return;
741 
742   m_file_spec =
743       FileSpec(die->GetAttributeValueAsString(this, DW_AT_name, nullptr),
744                GetPathStyle());
745 
746   if (m_file_spec->IsRelative())
747     m_file_spec->MakeAbsolute(GetCompilationDirectory());
748 }
749 
750 SymbolFileDWARFDwo *DWARFUnit::GetDwoSymbolFile() {
751   ExtractUnitDIEIfNeeded();
752   if (m_dwo)
753     return &llvm::cast<SymbolFileDWARFDwo>(m_dwo->GetSymbolFileDWARF());
754   return nullptr;
755 }
756 
757 const DWARFDebugAranges &DWARFUnit::GetFunctionAranges() {
758   if (m_func_aranges_up == nullptr) {
759     m_func_aranges_up = std::make_unique<DWARFDebugAranges>();
760     const DWARFDebugInfoEntry *die = DIEPtr();
761     if (die)
762       die->BuildFunctionAddressRangeTable(this, m_func_aranges_up.get());
763 
764     if (m_dwo) {
765       const DWARFDebugInfoEntry *dwo_die = m_dwo->DIEPtr();
766       if (dwo_die)
767         dwo_die->BuildFunctionAddressRangeTable(m_dwo.get(),
768                                                 m_func_aranges_up.get());
769     }
770 
771     const bool minimize = false;
772     m_func_aranges_up->Sort(minimize);
773   }
774   return *m_func_aranges_up;
775 }
776 
777 llvm::Expected<DWARFUnitHeader>
778 DWARFUnitHeader::extract(const DWARFDataExtractor &data,
779                          DIERef::Section section,
780                          lldb_private::DWARFContext &context,
781                          lldb::offset_t *offset_ptr) {
782   DWARFUnitHeader header;
783   header.m_offset = *offset_ptr;
784   header.m_length = data.GetDWARFInitialLength(offset_ptr);
785   header.m_version = data.GetU16(offset_ptr);
786   if (header.m_version == 5) {
787     header.m_unit_type = data.GetU8(offset_ptr);
788     header.m_addr_size = data.GetU8(offset_ptr);
789     header.m_abbr_offset = data.GetDWARFOffset(offset_ptr);
790     if (header.m_unit_type == llvm::dwarf::DW_UT_skeleton ||
791         header.m_unit_type == llvm::dwarf::DW_UT_split_compile)
792       header.m_dwo_id = data.GetU64(offset_ptr);
793   } else {
794     header.m_abbr_offset = data.GetDWARFOffset(offset_ptr);
795     header.m_addr_size = data.GetU8(offset_ptr);
796     header.m_unit_type =
797         section == DIERef::Section::DebugTypes ? DW_UT_type : DW_UT_compile;
798   }
799 
800   if (context.isDwo()) {
801     if (header.IsTypeUnit()) {
802       header.m_index_entry =
803           context.GetAsLLVM().getTUIndex().getFromOffset(header.m_offset);
804     } else {
805       header.m_index_entry =
806           context.GetAsLLVM().getCUIndex().getFromOffset(header.m_offset);
807     }
808   }
809 
810   if (header.m_index_entry) {
811     if (header.m_abbr_offset) {
812       return llvm::createStringError(
813           llvm::inconvertibleErrorCode(),
814           "Package unit with a non-zero abbreviation offset");
815     }
816     auto *unit_contrib = header.m_index_entry->getContribution();
817     if (!unit_contrib || unit_contrib->Length != header.m_length + 4) {
818       return llvm::createStringError(llvm::inconvertibleErrorCode(),
819                                      "Inconsistent DWARF package unit index");
820     }
821     auto *abbr_entry =
822         header.m_index_entry->getContribution(llvm::DW_SECT_ABBREV);
823     if (!abbr_entry) {
824       return llvm::createStringError(
825           llvm::inconvertibleErrorCode(),
826           "DWARF package index missing abbreviation column");
827     }
828     header.m_abbr_offset = abbr_entry->Offset;
829   }
830   if (header.IsTypeUnit()) {
831     header.m_type_hash = data.GetU64(offset_ptr);
832     header.m_type_offset = data.GetDWARFOffset(offset_ptr);
833   }
834 
835   bool length_OK = data.ValidOffset(header.GetNextUnitOffset() - 1);
836   bool version_OK = SymbolFileDWARF::SupportedVersion(header.m_version);
837   bool addr_size_OK = (header.m_addr_size == 4) || (header.m_addr_size == 8);
838   bool type_offset_OK =
839       !header.IsTypeUnit() || (header.m_type_offset <= header.GetLength());
840 
841   if (!length_OK)
842     return llvm::make_error<llvm::object::GenericBinaryError>(
843         "Invalid unit length");
844   if (!version_OK)
845     return llvm::make_error<llvm::object::GenericBinaryError>(
846         "Unsupported unit version");
847   if (!addr_size_OK)
848     return llvm::make_error<llvm::object::GenericBinaryError>(
849         "Invalid unit address size");
850   if (!type_offset_OK)
851     return llvm::make_error<llvm::object::GenericBinaryError>(
852         "Type offset out of range");
853 
854   return header;
855 }
856 
857 llvm::Expected<DWARFUnitSP>
858 DWARFUnit::extract(SymbolFileDWARF &dwarf, user_id_t uid,
859                    const DWARFDataExtractor &debug_info,
860                    DIERef::Section section, lldb::offset_t *offset_ptr) {
861   assert(debug_info.ValidOffset(*offset_ptr));
862 
863   auto expected_header = DWARFUnitHeader::extract(
864       debug_info, section, dwarf.GetDWARFContext(), offset_ptr);
865   if (!expected_header)
866     return expected_header.takeError();
867 
868   const DWARFDebugAbbrev *abbr = dwarf.DebugAbbrev();
869   if (!abbr)
870     return llvm::make_error<llvm::object::GenericBinaryError>(
871         "No debug_abbrev data");
872 
873   bool abbr_offset_OK =
874       dwarf.GetDWARFContext().getOrLoadAbbrevData().ValidOffset(
875           expected_header->GetAbbrOffset());
876   if (!abbr_offset_OK)
877     return llvm::make_error<llvm::object::GenericBinaryError>(
878         "Abbreviation offset for unit is not valid");
879 
880   const DWARFAbbreviationDeclarationSet *abbrevs =
881       abbr->GetAbbreviationDeclarationSet(expected_header->GetAbbrOffset());
882   if (!abbrevs)
883     return llvm::make_error<llvm::object::GenericBinaryError>(
884         "No abbrev exists at the specified offset.");
885 
886   bool is_dwo = dwarf.GetDWARFContext().isDwo();
887   if (expected_header->IsTypeUnit())
888     return DWARFUnitSP(new DWARFTypeUnit(dwarf, uid, *expected_header, *abbrevs,
889                                          section, is_dwo));
890   return DWARFUnitSP(new DWARFCompileUnit(dwarf, uid, *expected_header,
891                                           *abbrevs, section, is_dwo));
892 }
893 
894 const lldb_private::DWARFDataExtractor &DWARFUnit::GetData() const {
895   return m_section == DIERef::Section::DebugTypes
896              ? m_dwarf.GetDWARFContext().getOrLoadDebugTypesData()
897              : m_dwarf.GetDWARFContext().getOrLoadDebugInfoData();
898 }
899 
900 uint32_t DWARFUnit::GetHeaderByteSize() const {
901   switch (m_header.GetUnitType()) {
902   case llvm::dwarf::DW_UT_compile:
903   case llvm::dwarf::DW_UT_partial:
904     return GetVersion() < 5 ? 11 : 12;
905   case llvm::dwarf::DW_UT_skeleton:
906   case llvm::dwarf::DW_UT_split_compile:
907     return 20;
908   case llvm::dwarf::DW_UT_type:
909   case llvm::dwarf::DW_UT_split_type:
910     return GetVersion() < 5 ? 23 : 24;
911   }
912   llvm_unreachable("invalid UnitType.");
913 }
914 
915 llvm::Optional<uint64_t>
916 DWARFUnit::GetStringOffsetSectionItem(uint32_t index) const {
917   offset_t offset = GetStrOffsetsBase() + index * 4;
918   return m_dwarf.GetDWARFContext().getOrLoadStrOffsetsData().GetU32(&offset);
919 }
920 
921 llvm::Expected<DWARFRangeList>
922 DWARFUnit::FindRnglistFromOffset(dw_offset_t offset) {
923   if (GetVersion() <= 4) {
924     const DWARFDebugRanges *debug_ranges = m_dwarf.GetDebugRanges();
925     if (!debug_ranges)
926       return llvm::make_error<llvm::object::GenericBinaryError>(
927           "No debug_ranges section");
928     DWARFRangeList ranges;
929     debug_ranges->FindRanges(this, offset, ranges);
930     return ranges;
931   }
932 
933   if (!m_rnglist_table)
934     return llvm::createStringError(errc::invalid_argument,
935                                    "missing or invalid range list table");
936 
937   auto range_list_or_error = m_rnglist_table->findList(
938       m_dwarf.GetDWARFContext().getOrLoadRngListsData().GetAsLLVM(), offset);
939   if (!range_list_or_error)
940     return range_list_or_error.takeError();
941 
942   llvm::Expected<llvm::DWARFAddressRangesVector> llvm_ranges =
943       range_list_or_error->getAbsoluteRanges(
944           llvm::object::SectionedAddress{GetBaseAddress()},
945           GetAddressByteSize(), [&](uint32_t index) {
946             uint32_t index_size = GetAddressByteSize();
947             dw_offset_t addr_base = GetAddrBase();
948             lldb::offset_t offset = addr_base + index * index_size;
949             return llvm::object::SectionedAddress{
950                 m_dwarf.GetDWARFContext().getOrLoadAddrData().GetMaxU64(
951                     &offset, index_size)};
952           });
953   if (!llvm_ranges)
954     return llvm_ranges.takeError();
955 
956   DWARFRangeList ranges;
957   for (const llvm::DWARFAddressRange &llvm_range : *llvm_ranges) {
958     ranges.Append(DWARFRangeList::Entry(llvm_range.LowPC,
959                                         llvm_range.HighPC - llvm_range.LowPC));
960   }
961   return ranges;
962 }
963 
964 llvm::Expected<DWARFRangeList>
965 DWARFUnit::FindRnglistFromIndex(uint32_t index) {
966   if (llvm::Optional<uint64_t> offset = GetRnglistOffset(index))
967     return FindRnglistFromOffset(*offset);
968   if (m_rnglist_table)
969     return llvm::createStringError(errc::invalid_argument,
970                                    "invalid range list table index %d", index);
971 
972   return llvm::createStringError(errc::invalid_argument,
973                                  "missing or invalid range list table");
974 }
975