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 
39 DWARFUnit::~DWARFUnit() = default;
40 
41 // Parses first DIE of a compile unit.
42 void DWARFUnit::ExtractUnitDIEIfNeeded() {
43   {
44     llvm::sys::ScopedReader lock(m_first_die_mutex);
45     if (m_first_die)
46       return; // Already parsed
47   }
48   llvm::sys::ScopedWriter lock(m_first_die_mutex);
49   if (m_first_die)
50     return; // Already parsed
51 
52   LLDB_SCOPED_TIMERF("%8.8x: DWARFUnit::ExtractUnitDIEIfNeeded()", GetOffset());
53 
54   // Set the offset to that of the first DIE and calculate the start of the
55   // next compilation unit header.
56   lldb::offset_t offset = GetFirstDIEOffset();
57 
58   // We are in our compile unit, parse starting at the offset we were told to
59   // parse
60   const DWARFDataExtractor &data = GetData();
61   if (offset < GetNextUnitOffset() &&
62       m_first_die.Extract(data, this, &offset)) {
63     AddUnitDIE(m_first_die);
64     return;
65   }
66 }
67 
68 // Parses a compile unit and indexes its DIEs if it hasn't already been done.
69 // It will leave this compile unit extracted forever.
70 void DWARFUnit::ExtractDIEsIfNeeded() {
71   m_cancel_scopes = true;
72 
73   {
74     llvm::sys::ScopedReader lock(m_die_array_mutex);
75     if (!m_die_array.empty())
76       return; // Already parsed
77   }
78   llvm::sys::ScopedWriter lock(m_die_array_mutex);
79   if (!m_die_array.empty())
80     return; // Already parsed
81 
82   ExtractDIEsRWLocked();
83 }
84 
85 // Parses a compile unit and indexes its DIEs if it hasn't already been done.
86 // It will clear this compile unit after returned instance gets out of scope,
87 // no other ScopedExtractDIEs instance is running for this compile unit
88 // and no ExtractDIEsIfNeeded() has been executed during this ScopedExtractDIEs
89 // lifetime.
90 DWARFUnit::ScopedExtractDIEs DWARFUnit::ExtractDIEsScoped() {
91   ScopedExtractDIEs scoped(*this);
92 
93   {
94     llvm::sys::ScopedReader lock(m_die_array_mutex);
95     if (!m_die_array.empty())
96       return scoped; // Already parsed
97   }
98   llvm::sys::ScopedWriter lock(m_die_array_mutex);
99   if (!m_die_array.empty())
100     return scoped; // Already parsed
101 
102   // Otherwise m_die_array would be already populated.
103   lldbassert(!m_cancel_scopes);
104 
105   ExtractDIEsRWLocked();
106   scoped.m_clear_dies = true;
107   return scoped;
108 }
109 
110 DWARFUnit::ScopedExtractDIEs::ScopedExtractDIEs(DWARFUnit &cu) : m_cu(&cu) {
111   m_cu->m_die_array_scoped_mutex.lock_shared();
112 }
113 
114 DWARFUnit::ScopedExtractDIEs::~ScopedExtractDIEs() {
115   if (!m_cu)
116     return;
117   m_cu->m_die_array_scoped_mutex.unlock_shared();
118   if (!m_clear_dies || m_cu->m_cancel_scopes)
119     return;
120   // Be sure no other ScopedExtractDIEs is running anymore.
121   llvm::sys::ScopedWriter lock_scoped(m_cu->m_die_array_scoped_mutex);
122   llvm::sys::ScopedWriter lock(m_cu->m_die_array_mutex);
123   if (m_cu->m_cancel_scopes)
124     return;
125   m_cu->ClearDIEsRWLocked();
126 }
127 
128 DWARFUnit::ScopedExtractDIEs::ScopedExtractDIEs(ScopedExtractDIEs &&rhs)
129     : m_cu(rhs.m_cu), m_clear_dies(rhs.m_clear_dies) {
130   rhs.m_cu = nullptr;
131 }
132 
133 DWARFUnit::ScopedExtractDIEs &DWARFUnit::ScopedExtractDIEs::operator=(
134     DWARFUnit::ScopedExtractDIEs &&rhs) {
135   m_cu = rhs.m_cu;
136   rhs.m_cu = nullptr;
137   m_clear_dies = rhs.m_clear_dies;
138   return *this;
139 }
140 
141 // Parses a compile unit and indexes its DIEs, m_die_array_mutex must be
142 // held R/W and m_die_array must be empty.
143 void DWARFUnit::ExtractDIEsRWLocked() {
144   llvm::sys::ScopedWriter first_die_lock(m_first_die_mutex);
145 
146   LLDB_SCOPED_TIMERF("%8.8x: DWARFUnit::ExtractDIEsIfNeeded()", GetOffset());
147 
148   // Set the offset to that of the first DIE and calculate the start of the
149   // next compilation unit header.
150   lldb::offset_t offset = GetFirstDIEOffset();
151   lldb::offset_t next_cu_offset = GetNextUnitOffset();
152 
153   DWARFDebugInfoEntry die;
154 
155   uint32_t depth = 0;
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   die_index_stack.push_back(0);
162   bool prev_die_had_children = false;
163   while (offset < next_cu_offset && die.Extract(data, this, &offset)) {
164     const bool null_die = die.IsNULL();
165     if (depth == 0) {
166       assert(m_die_array.empty() && "Compile unit DIE already added");
167 
168       // The average bytes per DIE entry has been seen to be around 14-20 so
169       // lets pre-reserve half of that since we are now stripping the NULL
170       // tags.
171 
172       // Only reserve the memory if we are adding children of the main
173       // compile unit DIE. The compile unit DIE is always the first entry, so
174       // if our size is 1, then we are adding the first compile unit child
175       // DIE and should reserve the memory.
176       m_die_array.reserve(GetDebugInfoSize() / 24);
177       m_die_array.push_back(die);
178 
179       if (!m_first_die)
180         AddUnitDIE(m_die_array.front());
181 
182       // With -fsplit-dwarf-inlining, clang will emit non-empty skeleton compile
183       // units. We are not able to access these DIE *and* the dwo file
184       // simultaneously. We also don't need to do that as the dwo file will
185       // contain a superset of information. So, we don't even attempt to parse
186       // any remaining DIEs.
187       if (m_dwo) {
188         m_die_array.front().SetHasChildren(false);
189         break;
190       }
191 
192     } else {
193       if (null_die) {
194         if (prev_die_had_children) {
195           // This will only happen if a DIE says is has children but all it
196           // contains is a NULL tag. Since we are removing the NULL DIEs from
197           // the list (saves up to 25% in C++ code), we need a way to let the
198           // DIE know that it actually doesn't have children.
199           if (!m_die_array.empty())
200             m_die_array.back().SetHasChildren(false);
201         }
202       } else {
203         die.SetParentIndex(m_die_array.size() - die_index_stack[depth - 1]);
204 
205         if (die_index_stack.back())
206           m_die_array[die_index_stack.back()].SetSiblingIndex(
207               m_die_array.size() - die_index_stack.back());
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 
219       if (depth > 0)
220         --depth;
221       prev_die_had_children = false;
222     } else {
223       die_index_stack.back() = m_die_array.size() - 1;
224       // Normal DIE
225       const bool die_has_children = die.HasChildren();
226       if (die_has_children) {
227         die_index_stack.push_back(0);
228         ++depth;
229       }
230       prev_die_had_children = die_has_children;
231     }
232 
233     if (depth == 0)
234       break; // We are done with this compile unit!
235   }
236 
237   if (!m_die_array.empty()) {
238     if (m_first_die) {
239       // Only needed for the assertion.
240       m_first_die.SetHasChildren(m_die_array.front().HasChildren());
241       lldbassert(m_first_die == m_die_array.front());
242     }
243     m_first_die = m_die_array.front();
244   }
245 
246   m_die_array.shrink_to_fit();
247 
248   if (m_dwo)
249     m_dwo->ExtractDIEsIfNeeded();
250 }
251 
252 // This is used when a split dwarf is enabled.
253 // A skeleton compilation unit may contain the DW_AT_str_offsets_base attribute
254 // that points to the first string offset of the CU contribution to the
255 // .debug_str_offsets. At the same time, the corresponding split debug unit also
256 // may use DW_FORM_strx* forms pointing to its own .debug_str_offsets.dwo and
257 // for that case, we should find the offset (skip the section header).
258 void DWARFUnit::SetDwoStrOffsetsBase() {
259   lldb::offset_t baseOffset = 0;
260 
261   if (const llvm::DWARFUnitIndex::Entry *entry = m_header.GetIndexEntry()) {
262     if (const auto *contribution =
263             entry->getContribution(llvm::DW_SECT_STR_OFFSETS))
264       baseOffset = contribution->Offset;
265     else
266       return;
267   }
268 
269   if (GetVersion() >= 5) {
270     const DWARFDataExtractor &strOffsets =
271         GetSymbolFileDWARF().GetDWARFContext().getOrLoadStrOffsetsData();
272     uint64_t length = strOffsets.GetU32(&baseOffset);
273     if (length == 0xffffffff)
274       length = strOffsets.GetU64(&baseOffset);
275 
276     // Check version.
277     if (strOffsets.GetU16(&baseOffset) < 5)
278       return;
279 
280     // Skip padding.
281     baseOffset += 2;
282   }
283 
284   SetStrOffsetsBase(baseOffset);
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, ranges_base,
290       gnu_ranges_base;
291 
292   DWARFAttributes attributes;
293   size_t num_attributes = cu_die.GetAttributes(this, attributes);
294 
295   // Extract DW_AT_addr_base first, as other attributes may need it.
296   for (size_t i = 0; i < num_attributes; ++i) {
297     if (attributes.AttributeAtIndex(i) != DW_AT_addr_base)
298       continue;
299     DWARFFormValue form_value;
300     if (attributes.ExtractFormValueAtIndex(i, form_value)) {
301       addr_base = form_value.Unsigned();
302       SetAddrBase(*addr_base);
303       break;
304     }
305   }
306 
307   for (size_t i = 0; i < num_attributes; ++i) {
308     dw_attr_t attr = attributes.AttributeAtIndex(i);
309     DWARFFormValue form_value;
310     if (!attributes.ExtractFormValueAtIndex(i, form_value))
311       continue;
312     switch (attr) {
313     case DW_AT_loclists_base:
314       SetLoclistsBase(form_value.Unsigned());
315       break;
316     case DW_AT_rnglists_base:
317       ranges_base = form_value.Unsigned();
318       SetRangesBase(*ranges_base);
319       break;
320     case DW_AT_str_offsets_base:
321       SetStrOffsetsBase(form_value.Unsigned());
322       break;
323     case DW_AT_low_pc:
324       SetBaseAddress(form_value.Address());
325       break;
326     case DW_AT_entry_pc:
327       // If the value was already set by DW_AT_low_pc, don't update it.
328       if (m_base_addr == LLDB_INVALID_ADDRESS)
329         SetBaseAddress(form_value.Address());
330       break;
331     case DW_AT_stmt_list:
332       m_line_table_offset = form_value.Unsigned();
333       break;
334     case DW_AT_GNU_addr_base:
335       gnu_addr_base = form_value.Unsigned();
336       break;
337     case DW_AT_GNU_ranges_base:
338       gnu_ranges_base = form_value.Unsigned();
339       break;
340     }
341   }
342 
343   if (m_is_dwo) {
344     SetDwoStrOffsetsBase();
345     return;
346   }
347 
348   std::shared_ptr<SymbolFileDWARFDwo> dwo_symbol_file =
349       m_dwarf.GetDwoSymbolFileForCompileUnit(*this, cu_die);
350   if (!dwo_symbol_file)
351     return;
352 
353   uint64_t main_dwo_id =
354       cu_die.GetAttributeValueAsUnsigned(this, DW_AT_GNU_dwo_id, 0);
355   DWARFUnit *dwo_cu = dwo_symbol_file->GetDWOCompileUnitForHash(main_dwo_id);
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, lldb::offset_t *offset_ptr,
780                          const llvm::DWARFUnitIndex *index) {
781   DWARFUnitHeader header;
782   header.m_offset = *offset_ptr;
783   if (index)
784     header.m_index_entry = index->getFromOffset(*offset_ptr);
785   header.m_length = data.GetDWARFInitialLength(offset_ptr);
786   header.m_version = data.GetU16(offset_ptr);
787   if (header.m_version == 5) {
788     header.m_unit_type = data.GetU8(offset_ptr);
789     header.m_addr_size = data.GetU8(offset_ptr);
790     header.m_abbr_offset = data.GetDWARFOffset(offset_ptr);
791     if (header.m_unit_type == llvm::dwarf::DW_UT_skeleton)
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 (header.m_index_entry) {
801     if (header.m_abbr_offset) {
802       return llvm::createStringError(
803           llvm::inconvertibleErrorCode(),
804           "Package unit with a non-zero abbreviation offset");
805     }
806     auto *unit_contrib = header.m_index_entry->getContribution();
807     if (!unit_contrib || unit_contrib->Length != header.m_length + 4) {
808       return llvm::createStringError(llvm::inconvertibleErrorCode(),
809                                      "Inconsistent DWARF package unit index");
810     }
811     auto *abbr_entry =
812         header.m_index_entry->getContribution(llvm::DW_SECT_ABBREV);
813     if (!abbr_entry) {
814       return llvm::createStringError(
815           llvm::inconvertibleErrorCode(),
816           "DWARF package index missing abbreviation column");
817     }
818     header.m_abbr_offset = abbr_entry->Offset;
819   }
820   if (header.IsTypeUnit()) {
821     header.m_type_hash = data.GetU64(offset_ptr);
822     header.m_type_offset = data.GetDWARFOffset(offset_ptr);
823   }
824 
825   bool length_OK = data.ValidOffset(header.GetNextUnitOffset() - 1);
826   bool version_OK = SymbolFileDWARF::SupportedVersion(header.m_version);
827   bool addr_size_OK = (header.m_addr_size == 4) || (header.m_addr_size == 8);
828   bool type_offset_OK =
829       !header.IsTypeUnit() || (header.m_type_offset <= header.GetLength());
830 
831   if (!length_OK)
832     return llvm::make_error<llvm::object::GenericBinaryError>(
833         "Invalid unit length");
834   if (!version_OK)
835     return llvm::make_error<llvm::object::GenericBinaryError>(
836         "Unsupported unit version");
837   if (!addr_size_OK)
838     return llvm::make_error<llvm::object::GenericBinaryError>(
839         "Invalid unit address size");
840   if (!type_offset_OK)
841     return llvm::make_error<llvm::object::GenericBinaryError>(
842         "Type offset out of range");
843 
844   return header;
845 }
846 
847 llvm::Expected<DWARFUnitSP>
848 DWARFUnit::extract(SymbolFileDWARF &dwarf, user_id_t uid,
849                    const DWARFDataExtractor &debug_info,
850                    DIERef::Section section, lldb::offset_t *offset_ptr,
851                    const llvm::DWARFUnitIndex *index) {
852   assert(debug_info.ValidOffset(*offset_ptr));
853 
854   auto expected_header =
855       DWARFUnitHeader::extract(debug_info, section, offset_ptr, index);
856   if (!expected_header)
857     return expected_header.takeError();
858 
859   const DWARFDebugAbbrev *abbr = dwarf.DebugAbbrev();
860   if (!abbr)
861     return llvm::make_error<llvm::object::GenericBinaryError>(
862         "No debug_abbrev data");
863 
864   bool abbr_offset_OK =
865       dwarf.GetDWARFContext().getOrLoadAbbrevData().ValidOffset(
866           expected_header->GetAbbrOffset());
867   if (!abbr_offset_OK)
868     return llvm::make_error<llvm::object::GenericBinaryError>(
869         "Abbreviation offset for unit is not valid");
870 
871   const DWARFAbbreviationDeclarationSet *abbrevs =
872       abbr->GetAbbreviationDeclarationSet(expected_header->GetAbbrOffset());
873   if (!abbrevs)
874     return llvm::make_error<llvm::object::GenericBinaryError>(
875         "No abbrev exists at the specified offset.");
876 
877   bool is_dwo = dwarf.GetDWARFContext().isDwo();
878   if (expected_header->IsTypeUnit())
879     return DWARFUnitSP(new DWARFTypeUnit(dwarf, uid, *expected_header, *abbrevs,
880                                          section, is_dwo));
881   return DWARFUnitSP(new DWARFCompileUnit(dwarf, uid, *expected_header,
882                                           *abbrevs, section, is_dwo));
883 }
884 
885 const lldb_private::DWARFDataExtractor &DWARFUnit::GetData() const {
886   return m_section == DIERef::Section::DebugTypes
887              ? m_dwarf.GetDWARFContext().getOrLoadDebugTypesData()
888              : m_dwarf.GetDWARFContext().getOrLoadDebugInfoData();
889 }
890 
891 uint32_t DWARFUnit::GetHeaderByteSize() const {
892   switch (m_header.GetUnitType()) {
893   case llvm::dwarf::DW_UT_compile:
894   case llvm::dwarf::DW_UT_partial:
895     return GetVersion() < 5 ? 11 : 12;
896   case llvm::dwarf::DW_UT_skeleton:
897   case llvm::dwarf::DW_UT_split_compile:
898     return 20;
899   case llvm::dwarf::DW_UT_type:
900   case llvm::dwarf::DW_UT_split_type:
901     return GetVersion() < 5 ? 23 : 24;
902   }
903   llvm_unreachable("invalid UnitType.");
904 }
905 
906 llvm::Optional<uint64_t>
907 DWARFUnit::GetStringOffsetSectionItem(uint32_t index) const {
908   offset_t offset = GetStrOffsetsBase() + index * 4;
909   return m_dwarf.GetDWARFContext().getOrLoadStrOffsetsData().GetU32(&offset);
910 }
911 
912 llvm::Expected<DWARFRangeList>
913 DWARFUnit::FindRnglistFromOffset(dw_offset_t offset) {
914   if (GetVersion() <= 4) {
915     const DWARFDebugRanges *debug_ranges = m_dwarf.GetDebugRanges();
916     if (!debug_ranges)
917       return llvm::make_error<llvm::object::GenericBinaryError>(
918           "No debug_ranges section");
919     DWARFRangeList ranges;
920     debug_ranges->FindRanges(this, offset, ranges);
921     return ranges;
922   }
923 
924   if (!m_rnglist_table)
925     return llvm::createStringError(errc::invalid_argument,
926                                    "missing or invalid range list table");
927 
928   auto range_list_or_error = m_rnglist_table->findList(
929       m_dwarf.GetDWARFContext().getOrLoadRngListsData().GetAsLLVM(), offset);
930   if (!range_list_or_error)
931     return range_list_or_error.takeError();
932 
933   llvm::Expected<llvm::DWARFAddressRangesVector> llvm_ranges =
934       range_list_or_error->getAbsoluteRanges(
935           llvm::object::SectionedAddress{GetBaseAddress()},
936           GetAddressByteSize(), [&](uint32_t index) {
937             uint32_t index_size = GetAddressByteSize();
938             dw_offset_t addr_base = GetAddrBase();
939             lldb::offset_t offset = addr_base + index * index_size;
940             return llvm::object::SectionedAddress{
941                 m_dwarf.GetDWARFContext().getOrLoadAddrData().GetMaxU64(
942                     &offset, index_size)};
943           });
944   if (!llvm_ranges)
945     return llvm_ranges.takeError();
946 
947   DWARFRangeList ranges;
948   for (const llvm::DWARFAddressRange &llvm_range : *llvm_ranges) {
949     ranges.Append(DWARFRangeList::Entry(llvm_range.LowPC,
950                                         llvm_range.HighPC - llvm_range.LowPC));
951   }
952   return ranges;
953 }
954 
955 llvm::Expected<DWARFRangeList>
956 DWARFUnit::FindRnglistFromIndex(uint32_t index) {
957   if (llvm::Optional<uint64_t> offset = GetRnglistOffset(index))
958     return FindRnglistFromOffset(*offset);
959   if (m_rnglist_table)
960     return llvm::createStringError(errc::invalid_argument,
961                                    "invalid range list table index %d", index);
962 
963   return llvm::createStringError(errc::invalid_argument,
964                                  "missing or invalid range list table");
965 }
966