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