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