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