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