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