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