1 //===- DWARFDebugLine.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 "llvm/DebugInfo/DWARF/DWARFDebugLine.h" 10 #include "llvm/ADT/Optional.h" 11 #include "llvm/ADT/SmallString.h" 12 #include "llvm/ADT/SmallVector.h" 13 #include "llvm/ADT/StringRef.h" 14 #include "llvm/BinaryFormat/Dwarf.h" 15 #include "llvm/DebugInfo/DWARF/DWARFFormValue.h" 16 #include "llvm/DebugInfo/DWARF/DWARFRelocMap.h" 17 #include "llvm/Support/Errc.h" 18 #include "llvm/Support/Format.h" 19 #include "llvm/Support/FormatVariadic.h" 20 #include "llvm/Support/WithColor.h" 21 #include "llvm/Support/raw_ostream.h" 22 #include <algorithm> 23 #include <cassert> 24 #include <cinttypes> 25 #include <cstdint> 26 #include <cstdio> 27 #include <utility> 28 29 using namespace llvm; 30 using namespace dwarf; 31 32 using FileLineInfoKind = DILineInfoSpecifier::FileLineInfoKind; 33 34 namespace { 35 36 struct ContentDescriptor { 37 dwarf::LineNumberEntryFormat Type; 38 dwarf::Form Form; 39 }; 40 41 using ContentDescriptors = SmallVector<ContentDescriptor, 4>; 42 43 } // end anonymous namespace 44 45 static bool versionIsSupported(uint16_t Version) { 46 return Version >= 2 && Version <= 5; 47 } 48 49 void DWARFDebugLine::ContentTypeTracker::trackContentType( 50 dwarf::LineNumberEntryFormat ContentType) { 51 switch (ContentType) { 52 case dwarf::DW_LNCT_timestamp: 53 HasModTime = true; 54 break; 55 case dwarf::DW_LNCT_size: 56 HasLength = true; 57 break; 58 case dwarf::DW_LNCT_MD5: 59 HasMD5 = true; 60 break; 61 case dwarf::DW_LNCT_LLVM_source: 62 HasSource = true; 63 break; 64 default: 65 // We only care about values we consider optional, and new values may be 66 // added in the vendor extension range, so we do not match exhaustively. 67 break; 68 } 69 } 70 71 DWARFDebugLine::Prologue::Prologue() { clear(); } 72 73 bool DWARFDebugLine::Prologue::hasFileAtIndex(uint64_t FileIndex) const { 74 uint16_t DwarfVersion = getVersion(); 75 assert(DwarfVersion != 0 && 76 "line table prologue has no dwarf version information"); 77 if (DwarfVersion >= 5) 78 return FileIndex < FileNames.size(); 79 return FileIndex != 0 && FileIndex <= FileNames.size(); 80 } 81 82 const llvm::DWARFDebugLine::FileNameEntry & 83 DWARFDebugLine::Prologue::getFileNameEntry(uint64_t Index) const { 84 uint16_t DwarfVersion = getVersion(); 85 assert(DwarfVersion != 0 && 86 "line table prologue has no dwarf version information"); 87 // In DWARF v5 the file names are 0-indexed. 88 if (DwarfVersion >= 5) 89 return FileNames[Index]; 90 return FileNames[Index - 1]; 91 } 92 93 void DWARFDebugLine::Prologue::clear() { 94 TotalLength = PrologueLength = 0; 95 SegSelectorSize = 0; 96 MinInstLength = MaxOpsPerInst = DefaultIsStmt = LineBase = LineRange = 0; 97 OpcodeBase = 0; 98 FormParams = dwarf::FormParams({0, 0, DWARF32}); 99 ContentTypes = ContentTypeTracker(); 100 StandardOpcodeLengths.clear(); 101 IncludeDirectories.clear(); 102 FileNames.clear(); 103 } 104 105 void DWARFDebugLine::Prologue::dump(raw_ostream &OS, 106 DIDumpOptions DumpOptions) const { 107 if (!totalLengthIsValid()) 108 return; 109 OS << "Line table prologue:\n" 110 << format(" total_length: 0x%8.8" PRIx64 "\n", TotalLength) 111 << format(" version: %u\n", getVersion()); 112 if (!versionIsSupported(getVersion())) 113 return; 114 if (getVersion() >= 5) 115 OS << format(" address_size: %u\n", getAddressSize()) 116 << format(" seg_select_size: %u\n", SegSelectorSize); 117 OS << format(" prologue_length: 0x%8.8" PRIx64 "\n", PrologueLength) 118 << format(" min_inst_length: %u\n", MinInstLength) 119 << format(getVersion() >= 4 ? "max_ops_per_inst: %u\n" : "", MaxOpsPerInst) 120 << format(" default_is_stmt: %u\n", DefaultIsStmt) 121 << format(" line_base: %i\n", LineBase) 122 << format(" line_range: %u\n", LineRange) 123 << format(" opcode_base: %u\n", OpcodeBase); 124 125 for (uint32_t I = 0; I != StandardOpcodeLengths.size(); ++I) 126 OS << formatv("standard_opcode_lengths[{0}] = {1}\n", 127 static_cast<dwarf::LineNumberOps>(I + 1), 128 StandardOpcodeLengths[I]); 129 130 if (!IncludeDirectories.empty()) { 131 // DWARF v5 starts directory indexes at 0. 132 uint32_t DirBase = getVersion() >= 5 ? 0 : 1; 133 for (uint32_t I = 0; I != IncludeDirectories.size(); ++I) { 134 OS << format("include_directories[%3u] = ", I + DirBase); 135 IncludeDirectories[I].dump(OS, DumpOptions); 136 OS << '\n'; 137 } 138 } 139 140 if (!FileNames.empty()) { 141 // DWARF v5 starts file indexes at 0. 142 uint32_t FileBase = getVersion() >= 5 ? 0 : 1; 143 for (uint32_t I = 0; I != FileNames.size(); ++I) { 144 const FileNameEntry &FileEntry = FileNames[I]; 145 OS << format("file_names[%3u]:\n", I + FileBase); 146 OS << " name: "; 147 FileEntry.Name.dump(OS, DumpOptions); 148 OS << '\n' 149 << format(" dir_index: %" PRIu64 "\n", FileEntry.DirIdx); 150 if (ContentTypes.HasMD5) 151 OS << " md5_checksum: " << FileEntry.Checksum.digest() << '\n'; 152 if (ContentTypes.HasModTime) 153 OS << format(" mod_time: 0x%8.8" PRIx64 "\n", FileEntry.ModTime); 154 if (ContentTypes.HasLength) 155 OS << format(" length: 0x%8.8" PRIx64 "\n", FileEntry.Length); 156 if (ContentTypes.HasSource) { 157 OS << " source: "; 158 FileEntry.Source.dump(OS, DumpOptions); 159 OS << '\n'; 160 } 161 } 162 } 163 } 164 165 // Parse v2-v4 directory and file tables. 166 static Error 167 parseV2DirFileTables(const DWARFDataExtractor &DebugLineData, 168 uint64_t *OffsetPtr, uint64_t EndPrologueOffset, 169 DWARFDebugLine::ContentTypeTracker &ContentTypes, 170 std::vector<DWARFFormValue> &IncludeDirectories, 171 std::vector<DWARFDebugLine::FileNameEntry> &FileNames) { 172 bool Terminated = false; 173 while (*OffsetPtr < EndPrologueOffset) { 174 StringRef S = DebugLineData.getCStrRef(OffsetPtr); 175 if (S.empty()) { 176 Terminated = true; 177 break; 178 } 179 DWARFFormValue Dir = 180 DWARFFormValue::createFromPValue(dwarf::DW_FORM_string, S.data()); 181 IncludeDirectories.push_back(Dir); 182 } 183 184 if (!Terminated) 185 return createStringError(errc::invalid_argument, 186 "include directories table was not null " 187 "terminated before the end of the prologue"); 188 189 Terminated = false; 190 while (*OffsetPtr < EndPrologueOffset) { 191 StringRef Name = DebugLineData.getCStrRef(OffsetPtr); 192 if (Name.empty()) { 193 Terminated = true; 194 break; 195 } 196 DWARFDebugLine::FileNameEntry FileEntry; 197 FileEntry.Name = 198 DWARFFormValue::createFromPValue(dwarf::DW_FORM_string, Name.data()); 199 FileEntry.DirIdx = DebugLineData.getULEB128(OffsetPtr); 200 FileEntry.ModTime = DebugLineData.getULEB128(OffsetPtr); 201 FileEntry.Length = DebugLineData.getULEB128(OffsetPtr); 202 FileNames.push_back(FileEntry); 203 } 204 205 ContentTypes.HasModTime = true; 206 ContentTypes.HasLength = true; 207 208 if (!Terminated) 209 return createStringError(errc::invalid_argument, 210 "file names table was not null terminated before " 211 "the end of the prologue"); 212 213 return Error::success(); 214 } 215 216 // Parse v5 directory/file entry content descriptions. 217 // Returns the descriptors, or an error if we did not find a path or ran off 218 // the end of the prologue. 219 static llvm::Expected<ContentDescriptors> 220 parseV5EntryFormat(const DWARFDataExtractor &DebugLineData, uint64_t *OffsetPtr, 221 DWARFDebugLine::ContentTypeTracker *ContentTypes) { 222 ContentDescriptors Descriptors; 223 int FormatCount = DebugLineData.getU8(OffsetPtr); 224 bool HasPath = false; 225 for (int I = 0; I != FormatCount; ++I) { 226 ContentDescriptor Descriptor; 227 Descriptor.Type = 228 dwarf::LineNumberEntryFormat(DebugLineData.getULEB128(OffsetPtr)); 229 Descriptor.Form = dwarf::Form(DebugLineData.getULEB128(OffsetPtr)); 230 if (Descriptor.Type == dwarf::DW_LNCT_path) 231 HasPath = true; 232 if (ContentTypes) 233 ContentTypes->trackContentType(Descriptor.Type); 234 Descriptors.push_back(Descriptor); 235 } 236 237 if (!HasPath) 238 return createStringError(errc::invalid_argument, 239 "failed to parse entry content descriptions" 240 " because no path was found"); 241 return Descriptors; 242 } 243 244 static Error 245 parseV5DirFileTables(const DWARFDataExtractor &DebugLineData, 246 uint64_t *OffsetPtr, const dwarf::FormParams &FormParams, 247 const DWARFContext &Ctx, const DWARFUnit *U, 248 DWARFDebugLine::ContentTypeTracker &ContentTypes, 249 std::vector<DWARFFormValue> &IncludeDirectories, 250 std::vector<DWARFDebugLine::FileNameEntry> &FileNames) { 251 // Get the directory entry description. 252 llvm::Expected<ContentDescriptors> DirDescriptors = 253 parseV5EntryFormat(DebugLineData, OffsetPtr, nullptr); 254 if (!DirDescriptors) 255 return DirDescriptors.takeError(); 256 257 // Get the directory entries, according to the format described above. 258 int DirEntryCount = DebugLineData.getU8(OffsetPtr); 259 for (int I = 0; I != DirEntryCount; ++I) { 260 for (auto Descriptor : *DirDescriptors) { 261 DWARFFormValue Value(Descriptor.Form); 262 switch (Descriptor.Type) { 263 case DW_LNCT_path: 264 if (!Value.extractValue(DebugLineData, OffsetPtr, FormParams, &Ctx, U)) 265 return createStringError(errc::invalid_argument, 266 "failed to parse directory entry because " 267 "extracting the form value failed."); 268 IncludeDirectories.push_back(Value); 269 break; 270 default: 271 if (!Value.skipValue(DebugLineData, OffsetPtr, FormParams)) 272 return createStringError(errc::invalid_argument, 273 "failed to parse directory entry because " 274 "skipping the form value failed."); 275 } 276 } 277 } 278 279 // Get the file entry description. 280 llvm::Expected<ContentDescriptors> FileDescriptors = 281 parseV5EntryFormat(DebugLineData, OffsetPtr, &ContentTypes); 282 if (!FileDescriptors) 283 return FileDescriptors.takeError(); 284 285 // Get the file entries, according to the format described above. 286 int FileEntryCount = DebugLineData.getU8(OffsetPtr); 287 for (int I = 0; I != FileEntryCount; ++I) { 288 DWARFDebugLine::FileNameEntry FileEntry; 289 for (auto Descriptor : *FileDescriptors) { 290 DWARFFormValue Value(Descriptor.Form); 291 if (!Value.extractValue(DebugLineData, OffsetPtr, FormParams, &Ctx, U)) 292 return createStringError(errc::invalid_argument, 293 "failed to parse file entry because " 294 "extracting the form value failed."); 295 switch (Descriptor.Type) { 296 case DW_LNCT_path: 297 FileEntry.Name = Value; 298 break; 299 case DW_LNCT_LLVM_source: 300 FileEntry.Source = Value; 301 break; 302 case DW_LNCT_directory_index: 303 FileEntry.DirIdx = Value.getAsUnsignedConstant().getValue(); 304 break; 305 case DW_LNCT_timestamp: 306 FileEntry.ModTime = Value.getAsUnsignedConstant().getValue(); 307 break; 308 case DW_LNCT_size: 309 FileEntry.Length = Value.getAsUnsignedConstant().getValue(); 310 break; 311 case DW_LNCT_MD5: 312 if (!Value.getAsBlock() || Value.getAsBlock().getValue().size() != 16) 313 return createStringError( 314 errc::invalid_argument, 315 "failed to parse file entry because the MD5 hash is invalid"); 316 std::uninitialized_copy_n(Value.getAsBlock().getValue().begin(), 16, 317 FileEntry.Checksum.Bytes.begin()); 318 break; 319 default: 320 break; 321 } 322 } 323 FileNames.push_back(FileEntry); 324 } 325 return Error::success(); 326 } 327 328 uint64_t DWARFDebugLine::Prologue::getLength() const { 329 uint64_t Length = PrologueLength + sizeofTotalLength() + 330 sizeof(getVersion()) + sizeofPrologueLength(); 331 if (getVersion() >= 5) 332 Length += 2; // Address + Segment selector sizes. 333 return Length; 334 } 335 336 Error DWARFDebugLine::Prologue::parse( 337 const DWARFDataExtractor &DebugLineData, uint64_t *OffsetPtr, 338 function_ref<void(Error)> RecoverableErrorHandler, const DWARFContext &Ctx, 339 const DWARFUnit *U) { 340 const uint64_t PrologueOffset = *OffsetPtr; 341 342 clear(); 343 Error Err = Error::success(); 344 std::tie(TotalLength, FormParams.Format) = 345 DebugLineData.getInitialLength(OffsetPtr, &Err); 346 if (Err) 347 return createStringError( 348 errc::invalid_argument, 349 "parsing line table prologue at offset 0x%8.8" PRIx64 ": %s", 350 PrologueOffset, toString(std::move(Err)).c_str()); 351 352 FormParams.Version = DebugLineData.getU16(OffsetPtr); 353 if (!versionIsSupported(getVersion())) 354 // Treat this error as unrecoverable - we cannot be sure what any of 355 // the data represents including the length field, so cannot skip it or make 356 // any reasonable assumptions. 357 return createStringError( 358 errc::not_supported, 359 "parsing line table prologue at offset 0x%8.8" PRIx64 360 ": unsupported version %" PRIu16, 361 PrologueOffset, getVersion()); 362 363 if (getVersion() >= 5) { 364 FormParams.AddrSize = DebugLineData.getU8(OffsetPtr); 365 assert((DebugLineData.getAddressSize() == 0 || 366 DebugLineData.getAddressSize() == getAddressSize()) && 367 "Line table header and data extractor disagree"); 368 SegSelectorSize = DebugLineData.getU8(OffsetPtr); 369 } 370 371 PrologueLength = 372 DebugLineData.getRelocatedValue(sizeofPrologueLength(), OffsetPtr); 373 const uint64_t EndPrologueOffset = PrologueLength + *OffsetPtr; 374 MinInstLength = DebugLineData.getU8(OffsetPtr); 375 if (getVersion() >= 4) 376 MaxOpsPerInst = DebugLineData.getU8(OffsetPtr); 377 DefaultIsStmt = DebugLineData.getU8(OffsetPtr); 378 LineBase = DebugLineData.getU8(OffsetPtr); 379 LineRange = DebugLineData.getU8(OffsetPtr); 380 OpcodeBase = DebugLineData.getU8(OffsetPtr); 381 382 if (OpcodeBase == 0) { 383 // If the opcode base is 0, we cannot read the standard opcode lengths (of 384 // which there are supposed to be one fewer than the opcode base). Assume 385 // there are no standard opcodes and continue parsing. 386 RecoverableErrorHandler(createStringError( 387 errc::invalid_argument, 388 "parsing line table prologue at offset 0x%8.8" PRIx64 389 " found opcode base of 0. Assuming no standard opcodes", 390 PrologueOffset)); 391 } else { 392 StandardOpcodeLengths.reserve(OpcodeBase - 1); 393 for (uint32_t I = 1; I < OpcodeBase; ++I) { 394 uint8_t OpLen = DebugLineData.getU8(OffsetPtr); 395 StandardOpcodeLengths.push_back(OpLen); 396 } 397 } 398 399 auto ReportInvalidDirFileTable = [&](Error E) { 400 RecoverableErrorHandler(joinErrors( 401 createStringError( 402 errc::invalid_argument, 403 "parsing line table prologue at 0x%8.8" PRIx64 404 " found an invalid directory or file table description at" 405 " 0x%8.8" PRIx64, 406 PrologueOffset, *OffsetPtr), 407 std::move(E))); 408 // Skip to the end of the prologue, since the chances are that the parser 409 // did not read the whole table. This prevents the length check below from 410 // executing. 411 if (*OffsetPtr < EndPrologueOffset) 412 *OffsetPtr = EndPrologueOffset; 413 }; 414 if (getVersion() >= 5) { 415 if (Error E = 416 parseV5DirFileTables(DebugLineData, OffsetPtr, FormParams, Ctx, U, 417 ContentTypes, IncludeDirectories, FileNames)) 418 ReportInvalidDirFileTable(std::move(E)); 419 } else if (Error E = parseV2DirFileTables(DebugLineData, OffsetPtr, 420 EndPrologueOffset, ContentTypes, 421 IncludeDirectories, FileNames)) 422 ReportInvalidDirFileTable(std::move(E)); 423 424 if (*OffsetPtr != EndPrologueOffset) { 425 RecoverableErrorHandler(createStringError( 426 errc::invalid_argument, 427 "parsing line table prologue at 0x%8.8" PRIx64 428 " should have ended at 0x%8.8" PRIx64 " but it ended at 0x%8.8" PRIx64, 429 PrologueOffset, EndPrologueOffset, *OffsetPtr)); 430 *OffsetPtr = EndPrologueOffset; 431 } 432 return Error::success(); 433 } 434 435 DWARFDebugLine::Row::Row(bool DefaultIsStmt) { reset(DefaultIsStmt); } 436 437 void DWARFDebugLine::Row::postAppend() { 438 Discriminator = 0; 439 BasicBlock = false; 440 PrologueEnd = false; 441 EpilogueBegin = false; 442 } 443 444 void DWARFDebugLine::Row::reset(bool DefaultIsStmt) { 445 Address.Address = 0; 446 Address.SectionIndex = object::SectionedAddress::UndefSection; 447 Line = 1; 448 Column = 0; 449 File = 1; 450 Isa = 0; 451 Discriminator = 0; 452 IsStmt = DefaultIsStmt; 453 BasicBlock = false; 454 EndSequence = false; 455 PrologueEnd = false; 456 EpilogueBegin = false; 457 } 458 459 void DWARFDebugLine::Row::dumpTableHeader(raw_ostream &OS) { 460 OS << "Address Line Column File ISA Discriminator Flags\n" 461 << "------------------ ------ ------ ------ --- ------------- " 462 "-------------\n"; 463 } 464 465 void DWARFDebugLine::Row::dump(raw_ostream &OS) const { 466 OS << format("0x%16.16" PRIx64 " %6u %6u", Address.Address, Line, Column) 467 << format(" %6u %3u %13u ", File, Isa, Discriminator) 468 << (IsStmt ? " is_stmt" : "") << (BasicBlock ? " basic_block" : "") 469 << (PrologueEnd ? " prologue_end" : "") 470 << (EpilogueBegin ? " epilogue_begin" : "") 471 << (EndSequence ? " end_sequence" : "") << '\n'; 472 } 473 474 DWARFDebugLine::Sequence::Sequence() { reset(); } 475 476 void DWARFDebugLine::Sequence::reset() { 477 LowPC = 0; 478 HighPC = 0; 479 SectionIndex = object::SectionedAddress::UndefSection; 480 FirstRowIndex = 0; 481 LastRowIndex = 0; 482 Empty = true; 483 } 484 485 DWARFDebugLine::LineTable::LineTable() { clear(); } 486 487 void DWARFDebugLine::LineTable::dump(raw_ostream &OS, 488 DIDumpOptions DumpOptions) const { 489 Prologue.dump(OS, DumpOptions); 490 491 if (!Rows.empty()) { 492 OS << '\n'; 493 Row::dumpTableHeader(OS); 494 for (const Row &R : Rows) { 495 R.dump(OS); 496 } 497 } 498 499 // Terminate the table with a final blank line to clearly delineate it from 500 // later dumps. 501 OS << '\n'; 502 } 503 504 void DWARFDebugLine::LineTable::clear() { 505 Prologue.clear(); 506 Rows.clear(); 507 Sequences.clear(); 508 } 509 510 DWARFDebugLine::ParsingState::ParsingState(struct LineTable *LT) 511 : LineTable(LT) { 512 resetRowAndSequence(); 513 } 514 515 void DWARFDebugLine::ParsingState::resetRowAndSequence() { 516 Row.reset(LineTable->Prologue.DefaultIsStmt); 517 Sequence.reset(); 518 } 519 520 void DWARFDebugLine::ParsingState::appendRowToMatrix() { 521 unsigned RowNumber = LineTable->Rows.size(); 522 if (Sequence.Empty) { 523 // Record the beginning of instruction sequence. 524 Sequence.Empty = false; 525 Sequence.LowPC = Row.Address.Address; 526 Sequence.FirstRowIndex = RowNumber; 527 } 528 LineTable->appendRow(Row); 529 if (Row.EndSequence) { 530 // Record the end of instruction sequence. 531 Sequence.HighPC = Row.Address.Address; 532 Sequence.LastRowIndex = RowNumber + 1; 533 Sequence.SectionIndex = Row.Address.SectionIndex; 534 if (Sequence.isValid()) 535 LineTable->appendSequence(Sequence); 536 Sequence.reset(); 537 } 538 Row.postAppend(); 539 } 540 541 const DWARFDebugLine::LineTable * 542 DWARFDebugLine::getLineTable(uint64_t Offset) const { 543 LineTableConstIter Pos = LineTableMap.find(Offset); 544 if (Pos != LineTableMap.end()) 545 return &Pos->second; 546 return nullptr; 547 } 548 549 Expected<const DWARFDebugLine::LineTable *> DWARFDebugLine::getOrParseLineTable( 550 DWARFDataExtractor &DebugLineData, uint64_t Offset, const DWARFContext &Ctx, 551 const DWARFUnit *U, function_ref<void(Error)> RecoverableErrorHandler) { 552 if (!DebugLineData.isValidOffset(Offset)) 553 return createStringError(errc::invalid_argument, "offset 0x%8.8" PRIx64 554 " is not a valid debug line section offset", 555 Offset); 556 557 std::pair<LineTableIter, bool> Pos = 558 LineTableMap.insert(LineTableMapTy::value_type(Offset, LineTable())); 559 LineTable *LT = &Pos.first->second; 560 if (Pos.second) { 561 if (Error Err = 562 LT->parse(DebugLineData, &Offset, Ctx, U, RecoverableErrorHandler)) 563 return std::move(Err); 564 return LT; 565 } 566 return LT; 567 } 568 569 Error DWARFDebugLine::LineTable::parse( 570 DWARFDataExtractor &DebugLineData, uint64_t *OffsetPtr, 571 const DWARFContext &Ctx, const DWARFUnit *U, 572 function_ref<void(Error)> RecoverableErrorHandler, raw_ostream *OS) { 573 const uint64_t DebugLineOffset = *OffsetPtr; 574 575 clear(); 576 577 Error PrologueErr = 578 Prologue.parse(DebugLineData, OffsetPtr, RecoverableErrorHandler, Ctx, U); 579 580 if (OS) { 581 // The presence of OS signals verbose dumping. 582 DIDumpOptions DumpOptions; 583 DumpOptions.Verbose = true; 584 Prologue.dump(*OS, DumpOptions); 585 } 586 587 if (PrologueErr) 588 return PrologueErr; 589 590 uint64_t ProgramLength = Prologue.TotalLength + Prologue.sizeofTotalLength(); 591 if (!DebugLineData.isValidOffsetForDataOfSize(DebugLineOffset, 592 ProgramLength)) { 593 assert(DebugLineData.size() > DebugLineOffset && 594 "prologue parsing should handle invalid offset"); 595 uint64_t BytesRemaining = DebugLineData.size() - DebugLineOffset; 596 RecoverableErrorHandler( 597 createStringError(errc::invalid_argument, 598 "line table program with offset 0x%8.8" PRIx64 599 " has length 0x%8.8" PRIx64 " but only 0x%8.8" PRIx64 600 " bytes are available", 601 DebugLineOffset, ProgramLength, BytesRemaining)); 602 // Continue by capping the length at the number of remaining bytes. 603 ProgramLength = BytesRemaining; 604 } 605 606 const uint64_t EndOffset = DebugLineOffset + ProgramLength; 607 608 // See if we should tell the data extractor the address size. 609 if (DebugLineData.getAddressSize() == 0) 610 DebugLineData.setAddressSize(Prologue.getAddressSize()); 611 else 612 assert(Prologue.getAddressSize() == 0 || 613 Prologue.getAddressSize() == DebugLineData.getAddressSize()); 614 615 ParsingState State(this); 616 617 while (*OffsetPtr < EndOffset) { 618 if (OS) 619 *OS << format("0x%08.08" PRIx64 ": ", *OffsetPtr); 620 621 uint8_t Opcode = DebugLineData.getU8(OffsetPtr); 622 623 if (OS) 624 *OS << format("%02.02" PRIx8 " ", Opcode); 625 626 if (Opcode == 0) { 627 // Extended Opcodes always start with a zero opcode followed by 628 // a uleb128 length so you can skip ones you don't know about 629 uint64_t Len = DebugLineData.getULEB128(OffsetPtr); 630 uint64_t ExtOffset = *OffsetPtr; 631 632 // Tolerate zero-length; assume length is correct and soldier on. 633 if (Len == 0) { 634 if (OS) 635 *OS << "Badly formed extended line op (length 0)\n"; 636 continue; 637 } 638 639 uint8_t SubOpcode = DebugLineData.getU8(OffsetPtr); 640 if (OS) 641 *OS << LNExtendedString(SubOpcode); 642 switch (SubOpcode) { 643 case DW_LNE_end_sequence: 644 // Set the end_sequence register of the state machine to true and 645 // append a row to the matrix using the current values of the 646 // state-machine registers. Then reset the registers to the initial 647 // values specified above. Every statement program sequence must end 648 // with a DW_LNE_end_sequence instruction which creates a row whose 649 // address is that of the byte after the last target machine instruction 650 // of the sequence. 651 State.Row.EndSequence = true; 652 if (OS) { 653 *OS << "\n"; 654 OS->indent(12); 655 State.Row.dump(*OS); 656 } 657 State.appendRowToMatrix(); 658 State.resetRowAndSequence(); 659 break; 660 661 case DW_LNE_set_address: 662 // Takes a single relocatable address as an operand. The size of the 663 // operand is the size appropriate to hold an address on the target 664 // machine. Set the address register to the value given by the 665 // relocatable address. All of the other statement program opcodes 666 // that affect the address register add a delta to it. This instruction 667 // stores a relocatable value into it instead. 668 // 669 // Make sure the extractor knows the address size. If not, infer it 670 // from the size of the operand. 671 { 672 uint8_t ExtractorAddressSize = DebugLineData.getAddressSize(); 673 uint64_t OpcodeAddressSize = Len - 1; 674 if (ExtractorAddressSize != OpcodeAddressSize && 675 ExtractorAddressSize != 0) 676 RecoverableErrorHandler(createStringError( 677 errc::invalid_argument, 678 "mismatching address size at offset 0x%8.8" PRIx64 679 " expected 0x%2.2" PRIx8 " found 0x%2.2" PRIx64, 680 ExtOffset, ExtractorAddressSize, Len - 1)); 681 682 // Assume that the line table is correct and temporarily override the 683 // address size. If the size is unsupported, give up trying to read 684 // the address and continue to the next opcode. 685 if (OpcodeAddressSize != 1 && OpcodeAddressSize != 2 && 686 OpcodeAddressSize != 4 && OpcodeAddressSize != 8) { 687 RecoverableErrorHandler(createStringError( 688 errc::invalid_argument, 689 "address size 0x%2.2" PRIx64 690 " of DW_LNE_set_address opcode at offset 0x%8.8" PRIx64 691 " is unsupported", 692 OpcodeAddressSize, ExtOffset)); 693 *OffsetPtr += OpcodeAddressSize; 694 } else { 695 DebugLineData.setAddressSize(OpcodeAddressSize); 696 State.Row.Address.Address = DebugLineData.getRelocatedAddress( 697 OffsetPtr, &State.Row.Address.SectionIndex); 698 699 // Restore the address size if the extractor already had it. 700 if (ExtractorAddressSize != 0) 701 DebugLineData.setAddressSize(ExtractorAddressSize); 702 } 703 704 if (OS) 705 *OS << format(" (0x%16.16" PRIx64 ")", State.Row.Address.Address); 706 } 707 break; 708 709 case DW_LNE_define_file: 710 // Takes 4 arguments. The first is a null terminated string containing 711 // a source file name. The second is an unsigned LEB128 number 712 // representing the directory index of the directory in which the file 713 // was found. The third is an unsigned LEB128 number representing the 714 // time of last modification of the file. The fourth is an unsigned 715 // LEB128 number representing the length in bytes of the file. The time 716 // and length fields may contain LEB128(0) if the information is not 717 // available. 718 // 719 // The directory index represents an entry in the include_directories 720 // section of the statement program prologue. The index is LEB128(0) 721 // if the file was found in the current directory of the compilation, 722 // LEB128(1) if it was found in the first directory in the 723 // include_directories section, and so on. The directory index is 724 // ignored for file names that represent full path names. 725 // 726 // The files are numbered, starting at 1, in the order in which they 727 // appear; the names in the prologue come before names defined by 728 // the DW_LNE_define_file instruction. These numbers are used in the 729 // the file register of the state machine. 730 { 731 FileNameEntry FileEntry; 732 const char *Name = DebugLineData.getCStr(OffsetPtr); 733 FileEntry.Name = 734 DWARFFormValue::createFromPValue(dwarf::DW_FORM_string, Name); 735 FileEntry.DirIdx = DebugLineData.getULEB128(OffsetPtr); 736 FileEntry.ModTime = DebugLineData.getULEB128(OffsetPtr); 737 FileEntry.Length = DebugLineData.getULEB128(OffsetPtr); 738 Prologue.FileNames.push_back(FileEntry); 739 if (OS) 740 *OS << " (" << Name << ", dir=" << FileEntry.DirIdx << ", mod_time=" 741 << format("(0x%16.16" PRIx64 ")", FileEntry.ModTime) 742 << ", length=" << FileEntry.Length << ")"; 743 } 744 break; 745 746 case DW_LNE_set_discriminator: 747 State.Row.Discriminator = DebugLineData.getULEB128(OffsetPtr); 748 if (OS) 749 *OS << " (" << State.Row.Discriminator << ")"; 750 break; 751 752 default: 753 if (OS) 754 *OS << format("Unrecognized extended op 0x%02.02" PRIx8, SubOpcode) 755 << format(" length %" PRIx64, Len); 756 // Len doesn't include the zero opcode byte or the length itself, but 757 // it does include the sub_opcode, so we have to adjust for that. 758 (*OffsetPtr) += Len - 1; 759 break; 760 } 761 // Make sure the length as recorded in the table and the standard length 762 // for the opcode match. If they don't, continue from the end as claimed 763 // by the table. 764 uint64_t End = ExtOffset + Len; 765 if (*OffsetPtr != End) { 766 RecoverableErrorHandler(createStringError( 767 errc::illegal_byte_sequence, 768 "unexpected line op length at offset 0x%8.8" PRIx64 769 " expected 0x%2.2" PRIx64 " found 0x%2.2" PRIx64, 770 ExtOffset, Len, *OffsetPtr - ExtOffset)); 771 *OffsetPtr = End; 772 } 773 } else if (Opcode < Prologue.OpcodeBase) { 774 if (OS) 775 *OS << LNStandardString(Opcode); 776 switch (Opcode) { 777 // Standard Opcodes 778 case DW_LNS_copy: 779 // Takes no arguments. Append a row to the matrix using the 780 // current values of the state-machine registers. 781 if (OS) { 782 *OS << "\n"; 783 OS->indent(12); 784 State.Row.dump(*OS); 785 *OS << "\n"; 786 } 787 State.appendRowToMatrix(); 788 break; 789 790 case DW_LNS_advance_pc: 791 // Takes a single unsigned LEB128 operand, multiplies it by the 792 // min_inst_length field of the prologue, and adds the 793 // result to the address register of the state machine. 794 { 795 uint64_t AddrOffset = 796 DebugLineData.getULEB128(OffsetPtr) * Prologue.MinInstLength; 797 State.Row.Address.Address += AddrOffset; 798 if (OS) 799 *OS << " (" << AddrOffset << ")"; 800 } 801 break; 802 803 case DW_LNS_advance_line: 804 // Takes a single signed LEB128 operand and adds that value to 805 // the line register of the state machine. 806 State.Row.Line += DebugLineData.getSLEB128(OffsetPtr); 807 if (OS) 808 *OS << " (" << State.Row.Line << ")"; 809 break; 810 811 case DW_LNS_set_file: 812 // Takes a single unsigned LEB128 operand and stores it in the file 813 // register of the state machine. 814 State.Row.File = DebugLineData.getULEB128(OffsetPtr); 815 if (OS) 816 *OS << " (" << State.Row.File << ")"; 817 break; 818 819 case DW_LNS_set_column: 820 // Takes a single unsigned LEB128 operand and stores it in the 821 // column register of the state machine. 822 State.Row.Column = DebugLineData.getULEB128(OffsetPtr); 823 if (OS) 824 *OS << " (" << State.Row.Column << ")"; 825 break; 826 827 case DW_LNS_negate_stmt: 828 // Takes no arguments. Set the is_stmt register of the state 829 // machine to the logical negation of its current value. 830 State.Row.IsStmt = !State.Row.IsStmt; 831 break; 832 833 case DW_LNS_set_basic_block: 834 // Takes no arguments. Set the basic_block register of the 835 // state machine to true 836 State.Row.BasicBlock = true; 837 break; 838 839 case DW_LNS_const_add_pc: 840 // Takes no arguments. Add to the address register of the state 841 // machine the address increment value corresponding to special 842 // opcode 255. The motivation for DW_LNS_const_add_pc is this: 843 // when the statement program needs to advance the address by a 844 // small amount, it can use a single special opcode, which occupies 845 // a single byte. When it needs to advance the address by up to 846 // twice the range of the last special opcode, it can use 847 // DW_LNS_const_add_pc followed by a special opcode, for a total 848 // of two bytes. Only if it needs to advance the address by more 849 // than twice that range will it need to use both DW_LNS_advance_pc 850 // and a special opcode, requiring three or more bytes. 851 { 852 uint8_t AdjustOpcode = 255 - Prologue.OpcodeBase; 853 uint64_t AddrOffset = 854 (AdjustOpcode / Prologue.LineRange) * Prologue.MinInstLength; 855 State.Row.Address.Address += AddrOffset; 856 if (OS) 857 *OS 858 << format(" (0x%16.16" PRIx64 ")", AddrOffset); 859 } 860 break; 861 862 case DW_LNS_fixed_advance_pc: 863 // Takes a single uhalf operand. Add to the address register of 864 // the state machine the value of the (unencoded) operand. This 865 // is the only extended opcode that takes an argument that is not 866 // a variable length number. The motivation for DW_LNS_fixed_advance_pc 867 // is this: existing assemblers cannot emit DW_LNS_advance_pc or 868 // special opcodes because they cannot encode LEB128 numbers or 869 // judge when the computation of a special opcode overflows and 870 // requires the use of DW_LNS_advance_pc. Such assemblers, however, 871 // can use DW_LNS_fixed_advance_pc instead, sacrificing compression. 872 { 873 uint16_t PCOffset = DebugLineData.getRelocatedValue(2, OffsetPtr); 874 State.Row.Address.Address += PCOffset; 875 if (OS) 876 *OS 877 << format(" (0x%4.4" PRIx16 ")", PCOffset); 878 } 879 break; 880 881 case DW_LNS_set_prologue_end: 882 // Takes no arguments. Set the prologue_end register of the 883 // state machine to true 884 State.Row.PrologueEnd = true; 885 break; 886 887 case DW_LNS_set_epilogue_begin: 888 // Takes no arguments. Set the basic_block register of the 889 // state machine to true 890 State.Row.EpilogueBegin = true; 891 break; 892 893 case DW_LNS_set_isa: 894 // Takes a single unsigned LEB128 operand and stores it in the 895 // column register of the state machine. 896 State.Row.Isa = DebugLineData.getULEB128(OffsetPtr); 897 if (OS) 898 *OS << " (" << (uint64_t)State.Row.Isa << ")"; 899 break; 900 901 default: 902 // Handle any unknown standard opcodes here. We know the lengths 903 // of such opcodes because they are specified in the prologue 904 // as a multiple of LEB128 operands for each opcode. 905 { 906 assert(Opcode - 1U < Prologue.StandardOpcodeLengths.size()); 907 uint8_t OpcodeLength = Prologue.StandardOpcodeLengths[Opcode - 1]; 908 for (uint8_t I = 0; I < OpcodeLength; ++I) { 909 uint64_t Value = DebugLineData.getULEB128(OffsetPtr); 910 if (OS) 911 *OS << format("Skipping ULEB128 value: 0x%16.16" PRIx64 ")\n", 912 Value); 913 } 914 } 915 break; 916 } 917 } else { 918 // Special Opcodes 919 920 // A special opcode value is chosen based on the amount that needs 921 // to be added to the line and address registers. The maximum line 922 // increment for a special opcode is the value of the line_base 923 // field in the header, plus the value of the line_range field, 924 // minus 1 (line base + line range - 1). If the desired line 925 // increment is greater than the maximum line increment, a standard 926 // opcode must be used instead of a special opcode. The "address 927 // advance" is calculated by dividing the desired address increment 928 // by the minimum_instruction_length field from the header. The 929 // special opcode is then calculated using the following formula: 930 // 931 // opcode = (desired line increment - line_base) + 932 // (line_range * address advance) + opcode_base 933 // 934 // If the resulting opcode is greater than 255, a standard opcode 935 // must be used instead. 936 // 937 // To decode a special opcode, subtract the opcode_base from the 938 // opcode itself to give the adjusted opcode. The amount to 939 // increment the address register is the result of the adjusted 940 // opcode divided by the line_range multiplied by the 941 // minimum_instruction_length field from the header. That is: 942 // 943 // address increment = (adjusted opcode / line_range) * 944 // minimum_instruction_length 945 // 946 // The amount to increment the line register is the line_base plus 947 // the result of the adjusted opcode modulo the line_range. That is: 948 // 949 // line increment = line_base + (adjusted opcode % line_range) 950 951 uint8_t AdjustOpcode = Opcode - Prologue.OpcodeBase; 952 uint64_t AddrOffset = 953 (AdjustOpcode / Prologue.LineRange) * Prologue.MinInstLength; 954 int32_t LineOffset = 955 Prologue.LineBase + (AdjustOpcode % Prologue.LineRange); 956 State.Row.Line += LineOffset; 957 State.Row.Address.Address += AddrOffset; 958 959 if (OS) { 960 *OS << "address += " << AddrOffset << ", line += " << LineOffset 961 << "\n"; 962 OS->indent(12); 963 State.Row.dump(*OS); 964 } 965 966 State.appendRowToMatrix(); 967 } 968 if(OS) 969 *OS << "\n"; 970 } 971 972 if (!State.Sequence.Empty) 973 RecoverableErrorHandler(createStringError( 974 errc::illegal_byte_sequence, 975 "last sequence in debug line table at offset 0x%8.8" PRIx64 976 " is not terminated", 977 DebugLineOffset)); 978 979 // Sort all sequences so that address lookup will work faster. 980 if (!Sequences.empty()) { 981 llvm::sort(Sequences, Sequence::orderByHighPC); 982 // Note: actually, instruction address ranges of sequences should not 983 // overlap (in shared objects and executables). If they do, the address 984 // lookup would still work, though, but result would be ambiguous. 985 // We don't report warning in this case. For example, 986 // sometimes .so compiled from multiple object files contains a few 987 // rudimentary sequences for address ranges [0x0, 0xsomething). 988 } 989 990 return Error::success(); 991 } 992 993 uint32_t DWARFDebugLine::LineTable::findRowInSeq( 994 const DWARFDebugLine::Sequence &Seq, 995 object::SectionedAddress Address) const { 996 if (!Seq.containsPC(Address)) 997 return UnknownRowIndex; 998 assert(Seq.SectionIndex == Address.SectionIndex); 999 // In some cases, e.g. first instruction in a function, the compiler generates 1000 // two entries, both with the same address. We want the last one. 1001 // 1002 // In general we want a non-empty range: the last row whose address is less 1003 // than or equal to Address. This can be computed as upper_bound - 1. 1004 DWARFDebugLine::Row Row; 1005 Row.Address = Address; 1006 RowIter FirstRow = Rows.begin() + Seq.FirstRowIndex; 1007 RowIter LastRow = Rows.begin() + Seq.LastRowIndex; 1008 assert(FirstRow->Address.Address <= Row.Address.Address && 1009 Row.Address.Address < LastRow[-1].Address.Address); 1010 RowIter RowPos = std::upper_bound(FirstRow + 1, LastRow - 1, Row, 1011 DWARFDebugLine::Row::orderByAddress) - 1012 1; 1013 assert(Seq.SectionIndex == RowPos->Address.SectionIndex); 1014 return RowPos - Rows.begin(); 1015 } 1016 1017 uint32_t DWARFDebugLine::LineTable::lookupAddress( 1018 object::SectionedAddress Address) const { 1019 1020 // Search for relocatable addresses 1021 uint32_t Result = lookupAddressImpl(Address); 1022 1023 if (Result != UnknownRowIndex || 1024 Address.SectionIndex == object::SectionedAddress::UndefSection) 1025 return Result; 1026 1027 // Search for absolute addresses 1028 Address.SectionIndex = object::SectionedAddress::UndefSection; 1029 return lookupAddressImpl(Address); 1030 } 1031 1032 uint32_t DWARFDebugLine::LineTable::lookupAddressImpl( 1033 object::SectionedAddress Address) const { 1034 // First, find an instruction sequence containing the given address. 1035 DWARFDebugLine::Sequence Sequence; 1036 Sequence.SectionIndex = Address.SectionIndex; 1037 Sequence.HighPC = Address.Address; 1038 SequenceIter It = llvm::upper_bound(Sequences, Sequence, 1039 DWARFDebugLine::Sequence::orderByHighPC); 1040 if (It == Sequences.end() || It->SectionIndex != Address.SectionIndex) 1041 return UnknownRowIndex; 1042 return findRowInSeq(*It, Address); 1043 } 1044 1045 bool DWARFDebugLine::LineTable::lookupAddressRange( 1046 object::SectionedAddress Address, uint64_t Size, 1047 std::vector<uint32_t> &Result) const { 1048 1049 // Search for relocatable addresses 1050 if (lookupAddressRangeImpl(Address, Size, Result)) 1051 return true; 1052 1053 if (Address.SectionIndex == object::SectionedAddress::UndefSection) 1054 return false; 1055 1056 // Search for absolute addresses 1057 Address.SectionIndex = object::SectionedAddress::UndefSection; 1058 return lookupAddressRangeImpl(Address, Size, Result); 1059 } 1060 1061 bool DWARFDebugLine::LineTable::lookupAddressRangeImpl( 1062 object::SectionedAddress Address, uint64_t Size, 1063 std::vector<uint32_t> &Result) const { 1064 if (Sequences.empty()) 1065 return false; 1066 uint64_t EndAddr = Address.Address + Size; 1067 // First, find an instruction sequence containing the given address. 1068 DWARFDebugLine::Sequence Sequence; 1069 Sequence.SectionIndex = Address.SectionIndex; 1070 Sequence.HighPC = Address.Address; 1071 SequenceIter LastSeq = Sequences.end(); 1072 SequenceIter SeqPos = llvm::upper_bound( 1073 Sequences, Sequence, DWARFDebugLine::Sequence::orderByHighPC); 1074 if (SeqPos == LastSeq || !SeqPos->containsPC(Address)) 1075 return false; 1076 1077 SequenceIter StartPos = SeqPos; 1078 1079 // Add the rows from the first sequence to the vector, starting with the 1080 // index we just calculated 1081 1082 while (SeqPos != LastSeq && SeqPos->LowPC < EndAddr) { 1083 const DWARFDebugLine::Sequence &CurSeq = *SeqPos; 1084 // For the first sequence, we need to find which row in the sequence is the 1085 // first in our range. 1086 uint32_t FirstRowIndex = CurSeq.FirstRowIndex; 1087 if (SeqPos == StartPos) 1088 FirstRowIndex = findRowInSeq(CurSeq, Address); 1089 1090 // Figure out the last row in the range. 1091 uint32_t LastRowIndex = 1092 findRowInSeq(CurSeq, {EndAddr - 1, Address.SectionIndex}); 1093 if (LastRowIndex == UnknownRowIndex) 1094 LastRowIndex = CurSeq.LastRowIndex - 1; 1095 1096 assert(FirstRowIndex != UnknownRowIndex); 1097 assert(LastRowIndex != UnknownRowIndex); 1098 1099 for (uint32_t I = FirstRowIndex; I <= LastRowIndex; ++I) { 1100 Result.push_back(I); 1101 } 1102 1103 ++SeqPos; 1104 } 1105 1106 return true; 1107 } 1108 1109 Optional<StringRef> DWARFDebugLine::LineTable::getSourceByIndex(uint64_t FileIndex, 1110 FileLineInfoKind Kind) const { 1111 if (Kind == FileLineInfoKind::None || !Prologue.hasFileAtIndex(FileIndex)) 1112 return None; 1113 const FileNameEntry &Entry = Prologue.getFileNameEntry(FileIndex); 1114 if (Optional<const char *> source = Entry.Source.getAsCString()) 1115 return StringRef(*source); 1116 return None; 1117 } 1118 1119 static bool isPathAbsoluteOnWindowsOrPosix(const Twine &Path) { 1120 // Debug info can contain paths from any OS, not necessarily 1121 // an OS we're currently running on. Moreover different compilation units can 1122 // be compiled on different operating systems and linked together later. 1123 return sys::path::is_absolute(Path, sys::path::Style::posix) || 1124 sys::path::is_absolute(Path, sys::path::Style::windows); 1125 } 1126 1127 bool DWARFDebugLine::Prologue::getFileNameByIndex( 1128 uint64_t FileIndex, StringRef CompDir, FileLineInfoKind Kind, 1129 std::string &Result, sys::path::Style Style) const { 1130 if (Kind == FileLineInfoKind::None || !hasFileAtIndex(FileIndex)) 1131 return false; 1132 const FileNameEntry &Entry = getFileNameEntry(FileIndex); 1133 Optional<const char *> Name = Entry.Name.getAsCString(); 1134 if (!Name) 1135 return false; 1136 StringRef FileName = *Name; 1137 if (Kind == FileLineInfoKind::Default || 1138 isPathAbsoluteOnWindowsOrPosix(FileName)) { 1139 Result = std::string(FileName); 1140 return true; 1141 } 1142 1143 SmallString<16> FilePath; 1144 StringRef IncludeDir; 1145 // Be defensive about the contents of Entry. 1146 if (getVersion() >= 5) { 1147 if (Entry.DirIdx < IncludeDirectories.size()) 1148 IncludeDir = IncludeDirectories[Entry.DirIdx].getAsCString().getValue(); 1149 } else { 1150 if (0 < Entry.DirIdx && Entry.DirIdx <= IncludeDirectories.size()) 1151 IncludeDir = 1152 IncludeDirectories[Entry.DirIdx - 1].getAsCString().getValue(); 1153 } 1154 // For absolute paths only, include the compilation directory of compile unit. 1155 // We know that FileName is not absolute, the only way to have an absolute 1156 // path at this point would be if IncludeDir is absolute. 1157 if (Kind == FileLineInfoKind::AbsoluteFilePath && !CompDir.empty() && 1158 !isPathAbsoluteOnWindowsOrPosix(IncludeDir)) 1159 sys::path::append(FilePath, Style, CompDir); 1160 1161 assert((Kind == FileLineInfoKind::AbsoluteFilePath || 1162 Kind == FileLineInfoKind::RelativeFilePath) && 1163 "invalid FileLineInfo Kind"); 1164 1165 // sys::path::append skips empty strings. 1166 sys::path::append(FilePath, Style, IncludeDir, FileName); 1167 Result = std::string(FilePath.str()); 1168 return true; 1169 } 1170 1171 bool DWARFDebugLine::LineTable::getFileLineInfoForAddress( 1172 object::SectionedAddress Address, const char *CompDir, 1173 FileLineInfoKind Kind, DILineInfo &Result) const { 1174 // Get the index of row we're looking for in the line table. 1175 uint32_t RowIndex = lookupAddress(Address); 1176 if (RowIndex == -1U) 1177 return false; 1178 // Take file number and line/column from the row. 1179 const auto &Row = Rows[RowIndex]; 1180 if (!getFileNameByIndex(Row.File, CompDir, Kind, Result.FileName)) 1181 return false; 1182 Result.Line = Row.Line; 1183 Result.Column = Row.Column; 1184 Result.Discriminator = Row.Discriminator; 1185 Result.Source = getSourceByIndex(Row.File, Kind); 1186 return true; 1187 } 1188 1189 // We want to supply the Unit associated with a .debug_line[.dwo] table when 1190 // we dump it, if possible, but still dump the table even if there isn't a Unit. 1191 // Therefore, collect up handles on all the Units that point into the 1192 // line-table section. 1193 static DWARFDebugLine::SectionParser::LineToUnitMap 1194 buildLineToUnitMap(DWARFDebugLine::SectionParser::cu_range CUs, 1195 DWARFDebugLine::SectionParser::tu_range TUs) { 1196 DWARFDebugLine::SectionParser::LineToUnitMap LineToUnit; 1197 for (const auto &CU : CUs) 1198 if (auto CUDIE = CU->getUnitDIE()) 1199 if (auto StmtOffset = toSectionOffset(CUDIE.find(DW_AT_stmt_list))) 1200 LineToUnit.insert(std::make_pair(*StmtOffset, &*CU)); 1201 for (const auto &TU : TUs) 1202 if (auto TUDIE = TU->getUnitDIE()) 1203 if (auto StmtOffset = toSectionOffset(TUDIE.find(DW_AT_stmt_list))) 1204 LineToUnit.insert(std::make_pair(*StmtOffset, &*TU)); 1205 return LineToUnit; 1206 } 1207 1208 DWARFDebugLine::SectionParser::SectionParser(DWARFDataExtractor &Data, 1209 const DWARFContext &C, 1210 cu_range CUs, tu_range TUs) 1211 : DebugLineData(Data), Context(C) { 1212 LineToUnit = buildLineToUnitMap(CUs, TUs); 1213 if (!DebugLineData.isValidOffset(Offset)) 1214 Done = true; 1215 } 1216 1217 bool DWARFDebugLine::Prologue::totalLengthIsValid() const { 1218 return TotalLength != 0u; 1219 } 1220 1221 DWARFDebugLine::LineTable DWARFDebugLine::SectionParser::parseNext( 1222 function_ref<void(Error)> RecoverableErrorHandler, 1223 function_ref<void(Error)> UnrecoverableErrorHandler, raw_ostream *OS) { 1224 assert(DebugLineData.isValidOffset(Offset) && 1225 "parsing should have terminated"); 1226 DWARFUnit *U = prepareToParse(Offset); 1227 uint64_t OldOffset = Offset; 1228 LineTable LT; 1229 if (Error Err = LT.parse(DebugLineData, &Offset, Context, U, 1230 RecoverableErrorHandler, OS)) 1231 UnrecoverableErrorHandler(std::move(Err)); 1232 moveToNextTable(OldOffset, LT.Prologue); 1233 return LT; 1234 } 1235 1236 void DWARFDebugLine::SectionParser::skip( 1237 function_ref<void(Error)> RecoverableErrorHandler, 1238 function_ref<void(Error)> UnrecoverableErrorHandler) { 1239 assert(DebugLineData.isValidOffset(Offset) && 1240 "parsing should have terminated"); 1241 DWARFUnit *U = prepareToParse(Offset); 1242 uint64_t OldOffset = Offset; 1243 LineTable LT; 1244 if (Error Err = LT.Prologue.parse(DebugLineData, &Offset, 1245 RecoverableErrorHandler, Context, U)) 1246 UnrecoverableErrorHandler(std::move(Err)); 1247 moveToNextTable(OldOffset, LT.Prologue); 1248 } 1249 1250 DWARFUnit *DWARFDebugLine::SectionParser::prepareToParse(uint64_t Offset) { 1251 DWARFUnit *U = nullptr; 1252 auto It = LineToUnit.find(Offset); 1253 if (It != LineToUnit.end()) 1254 U = It->second; 1255 DebugLineData.setAddressSize(U ? U->getAddressByteSize() : 0); 1256 return U; 1257 } 1258 1259 void DWARFDebugLine::SectionParser::moveToNextTable(uint64_t OldOffset, 1260 const Prologue &P) { 1261 // If the length field is not valid, we don't know where the next table is, so 1262 // cannot continue to parse. Mark the parser as done, and leave the Offset 1263 // value as it currently is. This will be the end of the bad length field. 1264 if (!P.totalLengthIsValid()) { 1265 Done = true; 1266 return; 1267 } 1268 1269 Offset = OldOffset + P.TotalLength + P.sizeofTotalLength(); 1270 if (!DebugLineData.isValidOffset(Offset)) { 1271 Done = true; 1272 } 1273 } 1274