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