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)
36     : UserID(uid), m_dwarf(dwarf), m_header(header), m_abbrevs(&abbrevs),
37       m_cancel_scopes(false), m_section(section) {}
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   lldbassert(m_cu);
114   m_cu->m_die_array_scoped_mutex.lock_shared();
115 }
116 
117 DWARFUnit::ScopedExtractDIEs::~ScopedExtractDIEs() {
118   if (!m_cu)
119     return;
120   m_cu->m_die_array_scoped_mutex.unlock_shared();
121   if (!m_clear_dies || m_cu->m_cancel_scopes)
122     return;
123   // Be sure no other ScopedExtractDIEs is running anymore.
124   llvm::sys::ScopedWriter lock_scoped(m_cu->m_die_array_scoped_mutex);
125   llvm::sys::ScopedWriter lock(m_cu->m_die_array_mutex);
126   if (m_cu->m_cancel_scopes)
127     return;
128   m_cu->ClearDIEsRWLocked();
129 }
130 
131 DWARFUnit::ScopedExtractDIEs::ScopedExtractDIEs(ScopedExtractDIEs &&rhs)
132     : m_cu(rhs.m_cu), m_clear_dies(rhs.m_clear_dies) {
133   rhs.m_cu = nullptr;
134 }
135 
136 DWARFUnit::ScopedExtractDIEs &DWARFUnit::ScopedExtractDIEs::operator=(
137     DWARFUnit::ScopedExtractDIEs &&rhs) {
138   m_cu = rhs.m_cu;
139   rhs.m_cu = nullptr;
140   m_clear_dies = rhs.m_clear_dies;
141   return *this;
142 }
143 
144 // Parses a compile unit and indexes its DIEs, m_die_array_mutex must be
145 // held R/W and m_die_array must be empty.
146 void DWARFUnit::ExtractDIEsRWLocked() {
147   llvm::sys::ScopedWriter first_die_lock(m_first_die_mutex);
148 
149   static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
150   Timer scoped_timer(func_cat, "%8.8x: DWARFUnit::ExtractDIEsIfNeeded()",
151                      GetOffset());
152 
153   // Set the offset to that of the first DIE and calculate the start of the
154   // next compilation unit header.
155   lldb::offset_t offset = GetFirstDIEOffset();
156   lldb::offset_t next_cu_offset = GetNextUnitOffset();
157 
158   DWARFDebugInfoEntry die;
159 
160   uint32_t depth = 0;
161   // We are in our compile unit, parse starting at the offset we were told to
162   // parse
163   const DWARFDataExtractor &data = GetData();
164   std::vector<uint32_t> die_index_stack;
165   die_index_stack.reserve(32);
166   die_index_stack.push_back(0);
167   bool prev_die_had_children = false;
168   while (offset < next_cu_offset && die.Extract(data, this, &offset)) {
169     const bool null_die = die.IsNULL();
170     if (depth == 0) {
171       assert(m_die_array.empty() && "Compile unit DIE already added");
172 
173       // The average bytes per DIE entry has been seen to be around 14-20 so
174       // lets pre-reserve half of that since we are now stripping the NULL
175       // tags.
176 
177       // Only reserve the memory if we are adding children of the main
178       // compile unit DIE. The compile unit DIE is always the first entry, so
179       // if our size is 1, then we are adding the first compile unit child
180       // DIE and should reserve the memory.
181       m_die_array.reserve(GetDebugInfoSize() / 24);
182       m_die_array.push_back(die);
183 
184       if (!m_first_die)
185         AddUnitDIE(m_die_array.front());
186     } else {
187       if (null_die) {
188         if (prev_die_had_children) {
189           // This will only happen if a DIE says is has children but all it
190           // contains is a NULL tag. Since we are removing the NULL DIEs from
191           // the list (saves up to 25% in C++ code), we need a way to let the
192           // DIE know that it actually doesn't have children.
193           if (!m_die_array.empty())
194             m_die_array.back().SetHasChildren(false);
195         }
196       } else {
197         die.SetParentIndex(m_die_array.size() - die_index_stack[depth - 1]);
198 
199         if (die_index_stack.back())
200           m_die_array[die_index_stack.back()].SetSiblingIndex(
201               m_die_array.size() - die_index_stack.back());
202 
203         // Only push the DIE if it isn't a NULL DIE
204         m_die_array.push_back(die);
205       }
206     }
207 
208     if (null_die) {
209       // NULL DIE.
210       if (!die_index_stack.empty())
211         die_index_stack.pop_back();
212 
213       if (depth > 0)
214         --depth;
215       prev_die_had_children = false;
216     } else {
217       die_index_stack.back() = m_die_array.size() - 1;
218       // Normal DIE
219       const bool die_has_children = die.HasChildren();
220       if (die_has_children) {
221         die_index_stack.push_back(0);
222         ++depth;
223       }
224       prev_die_had_children = die_has_children;
225     }
226 
227     if (depth == 0)
228       break; // We are done with this compile unit!
229   }
230 
231   if (!m_die_array.empty()) {
232     if (m_first_die) {
233       // Only needed for the assertion.
234       m_first_die.SetHasChildren(m_die_array.front().HasChildren());
235       lldbassert(m_first_die == m_die_array.front());
236     }
237     m_first_die = m_die_array.front();
238   }
239 
240   m_die_array.shrink_to_fit();
241 
242   if (m_dwo_symbol_file) {
243     DWARFUnit *dwo_cu = m_dwo_symbol_file->GetCompileUnit();
244     dwo_cu->ExtractDIEsIfNeeded();
245   }
246 }
247 
248 // This is used when a split dwarf is enabled.
249 // A skeleton compilation unit may contain the DW_AT_str_offsets_base attribute
250 // that points to the first string offset of the CU contribution to the
251 // .debug_str_offsets. At the same time, the corresponding split debug unit also
252 // may use DW_FORM_strx* forms pointing to its own .debug_str_offsets.dwo and
253 // for that case, we should find the offset (skip the section header).
254 static void SetDwoStrOffsetsBase(DWARFUnit *dwo_cu) {
255   lldb::offset_t baseOffset = 0;
256 
257   const DWARFDataExtractor &strOffsets =
258       dwo_cu->GetSymbolFileDWARF()->GetDWARFContext().getOrLoadStrOffsetsData();
259   uint64_t length = strOffsets.GetU32(&baseOffset);
260   if (length == 0xffffffff)
261     length = strOffsets.GetU64(&baseOffset);
262 
263   // Check version.
264   if (strOffsets.GetU16(&baseOffset) < 5)
265     return;
266 
267   // Skip padding.
268   baseOffset += 2;
269 
270   dwo_cu->SetStrOffsetsBase(baseOffset);
271 }
272 
273 // m_die_array_mutex must be already held as read/write.
274 void DWARFUnit::AddUnitDIE(const DWARFDebugInfoEntry &cu_die) {
275   dw_addr_t addr_base = cu_die.GetAttributeValueAsUnsigned(
276       this, DW_AT_addr_base, LLDB_INVALID_ADDRESS);
277   if (addr_base != LLDB_INVALID_ADDRESS)
278     SetAddrBase(addr_base);
279 
280   dw_addr_t ranges_base = cu_die.GetAttributeValueAsUnsigned(
281       this, DW_AT_rnglists_base, LLDB_INVALID_ADDRESS);
282   if (ranges_base != LLDB_INVALID_ADDRESS)
283     SetRangesBase(ranges_base);
284 
285   SetStrOffsetsBase(
286       cu_die.GetAttributeValueAsUnsigned(this, DW_AT_str_offsets_base, 0));
287 
288   uint64_t base_addr = cu_die.GetAttributeValueAsAddress(this, DW_AT_low_pc,
289                                                          LLDB_INVALID_ADDRESS);
290   if (base_addr == LLDB_INVALID_ADDRESS)
291     base_addr = cu_die.GetAttributeValueAsAddress(this, DW_AT_entry_pc, 0);
292   SetBaseAddress(base_addr);
293 
294   std::unique_ptr<SymbolFileDWARFDwo> dwo_symbol_file =
295       m_dwarf->GetDwoSymbolFileForCompileUnit(*this, cu_die);
296   if (!dwo_symbol_file)
297     return;
298 
299   DWARFUnit *dwo_cu = dwo_symbol_file->GetCompileUnit();
300   if (!dwo_cu)
301     return; // Can't fetch the compile unit from the dwo file.
302 
303   DWARFBaseDIE dwo_cu_die = dwo_cu->GetUnitDIEOnly();
304   if (!dwo_cu_die.IsValid())
305     return; // Can't fetch the compile unit DIE from the dwo file.
306 
307   uint64_t main_dwo_id =
308       cu_die.GetAttributeValueAsUnsigned(this, DW_AT_GNU_dwo_id, 0);
309   uint64_t sub_dwo_id =
310       dwo_cu_die.GetAttributeValueAsUnsigned(DW_AT_GNU_dwo_id, 0);
311   if (main_dwo_id != sub_dwo_id)
312     return; // The 2 dwo ID isn't match. Don't use the dwo file as it belongs to
313   // a differectn compilation.
314 
315   m_dwo_symbol_file = std::move(dwo_symbol_file);
316 
317   // Here for DWO CU we want to use the address base set in the skeleton unit
318   // (DW_AT_addr_base) if it is available and use the DW_AT_GNU_addr_base
319   // otherwise. We do that because pre-DWARF v5 could use the DW_AT_GNU_*
320   // attributes which were applicable to the DWO units. The corresponding
321   // DW_AT_* attributes standardized in DWARF v5 are also applicable to the main
322   // unit in contrast.
323   if (addr_base == LLDB_INVALID_ADDRESS)
324     addr_base =
325         cu_die.GetAttributeValueAsUnsigned(this, DW_AT_GNU_addr_base, 0);
326   dwo_cu->SetAddrBase(addr_base);
327 
328   if (ranges_base == LLDB_INVALID_ADDRESS)
329     ranges_base =
330         cu_die.GetAttributeValueAsUnsigned(this, DW_AT_GNU_ranges_base, 0);
331   dwo_cu->SetRangesBase(ranges_base);
332 
333   dwo_cu->SetBaseObjOffset(GetOffset());
334 
335   SetDwoStrOffsetsBase(dwo_cu);
336 }
337 
338 DWARFDIE DWARFUnit::LookupAddress(const dw_addr_t address) {
339   if (DIE()) {
340     const DWARFDebugAranges &func_aranges = GetFunctionAranges();
341 
342     // Re-check the aranges auto pointer contents in case it was created above
343     if (!func_aranges.IsEmpty())
344       return GetDIE(func_aranges.FindAddress(address));
345   }
346   return DWARFDIE();
347 }
348 
349 size_t DWARFUnit::AppendDIEsWithTag(const dw_tag_t tag,
350                                     std::vector<DWARFDIE> &dies,
351                                     uint32_t depth) const {
352   size_t old_size = dies.size();
353   {
354     llvm::sys::ScopedReader lock(m_die_array_mutex);
355     DWARFDebugInfoEntry::const_iterator pos;
356     DWARFDebugInfoEntry::const_iterator end = m_die_array.end();
357     for (pos = m_die_array.begin(); pos != end; ++pos) {
358       if (pos->Tag() == tag)
359         dies.emplace_back(this, &(*pos));
360     }
361   }
362 
363   // Return the number of DIEs added to the collection
364   return dies.size() - old_size;
365 }
366 
367 size_t DWARFUnit::GetDebugInfoSize() const {
368   return GetLengthByteSize() + GetLength() - GetHeaderByteSize();
369 }
370 
371 const DWARFAbbreviationDeclarationSet *DWARFUnit::GetAbbreviations() const {
372   return m_abbrevs;
373 }
374 
375 dw_offset_t DWARFUnit::GetAbbrevOffset() const {
376   return m_abbrevs ? m_abbrevs->GetOffset() : DW_INVALID_OFFSET;
377 }
378 
379 void DWARFUnit::SetAddrBase(dw_addr_t addr_base) { m_addr_base = addr_base; }
380 
381 void DWARFUnit::SetRangesBase(dw_addr_t ranges_base) {
382   m_ranges_base = ranges_base;
383 }
384 
385 void DWARFUnit::SetBaseObjOffset(dw_offset_t base_obj_offset) {
386   m_base_obj_offset = base_obj_offset;
387 }
388 
389 void DWARFUnit::SetStrOffsetsBase(dw_offset_t str_offsets_base) {
390   m_str_offsets_base = str_offsets_base;
391 }
392 
393 // It may be called only with m_die_array_mutex held R/W.
394 void DWARFUnit::ClearDIEsRWLocked() {
395   m_die_array.clear();
396   m_die_array.shrink_to_fit();
397 
398   if (m_dwo_symbol_file)
399     m_dwo_symbol_file->GetCompileUnit()->ClearDIEsRWLocked();
400 }
401 
402 lldb::ByteOrder DWARFUnit::GetByteOrder() const {
403   return m_dwarf->GetObjectFile()->GetByteOrder();
404 }
405 
406 TypeSystem *DWARFUnit::GetTypeSystem() {
407   if (m_dwarf)
408     return m_dwarf->GetTypeSystemForLanguage(GetLanguageType());
409   else
410     return nullptr;
411 }
412 
413 void DWARFUnit::SetBaseAddress(dw_addr_t base_addr) { m_base_addr = base_addr; }
414 
415 // Compare function DWARFDebugAranges::Range structures
416 static bool CompareDIEOffset(const DWARFDebugInfoEntry &die,
417                              const dw_offset_t die_offset) {
418   return die.GetOffset() < die_offset;
419 }
420 
421 // GetDIE()
422 //
423 // Get the DIE (Debug Information Entry) with the specified offset by first
424 // checking if the DIE is contained within this compile unit and grabbing the
425 // DIE from this compile unit. Otherwise we grab the DIE from the DWARF file.
426 DWARFDIE
427 DWARFUnit::GetDIE(dw_offset_t die_offset) {
428   if (die_offset != DW_INVALID_OFFSET) {
429     if (GetDwoSymbolFile())
430       return GetDwoSymbolFile()->GetCompileUnit()->GetDIE(die_offset);
431 
432     if (ContainsDIEOffset(die_offset)) {
433       ExtractDIEsIfNeeded();
434       DWARFDebugInfoEntry::const_iterator end = m_die_array.cend();
435       DWARFDebugInfoEntry::const_iterator pos =
436           lower_bound(m_die_array.cbegin(), end, die_offset, CompareDIEOffset);
437       if (pos != end) {
438         if (die_offset == (*pos).GetOffset())
439           return DWARFDIE(this, &(*pos));
440       }
441     } else
442       GetSymbolFileDWARF()->GetObjectFile()->GetModule()->ReportError(
443           "GetDIE for DIE 0x%" PRIx32 " is outside of its CU 0x%" PRIx32,
444           die_offset, GetOffset());
445   }
446   return DWARFDIE(); // Not found
447 }
448 
449 uint8_t DWARFUnit::GetAddressByteSize(const DWARFUnit *cu) {
450   if (cu)
451     return cu->GetAddressByteSize();
452   return DWARFUnit::GetDefaultAddressSize();
453 }
454 
455 uint8_t DWARFUnit::GetDefaultAddressSize() { return 4; }
456 
457 void *DWARFUnit::GetUserData() const { return m_user_data; }
458 
459 void DWARFUnit::SetUserData(void *d) {
460   m_user_data = d;
461   if (m_dwo_symbol_file)
462     m_dwo_symbol_file->GetCompileUnit()->SetUserData(d);
463 }
464 
465 bool DWARFUnit::Supports_DW_AT_APPLE_objc_complete_type() {
466   return GetProducer() != eProducerLLVMGCC;
467 }
468 
469 bool DWARFUnit::DW_AT_decl_file_attributes_are_invalid() {
470   // llvm-gcc makes completely invalid decl file attributes and won't ever be
471   // fixed, so we need to know to ignore these.
472   return GetProducer() == eProducerLLVMGCC;
473 }
474 
475 bool DWARFUnit::Supports_unnamed_objc_bitfields() {
476   if (GetProducer() == eProducerClang) {
477     const uint32_t major_version = GetProducerVersionMajor();
478     return major_version > 425 ||
479            (major_version == 425 && GetProducerVersionUpdate() >= 13);
480   }
481   return true; // Assume all other compilers didn't have incorrect ObjC bitfield
482                // info
483 }
484 
485 SymbolFileDWARF *DWARFUnit::GetSymbolFileDWARF() const { return m_dwarf; }
486 
487 void DWARFUnit::ParseProducerInfo() {
488   m_producer_version_major = UINT32_MAX;
489   m_producer_version_minor = UINT32_MAX;
490   m_producer_version_update = UINT32_MAX;
491 
492   const DWARFDebugInfoEntry *die = GetUnitDIEPtrOnly();
493   if (die) {
494 
495     const char *producer_cstr =
496         die->GetAttributeValueAsString(this, DW_AT_producer, nullptr);
497     if (producer_cstr) {
498       RegularExpression llvm_gcc_regex(
499           llvm::StringRef("^4\\.[012]\\.[01] \\(Based on Apple "
500                           "Inc\\. build [0-9]+\\) \\(LLVM build "
501                           "[\\.0-9]+\\)$"));
502       if (llvm_gcc_regex.Execute(llvm::StringRef(producer_cstr))) {
503         m_producer = eProducerLLVMGCC;
504       } else if (strstr(producer_cstr, "clang")) {
505         static RegularExpression g_clang_version_regex(
506             llvm::StringRef("clang-([0-9]+)\\.([0-9]+)\\.([0-9]+)"));
507         RegularExpression::Match regex_match(3);
508         if (g_clang_version_regex.Execute(llvm::StringRef(producer_cstr),
509                                           &regex_match)) {
510           std::string str;
511           if (regex_match.GetMatchAtIndex(producer_cstr, 1, str))
512             m_producer_version_major =
513                 StringConvert::ToUInt32(str.c_str(), UINT32_MAX, 10);
514           if (regex_match.GetMatchAtIndex(producer_cstr, 2, str))
515             m_producer_version_minor =
516                 StringConvert::ToUInt32(str.c_str(), UINT32_MAX, 10);
517           if (regex_match.GetMatchAtIndex(producer_cstr, 3, str))
518             m_producer_version_update =
519                 StringConvert::ToUInt32(str.c_str(), UINT32_MAX, 10);
520         }
521         m_producer = eProducerClang;
522       } else if (strstr(producer_cstr, "GNU"))
523         m_producer = eProducerGCC;
524     }
525   }
526   if (m_producer == eProducerInvalid)
527     m_producer = eProcucerOther;
528 }
529 
530 DWARFProducer DWARFUnit::GetProducer() {
531   if (m_producer == eProducerInvalid)
532     ParseProducerInfo();
533   return m_producer;
534 }
535 
536 uint32_t DWARFUnit::GetProducerVersionMajor() {
537   if (m_producer_version_major == 0)
538     ParseProducerInfo();
539   return m_producer_version_major;
540 }
541 
542 uint32_t DWARFUnit::GetProducerVersionMinor() {
543   if (m_producer_version_minor == 0)
544     ParseProducerInfo();
545   return m_producer_version_minor;
546 }
547 
548 uint32_t DWARFUnit::GetProducerVersionUpdate() {
549   if (m_producer_version_update == 0)
550     ParseProducerInfo();
551   return m_producer_version_update;
552 }
553 LanguageType DWARFUnit::LanguageTypeFromDWARF(uint64_t val) {
554   // Note: user languages between lo_user and hi_user must be handled
555   // explicitly here.
556   switch (val) {
557   case DW_LANG_Mips_Assembler:
558     return eLanguageTypeMipsAssembler;
559   case DW_LANG_GOOGLE_RenderScript:
560     return eLanguageTypeExtRenderScript;
561   default:
562     return static_cast<LanguageType>(val);
563   }
564 }
565 
566 LanguageType DWARFUnit::GetLanguageType() {
567   if (m_language_type != eLanguageTypeUnknown)
568     return m_language_type;
569 
570   const DWARFDebugInfoEntry *die = GetUnitDIEPtrOnly();
571   if (die)
572     m_language_type = LanguageTypeFromDWARF(
573         die->GetAttributeValueAsUnsigned(this, DW_AT_language, 0));
574   return m_language_type;
575 }
576 
577 bool DWARFUnit::GetIsOptimized() {
578   if (m_is_optimized == eLazyBoolCalculate) {
579     const DWARFDebugInfoEntry *die = GetUnitDIEPtrOnly();
580     if (die) {
581       m_is_optimized = eLazyBoolNo;
582       if (die->GetAttributeValueAsUnsigned(this, DW_AT_APPLE_optimized, 0) ==
583           1) {
584         m_is_optimized = eLazyBoolYes;
585       }
586     }
587   }
588   return m_is_optimized == eLazyBoolYes;
589 }
590 
591 FileSpec::Style DWARFUnit::GetPathStyle() {
592   if (!m_comp_dir)
593     ComputeCompDirAndGuessPathStyle();
594   return m_comp_dir->GetPathStyle();
595 }
596 
597 const FileSpec &DWARFUnit::GetCompilationDirectory() {
598   if (!m_comp_dir)
599     ComputeCompDirAndGuessPathStyle();
600   return *m_comp_dir;
601 }
602 
603 // DWARF2/3 suggests the form hostname:pathname for compilation directory.
604 // Remove the host part if present.
605 static llvm::StringRef
606 removeHostnameFromPathname(llvm::StringRef path_from_dwarf) {
607   llvm::StringRef host, path;
608   std::tie(host, path) = path_from_dwarf.split(':');
609 
610   if (host.contains('/'))
611     return path_from_dwarf;
612 
613   // check whether we have a windows path, and so the first character is a
614   // drive-letter not a hostname.
615   if (host.size() == 1 && llvm::isAlpha(host[0]) && path.startswith("\\"))
616     return path_from_dwarf;
617 
618   return path;
619 }
620 
621 static FileSpec resolveCompDir(const FileSpec &path) {
622   bool is_symlink = SymbolFileDWARF::GetSymlinkPaths().FindFileIndex(
623                         0, path, /*full*/ true) != UINT32_MAX;
624 
625   if (!is_symlink)
626     return path;
627 
628   namespace fs = llvm::sys::fs;
629   if (fs::get_file_type(path.GetPath(), false) != fs::file_type::symlink_file)
630     return path;
631 
632   FileSpec resolved_symlink;
633   const auto error = FileSystem::Instance().Readlink(path, resolved_symlink);
634   if (error.Success())
635     return resolved_symlink;
636 
637   return path;
638 }
639 
640 void DWARFUnit::ComputeCompDirAndGuessPathStyle() {
641   m_comp_dir = FileSpec();
642   const DWARFDebugInfoEntry *die = GetUnitDIEPtrOnly();
643   if (!die)
644     return;
645 
646   llvm::StringRef comp_dir = removeHostnameFromPathname(
647       die->GetAttributeValueAsString(this, DW_AT_comp_dir, nullptr));
648   if (!comp_dir.empty()) {
649     FileSpec::Style comp_dir_style =
650         FileSpec::GuessPathStyle(comp_dir).getValueOr(FileSpec::Style::native);
651     m_comp_dir = resolveCompDir(FileSpec(comp_dir, comp_dir_style));
652   } else {
653     // Try to detect the style based on the DW_AT_name attribute, but just store
654     // the detected style in the m_comp_dir field.
655     const char *name =
656         die->GetAttributeValueAsString(this, DW_AT_name, nullptr);
657     m_comp_dir = FileSpec(
658         "", FileSpec::GuessPathStyle(name).getValueOr(FileSpec::Style::native));
659   }
660 }
661 
662 SymbolFileDWARFDwo *DWARFUnit::GetDwoSymbolFile() const {
663   return m_dwo_symbol_file.get();
664 }
665 
666 dw_offset_t DWARFUnit::GetBaseObjOffset() const { return m_base_obj_offset; }
667 
668 const DWARFDebugAranges &DWARFUnit::GetFunctionAranges() {
669   if (m_func_aranges_up == nullptr) {
670     m_func_aranges_up.reset(new DWARFDebugAranges());
671     const DWARFDebugInfoEntry *die = DIEPtr();
672     if (die)
673       die->BuildFunctionAddressRangeTable(this, m_func_aranges_up.get());
674 
675     if (m_dwo_symbol_file) {
676       DWARFUnit *dwo_cu = m_dwo_symbol_file->GetCompileUnit();
677       const DWARFDebugInfoEntry *dwo_die = dwo_cu->DIEPtr();
678       if (dwo_die)
679         dwo_die->BuildFunctionAddressRangeTable(dwo_cu,
680                                                 m_func_aranges_up.get());
681     }
682 
683     const bool minimize = false;
684     m_func_aranges_up->Sort(minimize);
685   }
686   return *m_func_aranges_up;
687 }
688 
689 llvm::Expected<DWARFUnitHeader>
690 DWARFUnitHeader::extract(const DWARFDataExtractor &data, DIERef::Section section,
691                          lldb::offset_t *offset_ptr) {
692   DWARFUnitHeader header;
693   header.m_offset = *offset_ptr;
694   header.m_length = data.GetDWARFInitialLength(offset_ptr);
695   header.m_version = data.GetU16(offset_ptr);
696   if (header.m_version == 5) {
697     header.m_unit_type = data.GetU8(offset_ptr);
698     header.m_addr_size = data.GetU8(offset_ptr);
699     header.m_abbr_offset = data.GetDWARFOffset(offset_ptr);
700     if (header.m_unit_type == llvm::dwarf::DW_UT_skeleton)
701       header.m_dwo_id = data.GetU64(offset_ptr);
702   } else {
703     header.m_abbr_offset = data.GetDWARFOffset(offset_ptr);
704     header.m_addr_size = data.GetU8(offset_ptr);
705     header.m_unit_type =
706         section == DIERef::Section::DebugTypes ? DW_UT_type : DW_UT_compile;
707   }
708 
709   if (header.IsTypeUnit()) {
710     header.m_type_hash = data.GetU64(offset_ptr);
711     header.m_type_offset = data.GetDWARFOffset(offset_ptr);
712   }
713 
714   bool length_OK = data.ValidOffset(header.GetNextUnitOffset() - 1);
715   bool version_OK = SymbolFileDWARF::SupportedVersion(header.m_version);
716   bool addr_size_OK = (header.m_addr_size == 4) || (header.m_addr_size == 8);
717   bool type_offset_OK =
718       !header.IsTypeUnit() || (header.m_type_offset <= header.GetLength());
719 
720   if (!length_OK)
721     return llvm::make_error<llvm::object::GenericBinaryError>(
722         "Invalid unit length");
723   if (!version_OK)
724     return llvm::make_error<llvm::object::GenericBinaryError>(
725         "Unsupported unit version");
726   if (!addr_size_OK)
727     return llvm::make_error<llvm::object::GenericBinaryError>(
728         "Invalid unit address size");
729   if (!type_offset_OK)
730     return llvm::make_error<llvm::object::GenericBinaryError>(
731         "Type offset out of range");
732 
733   return header;
734 }
735 
736 llvm::Expected<DWARFUnitSP>
737 DWARFUnit::extract(SymbolFileDWARF *dwarf, user_id_t uid,
738                    const DWARFDataExtractor &debug_info, DIERef::Section section,
739                    lldb::offset_t *offset_ptr) {
740   assert(debug_info.ValidOffset(*offset_ptr));
741 
742   auto expected_header =
743       DWARFUnitHeader::extract(debug_info, section, offset_ptr);
744   if (!expected_header)
745     return expected_header.takeError();
746 
747   const DWARFDebugAbbrev *abbr = dwarf->DebugAbbrev();
748   if (!abbr)
749     return llvm::make_error<llvm::object::GenericBinaryError>(
750         "No debug_abbrev data");
751 
752   bool abbr_offset_OK =
753       dwarf->GetDWARFContext().getOrLoadAbbrevData().ValidOffset(
754           expected_header->GetAbbrOffset());
755   if (!abbr_offset_OK)
756     return llvm::make_error<llvm::object::GenericBinaryError>(
757         "Abbreviation offset for unit is not valid");
758 
759   const DWARFAbbreviationDeclarationSet *abbrevs =
760       abbr->GetAbbreviationDeclarationSet(expected_header->GetAbbrOffset());
761   if (!abbrevs)
762     return llvm::make_error<llvm::object::GenericBinaryError>(
763         "No abbrev exists at the specified offset.");
764 
765   if (expected_header->IsTypeUnit())
766     return DWARFUnitSP(
767         new DWARFTypeUnit(dwarf, uid, *expected_header, *abbrevs, section));
768   return DWARFUnitSP(
769       new DWARFCompileUnit(dwarf, uid, *expected_header, *abbrevs, section));
770 }
771 
772 const lldb_private::DWARFDataExtractor &DWARFUnit::GetData() const {
773   return m_section == DIERef::Section::DebugTypes
774              ? m_dwarf->GetDWARFContext().getOrLoadDebugTypesData()
775              : m_dwarf->GetDWARFContext().getOrLoadDebugInfoData();
776 }
777 
778 uint32_t DWARFUnit::GetHeaderByteSize() const {
779   switch (m_header.GetUnitType()) {
780   case llvm::dwarf::DW_UT_compile:
781   case llvm::dwarf::DW_UT_partial:
782     return GetVersion() < 5 ? 11 : 12;
783   case llvm::dwarf::DW_UT_skeleton:
784   case llvm::dwarf::DW_UT_split_compile:
785     return 20;
786   case llvm::dwarf::DW_UT_type:
787   case llvm::dwarf::DW_UT_split_type:
788     return GetVersion() < 5 ? 23 : 24;
789   }
790   llvm_unreachable("invalid UnitType.");
791 }
792 
793 llvm::Expected<DWARFRangeList>
794 DWARFUnit::FindRnglistFromOffset(dw_offset_t offset) const {
795   const DWARFDebugRangesBase *debug_ranges;
796   llvm::StringRef section;
797   if (GetVersion() <= 4) {
798     debug_ranges = m_dwarf->GetDebugRanges();
799     section = "debug_ranges";
800   } else {
801     debug_ranges = m_dwarf->GetDebugRngLists();
802     section = "debug_rnglists";
803   }
804   if (!debug_ranges)
805     return llvm::make_error<llvm::object::GenericBinaryError>("No " + section +
806                                                               " section");
807 
808   DWARFRangeList ranges;
809   debug_ranges->FindRanges(this, offset, ranges);
810   return ranges;
811 }
812 
813 llvm::Expected<DWARFRangeList>
814 DWARFUnit::FindRnglistFromIndex(uint32_t index) const {
815   const DWARFDebugRangesBase *debug_rnglists = m_dwarf->GetDebugRngLists();
816   if (!debug_rnglists)
817     return llvm::make_error<llvm::object::GenericBinaryError>(
818         "No debug_rnglists section");
819   return FindRnglistFromOffset(debug_rnglists->GetOffset(index));
820 }
821