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