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