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