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