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