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 TotalLength = DebugLineData.getRelocatedValue(4, OffsetPtr); 344 if (TotalLength == dwarf::DW_LENGTH_DWARF64) { 345 FormParams.Format = dwarf::DWARF64; 346 TotalLength = DebugLineData.getU64(OffsetPtr); 347 } else if (TotalLength >= dwarf::DW_LENGTH_lo_reserved) { 348 // Treat this error as unrecoverable - we have no way of knowing where the 349 // table ends. 350 return createStringError(errc::invalid_argument, 351 "parsing line table prologue at offset 0x%8.8" PRIx64 352 " unsupported reserved unit length found of value 0x%8.8" PRIx64, 353 PrologueOffset, TotalLength); 354 } 355 FormParams.Version = DebugLineData.getU16(OffsetPtr); 356 if (!versionIsSupported(getVersion())) 357 // Treat this error as unrecoverable - we cannot be sure what any of 358 // the data represents including the length field, so cannot skip it or make 359 // any reasonable assumptions. 360 return createStringError( 361 errc::not_supported, 362 "parsing line table prologue at offset 0x%8.8" PRIx64 363 " found unsupported version %" PRIu16, 364 PrologueOffset, getVersion()); 365 366 if (getVersion() >= 5) { 367 FormParams.AddrSize = DebugLineData.getU8(OffsetPtr); 368 assert((DebugLineData.getAddressSize() == 0 || 369 DebugLineData.getAddressSize() == getAddressSize()) && 370 "Line table header and data extractor disagree"); 371 SegSelectorSize = DebugLineData.getU8(OffsetPtr); 372 } 373 374 PrologueLength = 375 DebugLineData.getRelocatedValue(sizeofPrologueLength(), OffsetPtr); 376 const uint64_t EndPrologueOffset = PrologueLength + *OffsetPtr; 377 MinInstLength = DebugLineData.getU8(OffsetPtr); 378 if (getVersion() >= 4) 379 MaxOpsPerInst = DebugLineData.getU8(OffsetPtr); 380 DefaultIsStmt = DebugLineData.getU8(OffsetPtr); 381 LineBase = DebugLineData.getU8(OffsetPtr); 382 LineRange = DebugLineData.getU8(OffsetPtr); 383 OpcodeBase = DebugLineData.getU8(OffsetPtr); 384 385 if (OpcodeBase == 0) { 386 // If the opcode base is 0, we cannot read the standard opcode lengths (of 387 // which there are supposed to be one fewer than the opcode base). Assume 388 // there are no standard opcodes and continue parsing. 389 RecoverableErrorHandler(createStringError( 390 errc::invalid_argument, 391 "parsing line table prologue at offset 0x%8.8" PRIx64 392 " found opcode base of 0. Assuming no standard opcodes", 393 PrologueOffset)); 394 } else { 395 StandardOpcodeLengths.reserve(OpcodeBase - 1); 396 for (uint32_t I = 1; I < OpcodeBase; ++I) { 397 uint8_t OpLen = DebugLineData.getU8(OffsetPtr); 398 StandardOpcodeLengths.push_back(OpLen); 399 } 400 } 401 402 auto ReportInvalidDirFileTable = [&](Error E) { 403 RecoverableErrorHandler(joinErrors( 404 createStringError( 405 errc::invalid_argument, 406 "parsing line table prologue at 0x%8.8" PRIx64 407 " found an invalid directory or file table description at" 408 " 0x%8.8" PRIx64, 409 PrologueOffset, *OffsetPtr), 410 std::move(E))); 411 // Skip to the end of the prologue, since the chances are that the parser 412 // did not read the whole table. This prevents the length check below from 413 // executing. 414 if (*OffsetPtr < EndPrologueOffset) 415 *OffsetPtr = EndPrologueOffset; 416 }; 417 if (getVersion() >= 5) { 418 if (Error E = 419 parseV5DirFileTables(DebugLineData, OffsetPtr, FormParams, Ctx, U, 420 ContentTypes, IncludeDirectories, FileNames)) 421 ReportInvalidDirFileTable(std::move(E)); 422 } else if (Error E = parseV2DirFileTables(DebugLineData, OffsetPtr, 423 EndPrologueOffset, ContentTypes, 424 IncludeDirectories, FileNames)) 425 ReportInvalidDirFileTable(std::move(E)); 426 427 if (*OffsetPtr != EndPrologueOffset) { 428 RecoverableErrorHandler(createStringError( 429 errc::invalid_argument, 430 "parsing line table prologue at 0x%8.8" PRIx64 431 " should have ended at 0x%8.8" PRIx64 " but it ended at 0x%8.8" PRIx64, 432 PrologueOffset, EndPrologueOffset, *OffsetPtr)); 433 *OffsetPtr = EndPrologueOffset; 434 } 435 return Error::success(); 436 } 437 438 DWARFDebugLine::Row::Row(bool DefaultIsStmt) { reset(DefaultIsStmt); } 439 440 void DWARFDebugLine::Row::postAppend() { 441 Discriminator = 0; 442 BasicBlock = false; 443 PrologueEnd = false; 444 EpilogueBegin = false; 445 } 446 447 void DWARFDebugLine::Row::reset(bool DefaultIsStmt) { 448 Address.Address = 0; 449 Address.SectionIndex = object::SectionedAddress::UndefSection; 450 Line = 1; 451 Column = 0; 452 File = 1; 453 Isa = 0; 454 Discriminator = 0; 455 IsStmt = DefaultIsStmt; 456 BasicBlock = false; 457 EndSequence = false; 458 PrologueEnd = false; 459 EpilogueBegin = false; 460 } 461 462 void DWARFDebugLine::Row::dumpTableHeader(raw_ostream &OS) { 463 OS << "Address Line Column File ISA Discriminator Flags\n" 464 << "------------------ ------ ------ ------ --- ------------- " 465 "-------------\n"; 466 } 467 468 void DWARFDebugLine::Row::dump(raw_ostream &OS) const { 469 OS << format("0x%16.16" PRIx64 " %6u %6u", Address.Address, Line, Column) 470 << format(" %6u %3u %13u ", File, Isa, Discriminator) 471 << (IsStmt ? " is_stmt" : "") << (BasicBlock ? " basic_block" : "") 472 << (PrologueEnd ? " prologue_end" : "") 473 << (EpilogueBegin ? " epilogue_begin" : "") 474 << (EndSequence ? " end_sequence" : "") << '\n'; 475 } 476 477 DWARFDebugLine::Sequence::Sequence() { reset(); } 478 479 void DWARFDebugLine::Sequence::reset() { 480 LowPC = 0; 481 HighPC = 0; 482 SectionIndex = object::SectionedAddress::UndefSection; 483 FirstRowIndex = 0; 484 LastRowIndex = 0; 485 Empty = true; 486 } 487 488 DWARFDebugLine::LineTable::LineTable() { clear(); } 489 490 void DWARFDebugLine::LineTable::dump(raw_ostream &OS, 491 DIDumpOptions DumpOptions) const { 492 Prologue.dump(OS, DumpOptions); 493 494 if (!Rows.empty()) { 495 OS << '\n'; 496 Row::dumpTableHeader(OS); 497 for (const Row &R : Rows) { 498 R.dump(OS); 499 } 500 } 501 502 // Terminate the table with a final blank line to clearly delineate it from 503 // later dumps. 504 OS << '\n'; 505 } 506 507 void DWARFDebugLine::LineTable::clear() { 508 Prologue.clear(); 509 Rows.clear(); 510 Sequences.clear(); 511 } 512 513 DWARFDebugLine::ParsingState::ParsingState(struct LineTable *LT) 514 : LineTable(LT) { 515 resetRowAndSequence(); 516 } 517 518 void DWARFDebugLine::ParsingState::resetRowAndSequence() { 519 Row.reset(LineTable->Prologue.DefaultIsStmt); 520 Sequence.reset(); 521 } 522 523 void DWARFDebugLine::ParsingState::appendRowToMatrix() { 524 unsigned RowNumber = LineTable->Rows.size(); 525 if (Sequence.Empty) { 526 // Record the beginning of instruction sequence. 527 Sequence.Empty = false; 528 Sequence.LowPC = Row.Address.Address; 529 Sequence.FirstRowIndex = RowNumber; 530 } 531 LineTable->appendRow(Row); 532 if (Row.EndSequence) { 533 // Record the end of instruction sequence. 534 Sequence.HighPC = Row.Address.Address; 535 Sequence.LastRowIndex = RowNumber + 1; 536 Sequence.SectionIndex = Row.Address.SectionIndex; 537 if (Sequence.isValid()) 538 LineTable->appendSequence(Sequence); 539 Sequence.reset(); 540 } 541 Row.postAppend(); 542 } 543 544 const DWARFDebugLine::LineTable * 545 DWARFDebugLine::getLineTable(uint64_t Offset) const { 546 LineTableConstIter Pos = LineTableMap.find(Offset); 547 if (Pos != LineTableMap.end()) 548 return &Pos->second; 549 return nullptr; 550 } 551 552 Expected<const DWARFDebugLine::LineTable *> DWARFDebugLine::getOrParseLineTable( 553 DWARFDataExtractor &DebugLineData, uint64_t Offset, const DWARFContext &Ctx, 554 const DWARFUnit *U, function_ref<void(Error)> RecoverableErrorHandler) { 555 if (!DebugLineData.isValidOffset(Offset)) 556 return createStringError(errc::invalid_argument, "offset 0x%8.8" PRIx64 557 " is not a valid debug line section offset", 558 Offset); 559 560 std::pair<LineTableIter, bool> Pos = 561 LineTableMap.insert(LineTableMapTy::value_type(Offset, LineTable())); 562 LineTable *LT = &Pos.first->second; 563 if (Pos.second) { 564 if (Error Err = 565 LT->parse(DebugLineData, &Offset, Ctx, U, RecoverableErrorHandler)) 566 return std::move(Err); 567 return LT; 568 } 569 return LT; 570 } 571 572 Error DWARFDebugLine::LineTable::parse( 573 DWARFDataExtractor &DebugLineData, uint64_t *OffsetPtr, 574 const DWARFContext &Ctx, const DWARFUnit *U, 575 function_ref<void(Error)> RecoverableErrorHandler, raw_ostream *OS) { 576 const uint64_t DebugLineOffset = *OffsetPtr; 577 578 clear(); 579 580 Error PrologueErr = 581 Prologue.parse(DebugLineData, OffsetPtr, RecoverableErrorHandler, Ctx, U); 582 583 if (OS) { 584 // The presence of OS signals verbose dumping. 585 DIDumpOptions DumpOptions; 586 DumpOptions.Verbose = true; 587 Prologue.dump(*OS, DumpOptions); 588 } 589 590 if (PrologueErr) 591 return PrologueErr; 592 593 uint64_t ProgramLength = Prologue.TotalLength + Prologue.sizeofTotalLength(); 594 if (!DebugLineData.isValidOffsetForDataOfSize(DebugLineOffset, 595 ProgramLength)) { 596 assert(DebugLineData.size() > DebugLineOffset && 597 "prologue parsing should handle invalid offset"); 598 uint64_t BytesRemaining = DebugLineData.size() - DebugLineOffset; 599 RecoverableErrorHandler( 600 createStringError(errc::invalid_argument, 601 "line table program with offset 0x%8.8" PRIx64 602 " has length 0x%8.8" PRIx64 " but only 0x%8.8" PRIx64 603 " bytes are available", 604 DebugLineOffset, ProgramLength, BytesRemaining)); 605 // Continue by capping the length at the number of remaining bytes. 606 ProgramLength = BytesRemaining; 607 } 608 609 const uint64_t EndOffset = DebugLineOffset + ProgramLength; 610 611 // See if we should tell the data extractor the address size. 612 if (DebugLineData.getAddressSize() == 0) 613 DebugLineData.setAddressSize(Prologue.getAddressSize()); 614 else 615 assert(Prologue.getAddressSize() == 0 || 616 Prologue.getAddressSize() == DebugLineData.getAddressSize()); 617 618 ParsingState State(this); 619 620 while (*OffsetPtr < EndOffset) { 621 if (OS) 622 *OS << format("0x%08.08" PRIx64 ": ", *OffsetPtr); 623 624 uint8_t Opcode = DebugLineData.getU8(OffsetPtr); 625 626 if (OS) 627 *OS << format("%02.02" PRIx8 " ", Opcode); 628 629 if (Opcode == 0) { 630 // Extended Opcodes always start with a zero opcode followed by 631 // a uleb128 length so you can skip ones you don't know about 632 uint64_t Len = DebugLineData.getULEB128(OffsetPtr); 633 uint64_t ExtOffset = *OffsetPtr; 634 635 // Tolerate zero-length; assume length is correct and soldier on. 636 if (Len == 0) { 637 if (OS) 638 *OS << "Badly formed extended line op (length 0)\n"; 639 continue; 640 } 641 642 uint8_t SubOpcode = DebugLineData.getU8(OffsetPtr); 643 if (OS) 644 *OS << LNExtendedString(SubOpcode); 645 switch (SubOpcode) { 646 case DW_LNE_end_sequence: 647 // Set the end_sequence register of the state machine to true and 648 // append a row to the matrix using the current values of the 649 // state-machine registers. Then reset the registers to the initial 650 // values specified above. Every statement program sequence must end 651 // with a DW_LNE_end_sequence instruction which creates a row whose 652 // address is that of the byte after the last target machine instruction 653 // of the sequence. 654 State.Row.EndSequence = true; 655 if (OS) { 656 *OS << "\n"; 657 OS->indent(12); 658 State.Row.dump(*OS); 659 } 660 State.appendRowToMatrix(); 661 State.resetRowAndSequence(); 662 break; 663 664 case DW_LNE_set_address: 665 // Takes a single relocatable address as an operand. The size of the 666 // operand is the size appropriate to hold an address on the target 667 // machine. Set the address register to the value given by the 668 // relocatable address. All of the other statement program opcodes 669 // that affect the address register add a delta to it. This instruction 670 // stores a relocatable value into it instead. 671 // 672 // Make sure the extractor knows the address size. If not, infer it 673 // from the size of the operand. 674 { 675 uint8_t ExtractorAddressSize = DebugLineData.getAddressSize(); 676 uint64_t OpcodeAddressSize = Len - 1; 677 if (ExtractorAddressSize != OpcodeAddressSize && 678 ExtractorAddressSize != 0) 679 RecoverableErrorHandler(createStringError( 680 errc::invalid_argument, 681 "mismatching address size at offset 0x%8.8" PRIx64 682 " expected 0x%2.2" PRIx8 " found 0x%2.2" PRIx64, 683 ExtOffset, ExtractorAddressSize, Len - 1)); 684 685 // Assume that the line table is correct and temporarily override the 686 // address size. If the size is unsupported, give up trying to read 687 // the address and continue to the next opcode. 688 if (OpcodeAddressSize != 1 && OpcodeAddressSize != 2 && 689 OpcodeAddressSize != 4 && OpcodeAddressSize != 8) { 690 RecoverableErrorHandler(createStringError( 691 errc::invalid_argument, 692 "address size 0x%2.2" PRIx64 693 " of DW_LNE_set_address opcode at offset 0x%8.8" PRIx64 694 " is unsupported", 695 OpcodeAddressSize, ExtOffset)); 696 *OffsetPtr += OpcodeAddressSize; 697 } else { 698 DebugLineData.setAddressSize(OpcodeAddressSize); 699 State.Row.Address.Address = DebugLineData.getRelocatedAddress( 700 OffsetPtr, &State.Row.Address.SectionIndex); 701 702 // Restore the address size if the extractor already had it. 703 if (ExtractorAddressSize != 0) 704 DebugLineData.setAddressSize(ExtractorAddressSize); 705 } 706 707 if (OS) 708 *OS << format(" (0x%16.16" PRIx64 ")", State.Row.Address.Address); 709 } 710 break; 711 712 case DW_LNE_define_file: 713 // Takes 4 arguments. The first is a null terminated string containing 714 // a source file name. The second is an unsigned LEB128 number 715 // representing the directory index of the directory in which the file 716 // was found. The third is an unsigned LEB128 number representing the 717 // time of last modification of the file. The fourth is an unsigned 718 // LEB128 number representing the length in bytes of the file. The time 719 // and length fields may contain LEB128(0) if the information is not 720 // available. 721 // 722 // The directory index represents an entry in the include_directories 723 // section of the statement program prologue. The index is LEB128(0) 724 // if the file was found in the current directory of the compilation, 725 // LEB128(1) if it was found in the first directory in the 726 // include_directories section, and so on. The directory index is 727 // ignored for file names that represent full path names. 728 // 729 // The files are numbered, starting at 1, in the order in which they 730 // appear; the names in the prologue come before names defined by 731 // the DW_LNE_define_file instruction. These numbers are used in the 732 // the file register of the state machine. 733 { 734 FileNameEntry FileEntry; 735 const char *Name = DebugLineData.getCStr(OffsetPtr); 736 FileEntry.Name = 737 DWARFFormValue::createFromPValue(dwarf::DW_FORM_string, Name); 738 FileEntry.DirIdx = DebugLineData.getULEB128(OffsetPtr); 739 FileEntry.ModTime = DebugLineData.getULEB128(OffsetPtr); 740 FileEntry.Length = DebugLineData.getULEB128(OffsetPtr); 741 Prologue.FileNames.push_back(FileEntry); 742 if (OS) 743 *OS << " (" << Name << ", dir=" << FileEntry.DirIdx << ", mod_time=" 744 << format("(0x%16.16" PRIx64 ")", FileEntry.ModTime) 745 << ", length=" << FileEntry.Length << ")"; 746 } 747 break; 748 749 case DW_LNE_set_discriminator: 750 State.Row.Discriminator = DebugLineData.getULEB128(OffsetPtr); 751 if (OS) 752 *OS << " (" << State.Row.Discriminator << ")"; 753 break; 754 755 default: 756 if (OS) 757 *OS << format("Unrecognized extended op 0x%02.02" PRIx8, SubOpcode) 758 << format(" length %" PRIx64, Len); 759 // Len doesn't include the zero opcode byte or the length itself, but 760 // it does include the sub_opcode, so we have to adjust for that. 761 (*OffsetPtr) += Len - 1; 762 break; 763 } 764 // Make sure the length as recorded in the table and the standard length 765 // for the opcode match. If they don't, continue from the end as claimed 766 // by the table. 767 uint64_t End = ExtOffset + Len; 768 if (*OffsetPtr != End) { 769 RecoverableErrorHandler(createStringError( 770 errc::illegal_byte_sequence, 771 "unexpected line op length at offset 0x%8.8" PRIx64 772 " expected 0x%2.2" PRIx64 " found 0x%2.2" PRIx64, 773 ExtOffset, Len, *OffsetPtr - ExtOffset)); 774 *OffsetPtr = End; 775 } 776 } else if (Opcode < Prologue.OpcodeBase) { 777 if (OS) 778 *OS << LNStandardString(Opcode); 779 switch (Opcode) { 780 // Standard Opcodes 781 case DW_LNS_copy: 782 // Takes no arguments. Append a row to the matrix using the 783 // current values of the state-machine registers. 784 if (OS) { 785 *OS << "\n"; 786 OS->indent(12); 787 State.Row.dump(*OS); 788 *OS << "\n"; 789 } 790 State.appendRowToMatrix(); 791 break; 792 793 case DW_LNS_advance_pc: 794 // Takes a single unsigned LEB128 operand, multiplies it by the 795 // min_inst_length field of the prologue, and adds the 796 // result to the address register of the state machine. 797 { 798 uint64_t AddrOffset = 799 DebugLineData.getULEB128(OffsetPtr) * Prologue.MinInstLength; 800 State.Row.Address.Address += AddrOffset; 801 if (OS) 802 *OS << " (" << AddrOffset << ")"; 803 } 804 break; 805 806 case DW_LNS_advance_line: 807 // Takes a single signed LEB128 operand and adds that value to 808 // the line register of the state machine. 809 State.Row.Line += DebugLineData.getSLEB128(OffsetPtr); 810 if (OS) 811 *OS << " (" << State.Row.Line << ")"; 812 break; 813 814 case DW_LNS_set_file: 815 // Takes a single unsigned LEB128 operand and stores it in the file 816 // register of the state machine. 817 State.Row.File = DebugLineData.getULEB128(OffsetPtr); 818 if (OS) 819 *OS << " (" << State.Row.File << ")"; 820 break; 821 822 case DW_LNS_set_column: 823 // Takes a single unsigned LEB128 operand and stores it in the 824 // column register of the state machine. 825 State.Row.Column = DebugLineData.getULEB128(OffsetPtr); 826 if (OS) 827 *OS << " (" << State.Row.Column << ")"; 828 break; 829 830 case DW_LNS_negate_stmt: 831 // Takes no arguments. Set the is_stmt register of the state 832 // machine to the logical negation of its current value. 833 State.Row.IsStmt = !State.Row.IsStmt; 834 break; 835 836 case DW_LNS_set_basic_block: 837 // Takes no arguments. Set the basic_block register of the 838 // state machine to true 839 State.Row.BasicBlock = true; 840 break; 841 842 case DW_LNS_const_add_pc: 843 // Takes no arguments. Add to the address register of the state 844 // machine the address increment value corresponding to special 845 // opcode 255. The motivation for DW_LNS_const_add_pc is this: 846 // when the statement program needs to advance the address by a 847 // small amount, it can use a single special opcode, which occupies 848 // a single byte. When it needs to advance the address by up to 849 // twice the range of the last special opcode, it can use 850 // DW_LNS_const_add_pc followed by a special opcode, for a total 851 // of two bytes. Only if it needs to advance the address by more 852 // than twice that range will it need to use both DW_LNS_advance_pc 853 // and a special opcode, requiring three or more bytes. 854 { 855 uint8_t AdjustOpcode = 255 - Prologue.OpcodeBase; 856 uint64_t AddrOffset = 857 (AdjustOpcode / Prologue.LineRange) * Prologue.MinInstLength; 858 State.Row.Address.Address += AddrOffset; 859 if (OS) 860 *OS 861 << format(" (0x%16.16" PRIx64 ")", AddrOffset); 862 } 863 break; 864 865 case DW_LNS_fixed_advance_pc: 866 // Takes a single uhalf operand. Add to the address register of 867 // the state machine the value of the (unencoded) operand. This 868 // is the only extended opcode that takes an argument that is not 869 // a variable length number. The motivation for DW_LNS_fixed_advance_pc 870 // is this: existing assemblers cannot emit DW_LNS_advance_pc or 871 // special opcodes because they cannot encode LEB128 numbers or 872 // judge when the computation of a special opcode overflows and 873 // requires the use of DW_LNS_advance_pc. Such assemblers, however, 874 // can use DW_LNS_fixed_advance_pc instead, sacrificing compression. 875 { 876 uint16_t PCOffset = DebugLineData.getRelocatedValue(2, OffsetPtr); 877 State.Row.Address.Address += PCOffset; 878 if (OS) 879 *OS 880 << format(" (0x%4.4" PRIx16 ")", PCOffset); 881 } 882 break; 883 884 case DW_LNS_set_prologue_end: 885 // Takes no arguments. Set the prologue_end register of the 886 // state machine to true 887 State.Row.PrologueEnd = true; 888 break; 889 890 case DW_LNS_set_epilogue_begin: 891 // Takes no arguments. Set the basic_block register of the 892 // state machine to true 893 State.Row.EpilogueBegin = true; 894 break; 895 896 case DW_LNS_set_isa: 897 // Takes a single unsigned LEB128 operand and stores it in the 898 // column register of the state machine. 899 State.Row.Isa = DebugLineData.getULEB128(OffsetPtr); 900 if (OS) 901 *OS << " (" << (uint64_t)State.Row.Isa << ")"; 902 break; 903 904 default: 905 // Handle any unknown standard opcodes here. We know the lengths 906 // of such opcodes because they are specified in the prologue 907 // as a multiple of LEB128 operands for each opcode. 908 { 909 assert(Opcode - 1U < Prologue.StandardOpcodeLengths.size()); 910 uint8_t OpcodeLength = Prologue.StandardOpcodeLengths[Opcode - 1]; 911 for (uint8_t I = 0; I < OpcodeLength; ++I) { 912 uint64_t Value = DebugLineData.getULEB128(OffsetPtr); 913 if (OS) 914 *OS << format("Skipping ULEB128 value: 0x%16.16" PRIx64 ")\n", 915 Value); 916 } 917 } 918 break; 919 } 920 } else { 921 // Special Opcodes 922 923 // A special opcode value is chosen based on the amount that needs 924 // to be added to the line and address registers. The maximum line 925 // increment for a special opcode is the value of the line_base 926 // field in the header, plus the value of the line_range field, 927 // minus 1 (line base + line range - 1). If the desired line 928 // increment is greater than the maximum line increment, a standard 929 // opcode must be used instead of a special opcode. The "address 930 // advance" is calculated by dividing the desired address increment 931 // by the minimum_instruction_length field from the header. The 932 // special opcode is then calculated using the following formula: 933 // 934 // opcode = (desired line increment - line_base) + 935 // (line_range * address advance) + opcode_base 936 // 937 // If the resulting opcode is greater than 255, a standard opcode 938 // must be used instead. 939 // 940 // To decode a special opcode, subtract the opcode_base from the 941 // opcode itself to give the adjusted opcode. The amount to 942 // increment the address register is the result of the adjusted 943 // opcode divided by the line_range multiplied by the 944 // minimum_instruction_length field from the header. That is: 945 // 946 // address increment = (adjusted opcode / line_range) * 947 // minimum_instruction_length 948 // 949 // The amount to increment the line register is the line_base plus 950 // the result of the adjusted opcode modulo the line_range. That is: 951 // 952 // line increment = line_base + (adjusted opcode % line_range) 953 954 uint8_t AdjustOpcode = Opcode - Prologue.OpcodeBase; 955 uint64_t AddrOffset = 956 (AdjustOpcode / Prologue.LineRange) * Prologue.MinInstLength; 957 int32_t LineOffset = 958 Prologue.LineBase + (AdjustOpcode % Prologue.LineRange); 959 State.Row.Line += LineOffset; 960 State.Row.Address.Address += AddrOffset; 961 962 if (OS) { 963 *OS << "address += " << AddrOffset << ", line += " << LineOffset 964 << "\n"; 965 OS->indent(12); 966 State.Row.dump(*OS); 967 } 968 969 State.appendRowToMatrix(); 970 } 971 if(OS) 972 *OS << "\n"; 973 } 974 975 if (!State.Sequence.Empty) 976 RecoverableErrorHandler(createStringError( 977 errc::illegal_byte_sequence, 978 "last sequence in debug line table at offset 0x%8.8" PRIx64 979 " is not terminated", 980 DebugLineOffset)); 981 982 // Sort all sequences so that address lookup will work faster. 983 if (!Sequences.empty()) { 984 llvm::sort(Sequences, Sequence::orderByHighPC); 985 // Note: actually, instruction address ranges of sequences should not 986 // overlap (in shared objects and executables). If they do, the address 987 // lookup would still work, though, but result would be ambiguous. 988 // We don't report warning in this case. For example, 989 // sometimes .so compiled from multiple object files contains a few 990 // rudimentary sequences for address ranges [0x0, 0xsomething). 991 } 992 993 return Error::success(); 994 } 995 996 uint32_t DWARFDebugLine::LineTable::findRowInSeq( 997 const DWARFDebugLine::Sequence &Seq, 998 object::SectionedAddress Address) const { 999 if (!Seq.containsPC(Address)) 1000 return UnknownRowIndex; 1001 assert(Seq.SectionIndex == Address.SectionIndex); 1002 // In some cases, e.g. first instruction in a function, the compiler generates 1003 // two entries, both with the same address. We want the last one. 1004 // 1005 // In general we want a non-empty range: the last row whose address is less 1006 // than or equal to Address. This can be computed as upper_bound - 1. 1007 DWARFDebugLine::Row Row; 1008 Row.Address = Address; 1009 RowIter FirstRow = Rows.begin() + Seq.FirstRowIndex; 1010 RowIter LastRow = Rows.begin() + Seq.LastRowIndex; 1011 assert(FirstRow->Address.Address <= Row.Address.Address && 1012 Row.Address.Address < LastRow[-1].Address.Address); 1013 RowIter RowPos = std::upper_bound(FirstRow + 1, LastRow - 1, Row, 1014 DWARFDebugLine::Row::orderByAddress) - 1015 1; 1016 assert(Seq.SectionIndex == RowPos->Address.SectionIndex); 1017 return RowPos - Rows.begin(); 1018 } 1019 1020 uint32_t DWARFDebugLine::LineTable::lookupAddress( 1021 object::SectionedAddress Address) const { 1022 1023 // Search for relocatable addresses 1024 uint32_t Result = lookupAddressImpl(Address); 1025 1026 if (Result != UnknownRowIndex || 1027 Address.SectionIndex == object::SectionedAddress::UndefSection) 1028 return Result; 1029 1030 // Search for absolute addresses 1031 Address.SectionIndex = object::SectionedAddress::UndefSection; 1032 return lookupAddressImpl(Address); 1033 } 1034 1035 uint32_t DWARFDebugLine::LineTable::lookupAddressImpl( 1036 object::SectionedAddress Address) const { 1037 // First, find an instruction sequence containing the given address. 1038 DWARFDebugLine::Sequence Sequence; 1039 Sequence.SectionIndex = Address.SectionIndex; 1040 Sequence.HighPC = Address.Address; 1041 SequenceIter It = llvm::upper_bound(Sequences, Sequence, 1042 DWARFDebugLine::Sequence::orderByHighPC); 1043 if (It == Sequences.end() || It->SectionIndex != Address.SectionIndex) 1044 return UnknownRowIndex; 1045 return findRowInSeq(*It, Address); 1046 } 1047 1048 bool DWARFDebugLine::LineTable::lookupAddressRange( 1049 object::SectionedAddress Address, uint64_t Size, 1050 std::vector<uint32_t> &Result) const { 1051 1052 // Search for relocatable addresses 1053 if (lookupAddressRangeImpl(Address, Size, Result)) 1054 return true; 1055 1056 if (Address.SectionIndex == object::SectionedAddress::UndefSection) 1057 return false; 1058 1059 // Search for absolute addresses 1060 Address.SectionIndex = object::SectionedAddress::UndefSection; 1061 return lookupAddressRangeImpl(Address, Size, Result); 1062 } 1063 1064 bool DWARFDebugLine::LineTable::lookupAddressRangeImpl( 1065 object::SectionedAddress Address, uint64_t Size, 1066 std::vector<uint32_t> &Result) const { 1067 if (Sequences.empty()) 1068 return false; 1069 uint64_t EndAddr = Address.Address + Size; 1070 // First, find an instruction sequence containing the given address. 1071 DWARFDebugLine::Sequence Sequence; 1072 Sequence.SectionIndex = Address.SectionIndex; 1073 Sequence.HighPC = Address.Address; 1074 SequenceIter LastSeq = Sequences.end(); 1075 SequenceIter SeqPos = llvm::upper_bound( 1076 Sequences, Sequence, DWARFDebugLine::Sequence::orderByHighPC); 1077 if (SeqPos == LastSeq || !SeqPos->containsPC(Address)) 1078 return false; 1079 1080 SequenceIter StartPos = SeqPos; 1081 1082 // Add the rows from the first sequence to the vector, starting with the 1083 // index we just calculated 1084 1085 while (SeqPos != LastSeq && SeqPos->LowPC < EndAddr) { 1086 const DWARFDebugLine::Sequence &CurSeq = *SeqPos; 1087 // For the first sequence, we need to find which row in the sequence is the 1088 // first in our range. 1089 uint32_t FirstRowIndex = CurSeq.FirstRowIndex; 1090 if (SeqPos == StartPos) 1091 FirstRowIndex = findRowInSeq(CurSeq, Address); 1092 1093 // Figure out the last row in the range. 1094 uint32_t LastRowIndex = 1095 findRowInSeq(CurSeq, {EndAddr - 1, Address.SectionIndex}); 1096 if (LastRowIndex == UnknownRowIndex) 1097 LastRowIndex = CurSeq.LastRowIndex - 1; 1098 1099 assert(FirstRowIndex != UnknownRowIndex); 1100 assert(LastRowIndex != UnknownRowIndex); 1101 1102 for (uint32_t I = FirstRowIndex; I <= LastRowIndex; ++I) { 1103 Result.push_back(I); 1104 } 1105 1106 ++SeqPos; 1107 } 1108 1109 return true; 1110 } 1111 1112 Optional<StringRef> DWARFDebugLine::LineTable::getSourceByIndex(uint64_t FileIndex, 1113 FileLineInfoKind Kind) const { 1114 if (Kind == FileLineInfoKind::None || !Prologue.hasFileAtIndex(FileIndex)) 1115 return None; 1116 const FileNameEntry &Entry = Prologue.getFileNameEntry(FileIndex); 1117 if (Optional<const char *> source = Entry.Source.getAsCString()) 1118 return StringRef(*source); 1119 return None; 1120 } 1121 1122 static bool isPathAbsoluteOnWindowsOrPosix(const Twine &Path) { 1123 // Debug info can contain paths from any OS, not necessarily 1124 // an OS we're currently running on. Moreover different compilation units can 1125 // be compiled on different operating systems and linked together later. 1126 return sys::path::is_absolute(Path, sys::path::Style::posix) || 1127 sys::path::is_absolute(Path, sys::path::Style::windows); 1128 } 1129 1130 bool DWARFDebugLine::Prologue::getFileNameByIndex( 1131 uint64_t FileIndex, StringRef CompDir, FileLineInfoKind Kind, 1132 std::string &Result, sys::path::Style Style) const { 1133 if (Kind == FileLineInfoKind::None || !hasFileAtIndex(FileIndex)) 1134 return false; 1135 const FileNameEntry &Entry = getFileNameEntry(FileIndex); 1136 Optional<const char *> Name = Entry.Name.getAsCString(); 1137 if (!Name) 1138 return false; 1139 StringRef FileName = *Name; 1140 if (Kind == FileLineInfoKind::Default || 1141 isPathAbsoluteOnWindowsOrPosix(FileName)) { 1142 Result = std::string(FileName); 1143 return true; 1144 } 1145 1146 SmallString<16> FilePath; 1147 StringRef IncludeDir; 1148 // Be defensive about the contents of Entry. 1149 if (getVersion() >= 5) { 1150 if (Entry.DirIdx < IncludeDirectories.size()) 1151 IncludeDir = IncludeDirectories[Entry.DirIdx].getAsCString().getValue(); 1152 } else { 1153 if (0 < Entry.DirIdx && Entry.DirIdx <= IncludeDirectories.size()) 1154 IncludeDir = 1155 IncludeDirectories[Entry.DirIdx - 1].getAsCString().getValue(); 1156 } 1157 // For absolute paths only, include the compilation directory of compile unit. 1158 // We know that FileName is not absolute, the only way to have an absolute 1159 // path at this point would be if IncludeDir is absolute. 1160 if (Kind == FileLineInfoKind::AbsoluteFilePath && !CompDir.empty() && 1161 !isPathAbsoluteOnWindowsOrPosix(IncludeDir)) 1162 sys::path::append(FilePath, Style, CompDir); 1163 1164 assert((Kind == FileLineInfoKind::AbsoluteFilePath || 1165 Kind == FileLineInfoKind::RelativeFilePath) && 1166 "invalid FileLineInfo Kind"); 1167 1168 // sys::path::append skips empty strings. 1169 sys::path::append(FilePath, Style, IncludeDir, FileName); 1170 Result = std::string(FilePath.str()); 1171 return true; 1172 } 1173 1174 bool DWARFDebugLine::LineTable::getFileLineInfoForAddress( 1175 object::SectionedAddress Address, const char *CompDir, 1176 FileLineInfoKind Kind, DILineInfo &Result) const { 1177 // Get the index of row we're looking for in the line table. 1178 uint32_t RowIndex = lookupAddress(Address); 1179 if (RowIndex == -1U) 1180 return false; 1181 // Take file number and line/column from the row. 1182 const auto &Row = Rows[RowIndex]; 1183 if (!getFileNameByIndex(Row.File, CompDir, Kind, Result.FileName)) 1184 return false; 1185 Result.Line = Row.Line; 1186 Result.Column = Row.Column; 1187 Result.Discriminator = Row.Discriminator; 1188 Result.Source = getSourceByIndex(Row.File, Kind); 1189 return true; 1190 } 1191 1192 // We want to supply the Unit associated with a .debug_line[.dwo] table when 1193 // we dump it, if possible, but still dump the table even if there isn't a Unit. 1194 // Therefore, collect up handles on all the Units that point into the 1195 // line-table section. 1196 static DWARFDebugLine::SectionParser::LineToUnitMap 1197 buildLineToUnitMap(DWARFDebugLine::SectionParser::cu_range CUs, 1198 DWARFDebugLine::SectionParser::tu_range TUs) { 1199 DWARFDebugLine::SectionParser::LineToUnitMap LineToUnit; 1200 for (const auto &CU : CUs) 1201 if (auto CUDIE = CU->getUnitDIE()) 1202 if (auto StmtOffset = toSectionOffset(CUDIE.find(DW_AT_stmt_list))) 1203 LineToUnit.insert(std::make_pair(*StmtOffset, &*CU)); 1204 for (const auto &TU : TUs) 1205 if (auto TUDIE = TU->getUnitDIE()) 1206 if (auto StmtOffset = toSectionOffset(TUDIE.find(DW_AT_stmt_list))) 1207 LineToUnit.insert(std::make_pair(*StmtOffset, &*TU)); 1208 return LineToUnit; 1209 } 1210 1211 DWARFDebugLine::SectionParser::SectionParser(DWARFDataExtractor &Data, 1212 const DWARFContext &C, 1213 cu_range CUs, tu_range TUs) 1214 : DebugLineData(Data), Context(C) { 1215 LineToUnit = buildLineToUnitMap(CUs, TUs); 1216 if (!DebugLineData.isValidOffset(Offset)) 1217 Done = true; 1218 } 1219 1220 bool DWARFDebugLine::Prologue::totalLengthIsValid() const { 1221 return TotalLength == dwarf::DW_LENGTH_DWARF64 || 1222 TotalLength < dwarf::DW_LENGTH_lo_reserved; 1223 } 1224 1225 DWARFDebugLine::LineTable DWARFDebugLine::SectionParser::parseNext( 1226 function_ref<void(Error)> RecoverableErrorHandler, 1227 function_ref<void(Error)> UnrecoverableErrorHandler, raw_ostream *OS) { 1228 assert(DebugLineData.isValidOffset(Offset) && 1229 "parsing should have terminated"); 1230 DWARFUnit *U = prepareToParse(Offset); 1231 uint64_t OldOffset = Offset; 1232 LineTable LT; 1233 if (Error Err = LT.parse(DebugLineData, &Offset, Context, U, 1234 RecoverableErrorHandler, OS)) 1235 UnrecoverableErrorHandler(std::move(Err)); 1236 moveToNextTable(OldOffset, LT.Prologue); 1237 return LT; 1238 } 1239 1240 void DWARFDebugLine::SectionParser::skip( 1241 function_ref<void(Error)> RecoverableErrorHandler, 1242 function_ref<void(Error)> UnrecoverableErrorHandler) { 1243 assert(DebugLineData.isValidOffset(Offset) && 1244 "parsing should have terminated"); 1245 DWARFUnit *U = prepareToParse(Offset); 1246 uint64_t OldOffset = Offset; 1247 LineTable LT; 1248 if (Error Err = LT.Prologue.parse(DebugLineData, &Offset, 1249 RecoverableErrorHandler, Context, U)) 1250 UnrecoverableErrorHandler(std::move(Err)); 1251 moveToNextTable(OldOffset, LT.Prologue); 1252 } 1253 1254 DWARFUnit *DWARFDebugLine::SectionParser::prepareToParse(uint64_t Offset) { 1255 DWARFUnit *U = nullptr; 1256 auto It = LineToUnit.find(Offset); 1257 if (It != LineToUnit.end()) 1258 U = It->second; 1259 DebugLineData.setAddressSize(U ? U->getAddressByteSize() : 0); 1260 return U; 1261 } 1262 1263 void DWARFDebugLine::SectionParser::moveToNextTable(uint64_t OldOffset, 1264 const Prologue &P) { 1265 // If the length field is not valid, we don't know where the next table is, so 1266 // cannot continue to parse. Mark the parser as done, and leave the Offset 1267 // value as it currently is. This will be the end of the bad length field. 1268 if (!P.totalLengthIsValid()) { 1269 Done = true; 1270 return; 1271 } 1272 1273 Offset = OldOffset + P.TotalLength + P.sizeofTotalLength(); 1274 if (!DebugLineData.isValidOffset(Offset)) { 1275 Done = true; 1276 } 1277 } 1278