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 
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) {
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)
253     m_dwo->ExtractDIEsIfNeeded();
254 }
255 
256 // This is used when a split dwarf is enabled.
257 // A skeleton compilation unit may contain the DW_AT_str_offsets_base attribute
258 // that points to the first string offset of the CU contribution to the
259 // .debug_str_offsets. At the same time, the corresponding split debug unit also
260 // may use DW_FORM_strx* forms pointing to its own .debug_str_offsets.dwo and
261 // for that case, we should find the offset (skip the section header).
262 void DWARFUnit::SetDwoStrOffsetsBase() {
263   lldb::offset_t baseOffset = 0;
264 
265   if (const llvm::DWARFUnitIndex::Entry *entry = m_header.GetIndexEntry()) {
266     if (const auto *contribution = entry->getOffset(llvm::DW_SECT_STR_OFFSETS))
267       baseOffset = contribution->Offset;
268     else
269       return;
270   }
271 
272   if (GetVersion() >= 5) {
273     const DWARFDataExtractor &strOffsets =
274         GetSymbolFileDWARF().GetDWARFContext().getOrLoadStrOffsetsData();
275     uint64_t length = strOffsets.GetU32(&baseOffset);
276     if (length == 0xffffffff)
277       length = strOffsets.GetU64(&baseOffset);
278 
279     // Check version.
280     if (strOffsets.GetU16(&baseOffset) < 5)
281       return;
282 
283     // Skip padding.
284     baseOffset += 2;
285   }
286 
287   SetStrOffsetsBase(baseOffset);
288 }
289 
290 // m_die_array_mutex must be already held as read/write.
291 void DWARFUnit::AddUnitDIE(const DWARFDebugInfoEntry &cu_die) {
292   llvm::Optional<uint64_t> addr_base, gnu_addr_base, ranges_base,
293       gnu_ranges_base;
294 
295   DWARFAttributes attributes;
296   size_t num_attributes = cu_die.GetAttributes(this, attributes);
297 
298   // Extract DW_AT_addr_base first, as other attributes may need it.
299   for (size_t i = 0; i < num_attributes; ++i) {
300     if (attributes.AttributeAtIndex(i) != DW_AT_addr_base)
301       continue;
302     DWARFFormValue form_value;
303     if (attributes.ExtractFormValueAtIndex(i, form_value)) {
304       addr_base = form_value.Unsigned();
305       SetAddrBase(*addr_base);
306       break;
307     }
308   }
309 
310   for (size_t i = 0; i < num_attributes; ++i) {
311     dw_attr_t attr = attributes.AttributeAtIndex(i);
312     DWARFFormValue form_value;
313     if (!attributes.ExtractFormValueAtIndex(i, form_value))
314       continue;
315     switch (attr) {
316     case DW_AT_loclists_base:
317       SetLoclistsBase(form_value.Unsigned());
318       break;
319     case DW_AT_rnglists_base:
320       ranges_base = form_value.Unsigned();
321       SetRangesBase(*ranges_base);
322       break;
323     case DW_AT_str_offsets_base:
324       SetStrOffsetsBase(form_value.Unsigned());
325       break;
326     case DW_AT_low_pc:
327       SetBaseAddress(form_value.Address());
328       break;
329     case DW_AT_entry_pc:
330       // If the value was already set by DW_AT_low_pc, don't update it.
331       if (m_base_addr == LLDB_INVALID_ADDRESS)
332         SetBaseAddress(form_value.Address());
333       break;
334     case DW_AT_stmt_list:
335       m_line_table_offset = form_value.Unsigned();
336       break;
337     case DW_AT_GNU_addr_base:
338       gnu_addr_base = form_value.Unsigned();
339       break;
340     case DW_AT_GNU_ranges_base:
341       gnu_ranges_base = form_value.Unsigned();
342       break;
343     }
344   }
345 
346   if (m_is_dwo) {
347     SetDwoStrOffsetsBase();
348     return;
349   }
350 
351   std::shared_ptr<SymbolFileDWARFDwo> dwo_symbol_file =
352       m_dwarf.GetDwoSymbolFileForCompileUnit(*this, cu_die);
353   if (!dwo_symbol_file)
354     return;
355 
356   uint64_t main_dwo_id =
357       cu_die.GetAttributeValueAsUnsigned(this, DW_AT_GNU_dwo_id, 0);
358   DWARFUnit *dwo_cu = dwo_symbol_file->GetDWOCompileUnitForHash(main_dwo_id);
359   if (!dwo_cu)
360     return; // Can't fetch the compile unit from the dwo file.
361   dwo_cu->SetUserData(this);
362 
363   DWARFBaseDIE dwo_cu_die = dwo_cu->GetUnitDIEOnly();
364   if (!dwo_cu_die.IsValid())
365     return; // Can't fetch the compile unit DIE from the dwo file.
366 
367   // Here for DWO CU we want to use the address base set in the skeleton unit
368   // (DW_AT_addr_base) if it is available and use the DW_AT_GNU_addr_base
369   // otherwise. We do that because pre-DWARF v5 could use the DW_AT_GNU_*
370   // attributes which were applicable to the DWO units. The corresponding
371   // DW_AT_* attributes standardized in DWARF v5 are also applicable to the main
372   // unit in contrast.
373   if (addr_base)
374     dwo_cu->SetAddrBase(*addr_base);
375   else if (gnu_addr_base)
376     dwo_cu->SetAddrBase(*gnu_addr_base);
377 
378   if (GetVersion() <= 4 && gnu_ranges_base)
379     dwo_cu->SetRangesBase(*gnu_ranges_base);
380   else if (dwo_symbol_file->GetDWARFContext()
381                .getOrLoadRngListsData()
382                .GetByteSize() > 0)
383     dwo_cu->SetRangesBase(llvm::DWARFListTableHeader::getHeaderSize(DWARF32));
384 
385   if (GetVersion() >= 5 &&
386       dwo_symbol_file->GetDWARFContext().getOrLoadLocListsData().GetByteSize() >
387           0)
388     dwo_cu->SetLoclistsBase(llvm::DWARFListTableHeader::getHeaderSize(DWARF32));
389   dwo_cu->SetBaseAddress(GetBaseAddress());
390 
391   m_dwo = std::shared_ptr<DWARFUnit>(std::move(dwo_symbol_file), dwo_cu);
392 }
393 
394 DWARFDIE DWARFUnit::LookupAddress(const dw_addr_t address) {
395   if (DIE()) {
396     const DWARFDebugAranges &func_aranges = GetFunctionAranges();
397 
398     // Re-check the aranges auto pointer contents in case it was created above
399     if (!func_aranges.IsEmpty())
400       return GetDIE(func_aranges.FindAddress(address));
401   }
402   return DWARFDIE();
403 }
404 
405 size_t DWARFUnit::GetDebugInfoSize() const {
406   return GetLengthByteSize() + GetLength() - GetHeaderByteSize();
407 }
408 
409 const DWARFAbbreviationDeclarationSet *DWARFUnit::GetAbbreviations() const {
410   return m_abbrevs;
411 }
412 
413 dw_offset_t DWARFUnit::GetAbbrevOffset() const {
414   return m_abbrevs ? m_abbrevs->GetOffset() : DW_INVALID_OFFSET;
415 }
416 
417 dw_offset_t DWARFUnit::GetLineTableOffset() {
418   ExtractUnitDIEIfNeeded();
419   return m_line_table_offset;
420 }
421 
422 void DWARFUnit::SetAddrBase(dw_addr_t addr_base) { m_addr_base = addr_base; }
423 
424 // Parse the rangelist table header, including the optional array of offsets
425 // following it (DWARF v5 and later).
426 template <typename ListTableType>
427 static llvm::Expected<ListTableType>
428 ParseListTableHeader(const llvm::DWARFDataExtractor &data, uint64_t offset,
429                      DwarfFormat format) {
430   // We are expected to be called with Offset 0 or pointing just past the table
431   // header. Correct Offset in the latter case so that it points to the start
432   // of the header.
433   if (offset > 0) {
434     uint64_t HeaderSize = llvm::DWARFListTableHeader::getHeaderSize(format);
435     if (offset < HeaderSize)
436       return llvm::createStringError(errc::invalid_argument,
437                                      "did not detect a valid"
438                                      " list table with base = 0x%" PRIx64 "\n",
439                                      offset);
440     offset -= HeaderSize;
441   }
442   ListTableType Table;
443   if (llvm::Error E = Table.extractHeaderAndOffsets(data, &offset))
444     return std::move(E);
445   return Table;
446 }
447 
448 void DWARFUnit::SetLoclistsBase(dw_addr_t loclists_base) {
449   m_loclists_base = loclists_base;
450 
451   uint64_t header_size = llvm::DWARFListTableHeader::getHeaderSize(DWARF32);
452   if (loclists_base < header_size)
453     return;
454 
455   m_loclist_table_header.emplace(".debug_loclists", "locations");
456   uint64_t offset = loclists_base - header_size;
457   if (llvm::Error E = m_loclist_table_header->extract(
458           m_dwarf.GetDWARFContext().getOrLoadLocListsData().GetAsLLVM(),
459           &offset)) {
460     GetSymbolFileDWARF().GetObjectFile()->GetModule()->ReportError(
461         "Failed to extract location list table at offset 0x%" PRIx64 ": %s",
462         loclists_base, toString(std::move(E)).c_str());
463   }
464 }
465 
466 std::unique_ptr<llvm::DWARFLocationTable>
467 DWARFUnit::GetLocationTable(const DataExtractor &data) const {
468   llvm::DWARFDataExtractor llvm_data(
469       data.GetData(), data.GetByteOrder() == lldb::eByteOrderLittle,
470       data.GetAddressByteSize());
471 
472   if (m_is_dwo || GetVersion() >= 5)
473     return std::make_unique<llvm::DWARFDebugLoclists>(llvm_data, GetVersion());
474   return std::make_unique<llvm::DWARFDebugLoc>(llvm_data);
475 }
476 
477 DWARFDataExtractor DWARFUnit::GetLocationData() const {
478   DWARFContext &Ctx = GetSymbolFileDWARF().GetDWARFContext();
479   const DWARFDataExtractor &data =
480       GetVersion() >= 5 ? Ctx.getOrLoadLocListsData() : Ctx.getOrLoadLocData();
481   if (const llvm::DWARFUnitIndex::Entry *entry = m_header.GetIndexEntry()) {
482     if (const auto *contribution = entry->getOffset(llvm::DW_SECT_LOC))
483       return DWARFDataExtractor(data, contribution->Offset,
484                                 contribution->Length);
485     return DWARFDataExtractor();
486   }
487   return data;
488 }
489 
490 void DWARFUnit::SetRangesBase(dw_addr_t ranges_base) {
491   m_ranges_base = ranges_base;
492 
493   if (GetVersion() < 5)
494     return;
495 
496   if (auto table_or_error = ParseListTableHeader<llvm::DWARFDebugRnglistTable>(
497           m_dwarf.GetDWARFContext().getOrLoadRngListsData().GetAsLLVM(),
498           ranges_base, DWARF32))
499     m_rnglist_table = std::move(table_or_error.get());
500   else
501     GetSymbolFileDWARF().GetObjectFile()->GetModule()->ReportError(
502         "Failed to extract range list table at offset 0x%" PRIx64 ": %s",
503         ranges_base, toString(table_or_error.takeError()).c_str());
504 }
505 
506 void DWARFUnit::SetStrOffsetsBase(dw_offset_t str_offsets_base) {
507   m_str_offsets_base = str_offsets_base;
508 }
509 
510 // It may be called only with m_die_array_mutex held R/W.
511 void DWARFUnit::ClearDIEsRWLocked() {
512   m_die_array.clear();
513   m_die_array.shrink_to_fit();
514 
515   if (m_dwo)
516     m_dwo->ClearDIEsRWLocked();
517 }
518 
519 lldb::ByteOrder DWARFUnit::GetByteOrder() const {
520   return m_dwarf.GetObjectFile()->GetByteOrder();
521 }
522 
523 void DWARFUnit::SetBaseAddress(dw_addr_t base_addr) { m_base_addr = base_addr; }
524 
525 // Compare function DWARFDebugAranges::Range structures
526 static bool CompareDIEOffset(const DWARFDebugInfoEntry &die,
527                              const dw_offset_t die_offset) {
528   return die.GetOffset() < die_offset;
529 }
530 
531 // GetDIE()
532 //
533 // Get the DIE (Debug Information Entry) with the specified offset by first
534 // checking if the DIE is contained within this compile unit and grabbing the
535 // DIE from this compile unit. Otherwise we grab the DIE from the DWARF file.
536 DWARFDIE
537 DWARFUnit::GetDIE(dw_offset_t die_offset) {
538   if (die_offset != DW_INVALID_OFFSET) {
539     if (ContainsDIEOffset(die_offset)) {
540       ExtractDIEsIfNeeded();
541       DWARFDebugInfoEntry::const_iterator end = m_die_array.cend();
542       DWARFDebugInfoEntry::const_iterator pos =
543           lower_bound(m_die_array.cbegin(), end, die_offset, CompareDIEOffset);
544       if (pos != end) {
545         if (die_offset == (*pos).GetOffset())
546           return DWARFDIE(this, &(*pos));
547       }
548     } else
549       GetSymbolFileDWARF().GetObjectFile()->GetModule()->ReportError(
550           "GetDIE for DIE 0x%" PRIx32 " is outside of its CU 0x%" PRIx32,
551           die_offset, GetOffset());
552   }
553   return DWARFDIE(); // Not found
554 }
555 
556 DWARFUnit &DWARFUnit::GetNonSkeletonUnit() {
557   ExtractUnitDIEIfNeeded();
558   if (m_dwo)
559     return *m_dwo;
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) { m_user_data = d; }
574 
575 bool DWARFUnit::Supports_DW_AT_APPLE_objc_complete_type() {
576   return GetProducer() != eProducerLLVMGCC;
577 }
578 
579 bool DWARFUnit::DW_AT_decl_file_attributes_are_invalid() {
580   // llvm-gcc makes completely invalid decl file attributes and won't ever be
581   // fixed, so we need to know to ignore these.
582   return GetProducer() == eProducerLLVMGCC;
583 }
584 
585 bool DWARFUnit::Supports_unnamed_objc_bitfields() {
586   if (GetProducer() == eProducerClang) {
587     const uint32_t major_version = GetProducerVersionMajor();
588     return major_version > 425 ||
589            (major_version == 425 && GetProducerVersionUpdate() >= 13);
590   }
591   return true; // Assume all other compilers didn't have incorrect ObjC bitfield
592                // info
593 }
594 
595 void DWARFUnit::ParseProducerInfo() {
596   m_producer_version_major = UINT32_MAX;
597   m_producer_version_minor = UINT32_MAX;
598   m_producer_version_update = UINT32_MAX;
599 
600   const DWARFDebugInfoEntry *die = GetUnitDIEPtrOnly();
601   if (die) {
602 
603     const char *producer_cstr =
604         die->GetAttributeValueAsString(this, DW_AT_producer, nullptr);
605     if (producer_cstr) {
606       RegularExpression llvm_gcc_regex(
607           llvm::StringRef("^4\\.[012]\\.[01] \\(Based on Apple "
608                           "Inc\\. build [0-9]+\\) \\(LLVM build "
609                           "[\\.0-9]+\\)$"));
610       if (llvm_gcc_regex.Execute(llvm::StringRef(producer_cstr))) {
611         m_producer = eProducerLLVMGCC;
612       } else if (strstr(producer_cstr, "clang")) {
613         static RegularExpression g_clang_version_regex(
614             llvm::StringRef("clang-([0-9]+)\\.([0-9]+)\\.([0-9]+)"));
615         llvm::SmallVector<llvm::StringRef, 4> matches;
616         if (g_clang_version_regex.Execute(llvm::StringRef(producer_cstr),
617                                           &matches)) {
618           m_producer_version_major =
619               StringConvert::ToUInt32(matches[1].str().c_str(), UINT32_MAX, 10);
620           m_producer_version_minor =
621               StringConvert::ToUInt32(matches[2].str().c_str(), UINT32_MAX, 10);
622           m_producer_version_update =
623               StringConvert::ToUInt32(matches[3].str().c_str(), UINT32_MAX, 10);
624         }
625         m_producer = eProducerClang;
626       } else if (strstr(producer_cstr, "GNU"))
627         m_producer = eProducerGCC;
628     }
629   }
630   if (m_producer == eProducerInvalid)
631     m_producer = eProcucerOther;
632 }
633 
634 DWARFProducer DWARFUnit::GetProducer() {
635   if (m_producer == eProducerInvalid)
636     ParseProducerInfo();
637   return m_producer;
638 }
639 
640 uint32_t DWARFUnit::GetProducerVersionMajor() {
641   if (m_producer_version_major == 0)
642     ParseProducerInfo();
643   return m_producer_version_major;
644 }
645 
646 uint32_t DWARFUnit::GetProducerVersionMinor() {
647   if (m_producer_version_minor == 0)
648     ParseProducerInfo();
649   return m_producer_version_minor;
650 }
651 
652 uint32_t DWARFUnit::GetProducerVersionUpdate() {
653   if (m_producer_version_update == 0)
654     ParseProducerInfo();
655   return m_producer_version_update;
656 }
657 
658 uint64_t DWARFUnit::GetDWARFLanguageType() {
659   if (m_language_type)
660     return *m_language_type;
661 
662   const DWARFDebugInfoEntry *die = GetUnitDIEPtrOnly();
663   if (!die)
664     m_language_type = 0;
665   else
666     m_language_type = die->GetAttributeValueAsUnsigned(this, DW_AT_language, 0);
667   return *m_language_type;
668 }
669 
670 bool DWARFUnit::GetIsOptimized() {
671   if (m_is_optimized == eLazyBoolCalculate) {
672     const DWARFDebugInfoEntry *die = GetUnitDIEPtrOnly();
673     if (die) {
674       m_is_optimized = eLazyBoolNo;
675       if (die->GetAttributeValueAsUnsigned(this, DW_AT_APPLE_optimized, 0) ==
676           1) {
677         m_is_optimized = eLazyBoolYes;
678       }
679     }
680   }
681   return m_is_optimized == eLazyBoolYes;
682 }
683 
684 FileSpec::Style DWARFUnit::GetPathStyle() {
685   if (!m_comp_dir)
686     ComputeCompDirAndGuessPathStyle();
687   return m_comp_dir->GetPathStyle();
688 }
689 
690 const FileSpec &DWARFUnit::GetCompilationDirectory() {
691   if (!m_comp_dir)
692     ComputeCompDirAndGuessPathStyle();
693   return *m_comp_dir;
694 }
695 
696 const FileSpec &DWARFUnit::GetAbsolutePath() {
697   if (!m_file_spec)
698     ComputeAbsolutePath();
699   return *m_file_spec;
700 }
701 
702 FileSpec DWARFUnit::GetFile(size_t file_idx) {
703   return m_dwarf.GetFile(*this, file_idx);
704 }
705 
706 // DWARF2/3 suggests the form hostname:pathname for compilation directory.
707 // Remove the host part if present.
708 static llvm::StringRef
709 removeHostnameFromPathname(llvm::StringRef path_from_dwarf) {
710   if (!path_from_dwarf.contains(':'))
711     return path_from_dwarf;
712   llvm::StringRef host, path;
713   std::tie(host, path) = path_from_dwarf.split(':');
714 
715   if (host.contains('/'))
716     return path_from_dwarf;
717 
718   // check whether we have a windows path, and so the first character is a
719   // drive-letter not a hostname.
720   if (host.size() == 1 && llvm::isAlpha(host[0]) && path.startswith("\\"))
721     return path_from_dwarf;
722 
723   return path;
724 }
725 
726 void DWARFUnit::ComputeCompDirAndGuessPathStyle() {
727   m_comp_dir = FileSpec();
728   const DWARFDebugInfoEntry *die = GetUnitDIEPtrOnly();
729   if (!die)
730     return;
731 
732   llvm::StringRef comp_dir = removeHostnameFromPathname(
733       die->GetAttributeValueAsString(this, DW_AT_comp_dir, nullptr));
734   if (!comp_dir.empty()) {
735     FileSpec::Style comp_dir_style =
736         FileSpec::GuessPathStyle(comp_dir).getValueOr(FileSpec::Style::native);
737     m_comp_dir = FileSpec(comp_dir, comp_dir_style);
738   } else {
739     // Try to detect the style based on the DW_AT_name attribute, but just store
740     // the detected style in the m_comp_dir field.
741     const char *name =
742         die->GetAttributeValueAsString(this, DW_AT_name, nullptr);
743     m_comp_dir = FileSpec(
744         "", FileSpec::GuessPathStyle(name).getValueOr(FileSpec::Style::native));
745   }
746 }
747 
748 void DWARFUnit::ComputeAbsolutePath() {
749   m_file_spec = FileSpec();
750   const DWARFDebugInfoEntry *die = GetUnitDIEPtrOnly();
751   if (!die)
752     return;
753 
754   m_file_spec =
755       FileSpec(die->GetAttributeValueAsString(this, DW_AT_name, nullptr),
756                GetPathStyle());
757 
758   if (m_file_spec->IsRelative())
759     m_file_spec->MakeAbsolute(GetCompilationDirectory());
760 }
761 
762 SymbolFileDWARFDwo *DWARFUnit::GetDwoSymbolFile() {
763   ExtractUnitDIEIfNeeded();
764   if (m_dwo)
765     return &llvm::cast<SymbolFileDWARFDwo>(m_dwo->GetSymbolFileDWARF());
766   return nullptr;
767 }
768 
769 const DWARFDebugAranges &DWARFUnit::GetFunctionAranges() {
770   if (m_func_aranges_up == nullptr) {
771     m_func_aranges_up.reset(new DWARFDebugAranges());
772     const DWARFDebugInfoEntry *die = DIEPtr();
773     if (die)
774       die->BuildFunctionAddressRangeTable(this, m_func_aranges_up.get());
775 
776     if (m_dwo) {
777       const DWARFDebugInfoEntry *dwo_die = m_dwo->DIEPtr();
778       if (dwo_die)
779         dwo_die->BuildFunctionAddressRangeTable(m_dwo.get(),
780                                                 m_func_aranges_up.get());
781     }
782 
783     const bool minimize = false;
784     m_func_aranges_up->Sort(minimize);
785   }
786   return *m_func_aranges_up;
787 }
788 
789 llvm::Expected<DWARFUnitHeader>
790 DWARFUnitHeader::extract(const DWARFDataExtractor &data,
791                          DIERef::Section section, lldb::offset_t *offset_ptr,
792                          const llvm::DWARFUnitIndex *index) {
793   DWARFUnitHeader header;
794   header.m_offset = *offset_ptr;
795   if (index)
796     header.m_index_entry = index->getFromOffset(*offset_ptr);
797   header.m_length = data.GetDWARFInitialLength(offset_ptr);
798   header.m_version = data.GetU16(offset_ptr);
799   if (header.m_version == 5) {
800     header.m_unit_type = data.GetU8(offset_ptr);
801     header.m_addr_size = data.GetU8(offset_ptr);
802     header.m_abbr_offset = data.GetDWARFOffset(offset_ptr);
803     if (header.m_unit_type == llvm::dwarf::DW_UT_skeleton)
804       header.m_dwo_id = data.GetU64(offset_ptr);
805   } else {
806     header.m_abbr_offset = data.GetDWARFOffset(offset_ptr);
807     header.m_addr_size = data.GetU8(offset_ptr);
808     header.m_unit_type =
809         section == DIERef::Section::DebugTypes ? DW_UT_type : DW_UT_compile;
810   }
811 
812   if (header.m_index_entry) {
813     if (header.m_abbr_offset) {
814       return llvm::createStringError(
815           llvm::inconvertibleErrorCode(),
816           "Package unit with a non-zero abbreviation offset");
817     }
818     auto *unit_contrib = header.m_index_entry->getOffset();
819     if (!unit_contrib || unit_contrib->Length != header.m_length + 4) {
820       return llvm::createStringError(llvm::inconvertibleErrorCode(),
821                                      "Inconsistent DWARF package unit index");
822     }
823     auto *abbr_entry = header.m_index_entry->getOffset(llvm::DW_SECT_ABBREV);
824     if (!abbr_entry) {
825       return llvm::createStringError(
826           llvm::inconvertibleErrorCode(),
827           "DWARF package index missing abbreviation column");
828     }
829     header.m_abbr_offset = abbr_entry->Offset;
830   }
831   if (header.IsTypeUnit()) {
832     header.m_type_hash = data.GetU64(offset_ptr);
833     header.m_type_offset = data.GetDWARFOffset(offset_ptr);
834   }
835 
836   bool length_OK = data.ValidOffset(header.GetNextUnitOffset() - 1);
837   bool version_OK = SymbolFileDWARF::SupportedVersion(header.m_version);
838   bool addr_size_OK = (header.m_addr_size == 4) || (header.m_addr_size == 8);
839   bool type_offset_OK =
840       !header.IsTypeUnit() || (header.m_type_offset <= header.GetLength());
841 
842   if (!length_OK)
843     return llvm::make_error<llvm::object::GenericBinaryError>(
844         "Invalid unit length");
845   if (!version_OK)
846     return llvm::make_error<llvm::object::GenericBinaryError>(
847         "Unsupported unit version");
848   if (!addr_size_OK)
849     return llvm::make_error<llvm::object::GenericBinaryError>(
850         "Invalid unit address size");
851   if (!type_offset_OK)
852     return llvm::make_error<llvm::object::GenericBinaryError>(
853         "Type offset out of range");
854 
855   return header;
856 }
857 
858 llvm::Expected<DWARFUnitSP>
859 DWARFUnit::extract(SymbolFileDWARF &dwarf, user_id_t uid,
860                    const DWARFDataExtractor &debug_info,
861                    DIERef::Section section, lldb::offset_t *offset_ptr,
862                    const llvm::DWARFUnitIndex *index) {
863   assert(debug_info.ValidOffset(*offset_ptr));
864 
865   auto expected_header =
866       DWARFUnitHeader::extract(debug_info, section, offset_ptr, index);
867   if (!expected_header)
868     return expected_header.takeError();
869 
870   const DWARFDebugAbbrev *abbr = dwarf.DebugAbbrev();
871   if (!abbr)
872     return llvm::make_error<llvm::object::GenericBinaryError>(
873         "No debug_abbrev data");
874 
875   bool abbr_offset_OK =
876       dwarf.GetDWARFContext().getOrLoadAbbrevData().ValidOffset(
877           expected_header->GetAbbrOffset());
878   if (!abbr_offset_OK)
879     return llvm::make_error<llvm::object::GenericBinaryError>(
880         "Abbreviation offset for unit is not valid");
881 
882   const DWARFAbbreviationDeclarationSet *abbrevs =
883       abbr->GetAbbreviationDeclarationSet(expected_header->GetAbbrOffset());
884   if (!abbrevs)
885     return llvm::make_error<llvm::object::GenericBinaryError>(
886         "No abbrev exists at the specified offset.");
887 
888   bool is_dwo = dwarf.GetDWARFContext().isDwo();
889   if (expected_header->IsTypeUnit())
890     return DWARFUnitSP(new DWARFTypeUnit(dwarf, uid, *expected_header, *abbrevs,
891                                          section, is_dwo));
892   return DWARFUnitSP(new DWARFCompileUnit(dwarf, uid, *expected_header,
893                                           *abbrevs, section, is_dwo));
894 }
895 
896 const lldb_private::DWARFDataExtractor &DWARFUnit::GetData() const {
897   return m_section == DIERef::Section::DebugTypes
898              ? m_dwarf.GetDWARFContext().getOrLoadDebugTypesData()
899              : m_dwarf.GetDWARFContext().getOrLoadDebugInfoData();
900 }
901 
902 uint32_t DWARFUnit::GetHeaderByteSize() const {
903   switch (m_header.GetUnitType()) {
904   case llvm::dwarf::DW_UT_compile:
905   case llvm::dwarf::DW_UT_partial:
906     return GetVersion() < 5 ? 11 : 12;
907   case llvm::dwarf::DW_UT_skeleton:
908   case llvm::dwarf::DW_UT_split_compile:
909     return 20;
910   case llvm::dwarf::DW_UT_type:
911   case llvm::dwarf::DW_UT_split_type:
912     return GetVersion() < 5 ? 23 : 24;
913   }
914   llvm_unreachable("invalid UnitType.");
915 }
916 
917 llvm::Optional<uint64_t>
918 DWARFUnit::GetStringOffsetSectionItem(uint32_t index) const {
919   offset_t offset = GetStrOffsetsBase() + index * 4;
920   return m_dwarf.GetDWARFContext().getOrLoadStrOffsetsData().GetU32(&offset);
921 }
922 
923 llvm::Expected<DWARFRangeList>
924 DWARFUnit::FindRnglistFromOffset(dw_offset_t offset) {
925   if (GetVersion() <= 4) {
926     const DWARFDebugRanges *debug_ranges = m_dwarf.GetDebugRanges();
927     if (!debug_ranges)
928       return llvm::make_error<llvm::object::GenericBinaryError>(
929           "No debug_ranges section");
930     DWARFRangeList ranges;
931     debug_ranges->FindRanges(this, offset, ranges);
932     return ranges;
933   }
934 
935   if (!m_rnglist_table)
936     return llvm::createStringError(errc::invalid_argument,
937                                    "missing or invalid range list table");
938 
939   auto range_list_or_error = m_rnglist_table->findList(
940       m_dwarf.GetDWARFContext().getOrLoadRngListsData().GetAsLLVM(), offset);
941   if (!range_list_or_error)
942     return range_list_or_error.takeError();
943 
944   llvm::Expected<llvm::DWARFAddressRangesVector> llvm_ranges =
945       range_list_or_error->getAbsoluteRanges(
946           llvm::object::SectionedAddress{GetBaseAddress()},
947           [&](uint32_t index) {
948             uint32_t index_size = GetAddressByteSize();
949             dw_offset_t addr_base = GetAddrBase();
950             lldb::offset_t offset = addr_base + index * index_size;
951             return llvm::object::SectionedAddress{
952                 m_dwarf.GetDWARFContext().getOrLoadAddrData().GetMaxU64(
953                     &offset, index_size)};
954           });
955   if (!llvm_ranges)
956     return llvm_ranges.takeError();
957 
958   DWARFRangeList ranges;
959   for (const llvm::DWARFAddressRange &llvm_range : *llvm_ranges) {
960     ranges.Append(DWARFRangeList::Entry(llvm_range.LowPC,
961                                         llvm_range.HighPC - llvm_range.LowPC));
962   }
963   return ranges;
964 }
965 
966 llvm::Expected<DWARFRangeList>
967 DWARFUnit::FindRnglistFromIndex(uint32_t index) {
968   if (llvm::Optional<uint64_t> offset = GetRnglistOffset(index))
969     return FindRnglistFromOffset(*offset);
970   if (m_rnglist_table)
971     return llvm::createStringError(errc::invalid_argument,
972                                    "invalid range list table index %d", index);
973 
974   return llvm::createStringError(errc::invalid_argument,
975                                  "missing or invalid range list table");
976 }
977