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