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