1 //===- DWARFDebugLine.cpp -------------------------------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 10 #include "llvm/DebugInfo/DWARF/DWARFDebugLine.h" 11 #include "llvm/ADT/Optional.h" 12 #include "llvm/ADT/SmallString.h" 13 #include "llvm/ADT/SmallVector.h" 14 #include "llvm/ADT/StringRef.h" 15 #include "llvm/BinaryFormat/Dwarf.h" 16 #include "llvm/DebugInfo/DWARF/DWARFFormValue.h" 17 #include "llvm/DebugInfo/DWARF/DWARFRelocMap.h" 18 #include "llvm/Support/Format.h" 19 #include "llvm/Support/Path.h" 20 #include "llvm/Support/raw_ostream.h" 21 #include <algorithm> 22 #include <cassert> 23 #include <cinttypes> 24 #include <cstdint> 25 #include <cstdio> 26 #include <utility> 27 28 using namespace llvm; 29 using namespace dwarf; 30 31 using FileLineInfoKind = DILineInfoSpecifier::FileLineInfoKind; 32 33 namespace { 34 35 struct ContentDescriptor { 36 dwarf::LineNumberEntryFormat Type; 37 dwarf::Form Form; 38 }; 39 40 using ContentDescriptors = SmallVector<ContentDescriptor, 4>; 41 42 } // end anonmyous namespace 43 44 void DWARFDebugLine::ContentTypeTracker::trackContentType( 45 dwarf::LineNumberEntryFormat ContentType) { 46 switch (ContentType) { 47 case dwarf::DW_LNCT_timestamp: 48 HasModTime = true; 49 break; 50 case dwarf::DW_LNCT_size: 51 HasLength = true; 52 break; 53 case dwarf::DW_LNCT_MD5: 54 HasMD5 = true; 55 break; 56 case dwarf::DW_LNCT_LLVM_source: 57 HasSource = true; 58 break; 59 default: 60 // We only care about values we consider optional, and new values may be 61 // added in the vendor extension range, so we do not match exhaustively. 62 break; 63 } 64 } 65 66 DWARFDebugLine::Prologue::Prologue() { clear(); } 67 68 void DWARFDebugLine::Prologue::clear() { 69 TotalLength = PrologueLength = 0; 70 SegSelectorSize = 0; 71 MinInstLength = MaxOpsPerInst = DefaultIsStmt = LineBase = LineRange = 0; 72 OpcodeBase = 0; 73 FormParams = DWARFFormParams({0, 0, DWARF32}); 74 ContentTypes = ContentTypeTracker(); 75 StandardOpcodeLengths.clear(); 76 IncludeDirectories.clear(); 77 FileNames.clear(); 78 } 79 80 void DWARFDebugLine::Prologue::dump(raw_ostream &OS, 81 DIDumpOptions DumpOptions) const { 82 OS << "Line table prologue:\n" 83 << format(" total_length: 0x%8.8" PRIx64 "\n", TotalLength) 84 << format(" version: %u\n", getVersion()); 85 if (getVersion() >= 5) 86 OS << format(" address_size: %u\n", getAddressSize()) 87 << format(" seg_select_size: %u\n", SegSelectorSize); 88 OS << format(" prologue_length: 0x%8.8" PRIx64 "\n", PrologueLength) 89 << format(" min_inst_length: %u\n", MinInstLength) 90 << format(getVersion() >= 4 ? "max_ops_per_inst: %u\n" : "", MaxOpsPerInst) 91 << format(" default_is_stmt: %u\n", DefaultIsStmt) 92 << format(" line_base: %i\n", LineBase) 93 << format(" line_range: %u\n", LineRange) 94 << format(" opcode_base: %u\n", OpcodeBase); 95 96 for (uint32_t I = 0; I != StandardOpcodeLengths.size(); ++I) 97 OS << format("standard_opcode_lengths[%s] = %u\n", 98 LNStandardString(I + 1).data(), StandardOpcodeLengths[I]); 99 100 if (!IncludeDirectories.empty()) { 101 // DWARF v5 starts directory indexes at 0. 102 uint32_t DirBase = getVersion() >= 5 ? 0 : 1; 103 for (uint32_t I = 0; I != IncludeDirectories.size(); ++I) { 104 OS << format("include_directories[%3u] = ", I + DirBase); 105 IncludeDirectories[I].dump(OS, DumpOptions); 106 OS << '\n'; 107 } 108 } 109 110 if (!FileNames.empty()) { 111 // DWARF v5 starts file indexes at 0. 112 uint32_t FileBase = getVersion() >= 5 ? 0 : 1; 113 for (uint32_t I = 0; I != FileNames.size(); ++I) { 114 const FileNameEntry &FileEntry = FileNames[I]; 115 OS << format("file_names[%3u]:\n", I + FileBase); 116 OS << " name: "; 117 FileEntry.Name.dump(OS, DumpOptions); 118 OS << '\n' 119 << format(" dir_index: %" PRIu64 "\n", FileEntry.DirIdx); 120 if (ContentTypes.HasMD5) 121 OS << " md5_checksum: " << FileEntry.Checksum.digest() << '\n'; 122 if (ContentTypes.HasModTime) 123 OS << format(" mod_time: 0x%8.8" PRIx64 "\n", FileEntry.ModTime); 124 if (ContentTypes.HasLength) 125 OS << format(" length: 0x%8.8" PRIx64 "\n", FileEntry.Length); 126 if (ContentTypes.HasSource) { 127 OS << " source: "; 128 FileEntry.Source.dump(OS, DumpOptions); 129 OS << '\n'; 130 } 131 } 132 } 133 } 134 135 // Parse v2-v4 directory and file tables. 136 static void 137 parseV2DirFileTables(const DWARFDataExtractor &DebugLineData, 138 uint32_t *OffsetPtr, uint64_t EndPrologueOffset, 139 DWARFDebugLine::ContentTypeTracker &ContentTypes, 140 std::vector<DWARFFormValue> &IncludeDirectories, 141 std::vector<DWARFDebugLine::FileNameEntry> &FileNames) { 142 while (*OffsetPtr < EndPrologueOffset) { 143 StringRef S = DebugLineData.getCStrRef(OffsetPtr); 144 if (S.empty()) 145 break; 146 DWARFFormValue Dir(dwarf::DW_FORM_string); 147 Dir.setPValue(S.data()); 148 IncludeDirectories.push_back(Dir); 149 } 150 151 while (*OffsetPtr < EndPrologueOffset) { 152 StringRef Name = DebugLineData.getCStrRef(OffsetPtr); 153 if (Name.empty()) 154 break; 155 DWARFDebugLine::FileNameEntry FileEntry; 156 FileEntry.Name.setForm(dwarf::DW_FORM_string); 157 FileEntry.Name.setPValue(Name.data()); 158 FileEntry.DirIdx = DebugLineData.getULEB128(OffsetPtr); 159 FileEntry.ModTime = DebugLineData.getULEB128(OffsetPtr); 160 FileEntry.Length = DebugLineData.getULEB128(OffsetPtr); 161 FileNames.push_back(FileEntry); 162 } 163 164 ContentTypes.HasModTime = true; 165 ContentTypes.HasLength = true; 166 } 167 168 // Parse v5 directory/file entry content descriptions. 169 // Returns the descriptors, or an empty vector if we did not find a path or 170 // ran off the end of the prologue. 171 static ContentDescriptors 172 parseV5EntryFormat(const DWARFDataExtractor &DebugLineData, uint32_t 173 *OffsetPtr, uint64_t EndPrologueOffset, DWARFDebugLine::ContentTypeTracker 174 *ContentTypes) { 175 ContentDescriptors Descriptors; 176 int FormatCount = DebugLineData.getU8(OffsetPtr); 177 bool HasPath = false; 178 for (int I = 0; I != FormatCount; ++I) { 179 if (*OffsetPtr >= EndPrologueOffset) 180 return ContentDescriptors(); 181 ContentDescriptor Descriptor; 182 Descriptor.Type = 183 dwarf::LineNumberEntryFormat(DebugLineData.getULEB128(OffsetPtr)); 184 Descriptor.Form = dwarf::Form(DebugLineData.getULEB128(OffsetPtr)); 185 if (Descriptor.Type == dwarf::DW_LNCT_path) 186 HasPath = true; 187 if (ContentTypes) 188 ContentTypes->trackContentType(Descriptor.Type); 189 Descriptors.push_back(Descriptor); 190 } 191 return HasPath ? Descriptors : ContentDescriptors(); 192 } 193 194 static bool 195 parseV5DirFileTables(const DWARFDataExtractor &DebugLineData, 196 uint32_t *OffsetPtr, uint64_t EndPrologueOffset, 197 const DWARFFormParams &FormParams, const DWARFContext 198 &Ctx, const DWARFUnit *U, 199 DWARFDebugLine::ContentTypeTracker &ContentTypes, 200 std::vector<DWARFFormValue> &IncludeDirectories, 201 std::vector<DWARFDebugLine::FileNameEntry> &FileNames) { 202 // Get the directory entry description. 203 ContentDescriptors DirDescriptors = 204 parseV5EntryFormat(DebugLineData, OffsetPtr, EndPrologueOffset, nullptr); 205 if (DirDescriptors.empty()) 206 return false; 207 208 // Get the directory entries, according to the format described above. 209 int DirEntryCount = DebugLineData.getU8(OffsetPtr); 210 for (int I = 0; I != DirEntryCount; ++I) { 211 if (*OffsetPtr >= EndPrologueOffset) 212 return false; 213 for (auto Descriptor : DirDescriptors) { 214 DWARFFormValue Value(Descriptor.Form); 215 switch (Descriptor.Type) { 216 case DW_LNCT_path: 217 if (!Value.extractValue(DebugLineData, OffsetPtr, FormParams, &Ctx, U)) 218 return false; 219 IncludeDirectories.push_back(Value); 220 break; 221 default: 222 if (!Value.skipValue(DebugLineData, OffsetPtr, FormParams)) 223 return false; 224 } 225 } 226 } 227 228 // Get the file entry description. 229 ContentDescriptors FileDescriptors = 230 parseV5EntryFormat(DebugLineData, OffsetPtr, EndPrologueOffset, 231 &ContentTypes); 232 if (FileDescriptors.empty()) 233 return false; 234 235 // Get the file entries, according to the format described above. 236 int FileEntryCount = DebugLineData.getU8(OffsetPtr); 237 for (int I = 0; I != FileEntryCount; ++I) { 238 if (*OffsetPtr >= EndPrologueOffset) 239 return false; 240 DWARFDebugLine::FileNameEntry FileEntry; 241 for (auto Descriptor : FileDescriptors) { 242 DWARFFormValue Value(Descriptor.Form); 243 if (!Value.extractValue(DebugLineData, OffsetPtr, FormParams, &Ctx, U)) 244 return false; 245 switch (Descriptor.Type) { 246 case DW_LNCT_path: 247 FileEntry.Name = Value; 248 break; 249 case DW_LNCT_LLVM_source: 250 FileEntry.Source = Value; 251 break; 252 case DW_LNCT_directory_index: 253 FileEntry.DirIdx = Value.getAsUnsignedConstant().getValue(); 254 break; 255 case DW_LNCT_timestamp: 256 FileEntry.ModTime = Value.getAsUnsignedConstant().getValue(); 257 break; 258 case DW_LNCT_size: 259 FileEntry.Length = Value.getAsUnsignedConstant().getValue(); 260 break; 261 case DW_LNCT_MD5: 262 assert(Value.getAsBlock().getValue().size() == 16); 263 std::uninitialized_copy_n(Value.getAsBlock().getValue().begin(), 16, 264 FileEntry.Checksum.Bytes.begin()); 265 break; 266 default: 267 break; 268 } 269 } 270 FileNames.push_back(FileEntry); 271 } 272 return true; 273 } 274 275 bool DWARFDebugLine::Prologue::parse(const DWARFDataExtractor &DebugLineData, 276 uint32_t *OffsetPtr, 277 const DWARFContext &Ctx, 278 const DWARFUnit *U) { 279 const uint64_t PrologueOffset = *OffsetPtr; 280 281 clear(); 282 TotalLength = DebugLineData.getU32(OffsetPtr); 283 if (TotalLength == UINT32_MAX) { 284 FormParams.Format = dwarf::DWARF64; 285 TotalLength = DebugLineData.getU64(OffsetPtr); 286 } else if (TotalLength >= 0xffffff00) { 287 return false; 288 } 289 FormParams.Version = DebugLineData.getU16(OffsetPtr); 290 if (getVersion() < 2) 291 return false; 292 293 if (getVersion() >= 5) { 294 FormParams.AddrSize = DebugLineData.getU8(OffsetPtr); 295 assert((DebugLineData.getAddressSize() == 0 || 296 DebugLineData.getAddressSize() == getAddressSize()) && 297 "Line table header and data extractor disagree"); 298 SegSelectorSize = DebugLineData.getU8(OffsetPtr); 299 } 300 301 PrologueLength = DebugLineData.getUnsigned(OffsetPtr, sizeofPrologueLength()); 302 const uint64_t EndPrologueOffset = PrologueLength + *OffsetPtr; 303 MinInstLength = DebugLineData.getU8(OffsetPtr); 304 if (getVersion() >= 4) 305 MaxOpsPerInst = DebugLineData.getU8(OffsetPtr); 306 DefaultIsStmt = DebugLineData.getU8(OffsetPtr); 307 LineBase = DebugLineData.getU8(OffsetPtr); 308 LineRange = DebugLineData.getU8(OffsetPtr); 309 OpcodeBase = DebugLineData.getU8(OffsetPtr); 310 311 StandardOpcodeLengths.reserve(OpcodeBase - 1); 312 for (uint32_t I = 1; I < OpcodeBase; ++I) { 313 uint8_t OpLen = DebugLineData.getU8(OffsetPtr); 314 StandardOpcodeLengths.push_back(OpLen); 315 } 316 317 if (getVersion() >= 5) { 318 if (!parseV5DirFileTables(DebugLineData, OffsetPtr, EndPrologueOffset, 319 FormParams, Ctx, U, ContentTypes, 320 IncludeDirectories, FileNames)) { 321 fprintf(stderr, 322 "warning: parsing line table prologue at 0x%8.8" PRIx64 323 " found an invalid directory or file table description at" 324 " 0x%8.8" PRIx64 "\n", PrologueOffset, (uint64_t)*OffsetPtr); 325 return false; 326 } 327 } else 328 parseV2DirFileTables(DebugLineData, OffsetPtr, EndPrologueOffset, 329 ContentTypes, IncludeDirectories, FileNames); 330 331 if (*OffsetPtr != EndPrologueOffset) { 332 fprintf(stderr, 333 "warning: parsing line table prologue at 0x%8.8" PRIx64 334 " should have ended at 0x%8.8" PRIx64 335 " but it ended at 0x%8.8" PRIx64 "\n", 336 PrologueOffset, EndPrologueOffset, (uint64_t)*OffsetPtr); 337 return false; 338 } 339 return true; 340 } 341 342 DWARFDebugLine::Row::Row(bool DefaultIsStmt) { reset(DefaultIsStmt); } 343 344 void DWARFDebugLine::Row::postAppend() { 345 BasicBlock = false; 346 PrologueEnd = false; 347 EpilogueBegin = false; 348 } 349 350 void DWARFDebugLine::Row::reset(bool DefaultIsStmt) { 351 Address = 0; 352 Line = 1; 353 Column = 0; 354 File = 1; 355 Isa = 0; 356 Discriminator = 0; 357 IsStmt = DefaultIsStmt; 358 BasicBlock = false; 359 EndSequence = false; 360 PrologueEnd = false; 361 EpilogueBegin = false; 362 } 363 364 void DWARFDebugLine::Row::dumpTableHeader(raw_ostream &OS) { 365 OS << "Address Line Column File ISA Discriminator Flags\n" 366 << "------------------ ------ ------ ------ --- ------------- " 367 "-------------\n"; 368 } 369 370 void DWARFDebugLine::Row::dump(raw_ostream &OS) const { 371 OS << format("0x%16.16" PRIx64 " %6u %6u", Address, Line, Column) 372 << format(" %6u %3u %13u ", File, Isa, Discriminator) 373 << (IsStmt ? " is_stmt" : "") << (BasicBlock ? " basic_block" : "") 374 << (PrologueEnd ? " prologue_end" : "") 375 << (EpilogueBegin ? " epilogue_begin" : "") 376 << (EndSequence ? " end_sequence" : "") << '\n'; 377 } 378 379 DWARFDebugLine::Sequence::Sequence() { reset(); } 380 381 void DWARFDebugLine::Sequence::reset() { 382 LowPC = 0; 383 HighPC = 0; 384 FirstRowIndex = 0; 385 LastRowIndex = 0; 386 Empty = true; 387 } 388 389 DWARFDebugLine::LineTable::LineTable() { clear(); } 390 391 void DWARFDebugLine::LineTable::dump(raw_ostream &OS, 392 DIDumpOptions DumpOptions) const { 393 Prologue.dump(OS, DumpOptions); 394 OS << '\n'; 395 396 if (!Rows.empty()) { 397 Row::dumpTableHeader(OS); 398 for (const Row &R : Rows) { 399 R.dump(OS); 400 } 401 } 402 } 403 404 void DWARFDebugLine::LineTable::clear() { 405 Prologue.clear(); 406 Rows.clear(); 407 Sequences.clear(); 408 } 409 410 DWARFDebugLine::ParsingState::ParsingState(struct LineTable *LT) 411 : LineTable(LT) { 412 resetRowAndSequence(); 413 } 414 415 void DWARFDebugLine::ParsingState::resetRowAndSequence() { 416 Row.reset(LineTable->Prologue.DefaultIsStmt); 417 Sequence.reset(); 418 } 419 420 void DWARFDebugLine::ParsingState::appendRowToMatrix(uint32_t Offset) { 421 if (Sequence.Empty) { 422 // Record the beginning of instruction sequence. 423 Sequence.Empty = false; 424 Sequence.LowPC = Row.Address; 425 Sequence.FirstRowIndex = RowNumber; 426 } 427 ++RowNumber; 428 LineTable->appendRow(Row); 429 if (Row.EndSequence) { 430 // Record the end of instruction sequence. 431 Sequence.HighPC = Row.Address; 432 Sequence.LastRowIndex = RowNumber; 433 if (Sequence.isValid()) 434 LineTable->appendSequence(Sequence); 435 Sequence.reset(); 436 } 437 Row.postAppend(); 438 } 439 440 const DWARFDebugLine::LineTable * 441 DWARFDebugLine::getLineTable(uint32_t Offset) const { 442 LineTableConstIter Pos = LineTableMap.find(Offset); 443 if (Pos != LineTableMap.end()) 444 return &Pos->second; 445 return nullptr; 446 } 447 448 const DWARFDebugLine::LineTable * 449 DWARFDebugLine::getOrParseLineTable(DWARFDataExtractor &DebugLineData, 450 uint32_t Offset, const DWARFContext &Ctx, 451 const DWARFUnit *U) { 452 std::pair<LineTableIter, bool> Pos = 453 LineTableMap.insert(LineTableMapTy::value_type(Offset, LineTable())); 454 LineTable *LT = &Pos.first->second; 455 if (Pos.second) { 456 if (!LT->parse(DebugLineData, &Offset, Ctx, U)) 457 return nullptr; 458 } 459 return LT; 460 } 461 462 bool DWARFDebugLine::LineTable::parse(DWARFDataExtractor &DebugLineData, 463 uint32_t *OffsetPtr, 464 const DWARFContext &Ctx, 465 const DWARFUnit *U, raw_ostream *OS) { 466 const uint32_t DebugLineOffset = *OffsetPtr; 467 468 clear(); 469 470 if (!Prologue.parse(DebugLineData, OffsetPtr, Ctx, U)) { 471 // Restore our offset and return false to indicate failure! 472 *OffsetPtr = DebugLineOffset; 473 return false; 474 } 475 476 if (OS) { 477 // The presence of OS signals verbose dumping. 478 DIDumpOptions DumpOptions; 479 DumpOptions.Verbose = true; 480 Prologue.dump(*OS, DumpOptions); 481 } 482 483 const uint32_t EndOffset = 484 DebugLineOffset + Prologue.TotalLength + Prologue.sizeofTotalLength(); 485 486 // See if we should tell the data extractor the address size. 487 if (DebugLineData.getAddressSize() == 0) 488 DebugLineData.setAddressSize(Prologue.getAddressSize()); 489 else 490 assert(Prologue.getAddressSize() == 0 || 491 Prologue.getAddressSize() == DebugLineData.getAddressSize()); 492 493 ParsingState State(this); 494 495 while (*OffsetPtr < EndOffset) { 496 if (OS) 497 *OS << format("0x%08.08" PRIx32 ": ", *OffsetPtr); 498 499 uint8_t Opcode = DebugLineData.getU8(OffsetPtr); 500 501 if (OS) 502 *OS << format("%02.02" PRIx8 " ", Opcode); 503 504 if (Opcode == 0) { 505 // Extended Opcodes always start with a zero opcode followed by 506 // a uleb128 length so you can skip ones you don't know about 507 uint64_t Len = DebugLineData.getULEB128(OffsetPtr); 508 uint32_t ExtOffset = *OffsetPtr; 509 510 // Tolerate zero-length; assume length is correct and soldier on. 511 if (Len == 0) { 512 if (OS) 513 *OS << "Badly formed extended line op (length 0)\n"; 514 continue; 515 } 516 517 uint8_t SubOpcode = DebugLineData.getU8(OffsetPtr); 518 if (OS) 519 *OS << LNExtendedString(SubOpcode); 520 switch (SubOpcode) { 521 case DW_LNE_end_sequence: 522 // Set the end_sequence register of the state machine to true and 523 // append a row to the matrix using the current values of the 524 // state-machine registers. Then reset the registers to the initial 525 // values specified above. Every statement program sequence must end 526 // with a DW_LNE_end_sequence instruction which creates a row whose 527 // address is that of the byte after the last target machine instruction 528 // of the sequence. 529 State.Row.EndSequence = true; 530 State.appendRowToMatrix(*OffsetPtr); 531 if (OS) { 532 *OS << "\n"; 533 OS->indent(12); 534 State.Row.dump(*OS); 535 } 536 State.resetRowAndSequence(); 537 break; 538 539 case DW_LNE_set_address: 540 // Takes a single relocatable address as an operand. The size of the 541 // operand is the size appropriate to hold an address on the target 542 // machine. Set the address register to the value given by the 543 // relocatable address. All of the other statement program opcodes 544 // that affect the address register add a delta to it. This instruction 545 // stores a relocatable value into it instead. 546 // 547 // Make sure the extractor knows the address size. If not, infer it 548 // from the size of the operand. 549 if (DebugLineData.getAddressSize() == 0) 550 DebugLineData.setAddressSize(Len - 1); 551 else 552 assert(DebugLineData.getAddressSize() == Len - 1); 553 State.Row.Address = DebugLineData.getRelocatedAddress(OffsetPtr); 554 if (OS) 555 *OS << format(" (0x%16.16" PRIx64 ")", State.Row.Address); 556 break; 557 558 case DW_LNE_define_file: 559 // Takes 4 arguments. The first is a null terminated string containing 560 // a source file name. The second is an unsigned LEB128 number 561 // representing the directory index of the directory in which the file 562 // was found. The third is an unsigned LEB128 number representing the 563 // time of last modification of the file. The fourth is an unsigned 564 // LEB128 number representing the length in bytes of the file. The time 565 // and length fields may contain LEB128(0) if the information is not 566 // available. 567 // 568 // The directory index represents an entry in the include_directories 569 // section of the statement program prologue. The index is LEB128(0) 570 // if the file was found in the current directory of the compilation, 571 // LEB128(1) if it was found in the first directory in the 572 // include_directories section, and so on. The directory index is 573 // ignored for file names that represent full path names. 574 // 575 // The files are numbered, starting at 1, in the order in which they 576 // appear; the names in the prologue come before names defined by 577 // the DW_LNE_define_file instruction. These numbers are used in the 578 // the file register of the state machine. 579 { 580 FileNameEntry FileEntry; 581 const char *Name = DebugLineData.getCStr(OffsetPtr); 582 FileEntry.Name.setForm(dwarf::DW_FORM_string); 583 FileEntry.Name.setPValue(Name); 584 FileEntry.DirIdx = DebugLineData.getULEB128(OffsetPtr); 585 FileEntry.ModTime = DebugLineData.getULEB128(OffsetPtr); 586 FileEntry.Length = DebugLineData.getULEB128(OffsetPtr); 587 Prologue.FileNames.push_back(FileEntry); 588 if (OS) 589 *OS << " (" << Name << ", dir=" << FileEntry.DirIdx << ", mod_time=" 590 << format("(0x%16.16" PRIx64 ")", FileEntry.ModTime) 591 << ", length=" << FileEntry.Length << ")"; 592 } 593 break; 594 595 case DW_LNE_set_discriminator: 596 State.Row.Discriminator = DebugLineData.getULEB128(OffsetPtr); 597 if (OS) 598 *OS << " (" << State.Row.Discriminator << ")"; 599 break; 600 601 default: 602 if (OS) 603 *OS << format("Unrecognized extended op 0x%02.02" PRIx8, SubOpcode) 604 << format(" length %" PRIx64, Len); 605 // Len doesn't include the zero opcode byte or the length itself, but 606 // it does include the sub_opcode, so we have to adjust for that. 607 (*OffsetPtr) += Len - 1; 608 break; 609 } 610 // Make sure the stated and parsed lengths are the same. 611 // Otherwise we have an unparseable line-number program. 612 if (*OffsetPtr - ExtOffset != Len) { 613 fprintf(stderr, "Unexpected line op length at offset 0x%8.8" PRIx32 614 " expected 0x%2.2" PRIx64 " found 0x%2.2" PRIx32 "\n", 615 ExtOffset, Len, *OffsetPtr - ExtOffset); 616 // Skip the rest of the line-number program. 617 *OffsetPtr = EndOffset; 618 return false; 619 } 620 } else if (Opcode < Prologue.OpcodeBase) { 621 if (OS) 622 *OS << LNStandardString(Opcode); 623 switch (Opcode) { 624 // Standard Opcodes 625 case DW_LNS_copy: 626 // Takes no arguments. Append a row to the matrix using the 627 // current values of the state-machine registers. Then set 628 // the basic_block register to false. 629 State.appendRowToMatrix(*OffsetPtr); 630 if (OS) { 631 *OS << "\n"; 632 OS->indent(12); 633 State.Row.dump(*OS); 634 *OS << "\n"; 635 } 636 break; 637 638 case DW_LNS_advance_pc: 639 // Takes a single unsigned LEB128 operand, multiplies it by the 640 // min_inst_length field of the prologue, and adds the 641 // result to the address register of the state machine. 642 { 643 uint64_t AddrOffset = 644 DebugLineData.getULEB128(OffsetPtr) * Prologue.MinInstLength; 645 State.Row.Address += AddrOffset; 646 if (OS) 647 *OS << " (" << AddrOffset << ")"; 648 } 649 break; 650 651 case DW_LNS_advance_line: 652 // Takes a single signed LEB128 operand and adds that value to 653 // the line register of the state machine. 654 State.Row.Line += DebugLineData.getSLEB128(OffsetPtr); 655 if (OS) 656 *OS << " (" << State.Row.Line << ")"; 657 break; 658 659 case DW_LNS_set_file: 660 // Takes a single unsigned LEB128 operand and stores it in the file 661 // register of the state machine. 662 State.Row.File = DebugLineData.getULEB128(OffsetPtr); 663 if (OS) 664 *OS << " (" << State.Row.File << ")"; 665 break; 666 667 case DW_LNS_set_column: 668 // Takes a single unsigned LEB128 operand and stores it in the 669 // column register of the state machine. 670 State.Row.Column = DebugLineData.getULEB128(OffsetPtr); 671 if (OS) 672 *OS << " (" << State.Row.Column << ")"; 673 break; 674 675 case DW_LNS_negate_stmt: 676 // Takes no arguments. Set the is_stmt register of the state 677 // machine to the logical negation of its current value. 678 State.Row.IsStmt = !State.Row.IsStmt; 679 break; 680 681 case DW_LNS_set_basic_block: 682 // Takes no arguments. Set the basic_block register of the 683 // state machine to true 684 State.Row.BasicBlock = true; 685 break; 686 687 case DW_LNS_const_add_pc: 688 // Takes no arguments. Add to the address register of the state 689 // machine the address increment value corresponding to special 690 // opcode 255. The motivation for DW_LNS_const_add_pc is this: 691 // when the statement program needs to advance the address by a 692 // small amount, it can use a single special opcode, which occupies 693 // a single byte. When it needs to advance the address by up to 694 // twice the range of the last special opcode, it can use 695 // DW_LNS_const_add_pc followed by a special opcode, for a total 696 // of two bytes. Only if it needs to advance the address by more 697 // than twice that range will it need to use both DW_LNS_advance_pc 698 // and a special opcode, requiring three or more bytes. 699 { 700 uint8_t AdjustOpcode = 255 - Prologue.OpcodeBase; 701 uint64_t AddrOffset = 702 (AdjustOpcode / Prologue.LineRange) * Prologue.MinInstLength; 703 State.Row.Address += AddrOffset; 704 if (OS) 705 *OS 706 << format(" (0x%16.16" PRIx64 ")", AddrOffset); 707 } 708 break; 709 710 case DW_LNS_fixed_advance_pc: 711 // Takes a single uhalf operand. Add to the address register of 712 // the state machine the value of the (unencoded) operand. This 713 // is the only extended opcode that takes an argument that is not 714 // a variable length number. The motivation for DW_LNS_fixed_advance_pc 715 // is this: existing assemblers cannot emit DW_LNS_advance_pc or 716 // special opcodes because they cannot encode LEB128 numbers or 717 // judge when the computation of a special opcode overflows and 718 // requires the use of DW_LNS_advance_pc. Such assemblers, however, 719 // can use DW_LNS_fixed_advance_pc instead, sacrificing compression. 720 { 721 uint16_t PCOffset = DebugLineData.getU16(OffsetPtr); 722 State.Row.Address += PCOffset; 723 if (OS) 724 *OS 725 << format(" (0x%16.16" PRIx64 ")", PCOffset); 726 } 727 break; 728 729 case DW_LNS_set_prologue_end: 730 // Takes no arguments. Set the prologue_end register of the 731 // state machine to true 732 State.Row.PrologueEnd = true; 733 break; 734 735 case DW_LNS_set_epilogue_begin: 736 // Takes no arguments. Set the basic_block register of the 737 // state machine to true 738 State.Row.EpilogueBegin = true; 739 break; 740 741 case DW_LNS_set_isa: 742 // Takes a single unsigned LEB128 operand and stores it in the 743 // column register of the state machine. 744 State.Row.Isa = DebugLineData.getULEB128(OffsetPtr); 745 if (OS) 746 *OS << " (" << State.Row.Isa << ")"; 747 break; 748 749 default: 750 // Handle any unknown standard opcodes here. We know the lengths 751 // of such opcodes because they are specified in the prologue 752 // as a multiple of LEB128 operands for each opcode. 753 { 754 assert(Opcode - 1U < Prologue.StandardOpcodeLengths.size()); 755 uint8_t OpcodeLength = Prologue.StandardOpcodeLengths[Opcode - 1]; 756 for (uint8_t I = 0; I < OpcodeLength; ++I) { 757 uint64_t Value = DebugLineData.getULEB128(OffsetPtr); 758 if (OS) 759 *OS << format("Skipping ULEB128 value: 0x%16.16" PRIx64 ")\n", 760 Value); 761 } 762 } 763 break; 764 } 765 } else { 766 // Special Opcodes 767 768 // A special opcode value is chosen based on the amount that needs 769 // to be added to the line and address registers. The maximum line 770 // increment for a special opcode is the value of the line_base 771 // field in the header, plus the value of the line_range field, 772 // minus 1 (line base + line range - 1). If the desired line 773 // increment is greater than the maximum line increment, a standard 774 // opcode must be used instead of a special opcode. The "address 775 // advance" is calculated by dividing the desired address increment 776 // by the minimum_instruction_length field from the header. The 777 // special opcode is then calculated using the following formula: 778 // 779 // opcode = (desired line increment - line_base) + 780 // (line_range * address advance) + opcode_base 781 // 782 // If the resulting opcode is greater than 255, a standard opcode 783 // must be used instead. 784 // 785 // To decode a special opcode, subtract the opcode_base from the 786 // opcode itself to give the adjusted opcode. The amount to 787 // increment the address register is the result of the adjusted 788 // opcode divided by the line_range multiplied by the 789 // minimum_instruction_length field from the header. That is: 790 // 791 // address increment = (adjusted opcode / line_range) * 792 // minimum_instruction_length 793 // 794 // The amount to increment the line register is the line_base plus 795 // the result of the adjusted opcode modulo the line_range. That is: 796 // 797 // line increment = line_base + (adjusted opcode % line_range) 798 799 uint8_t AdjustOpcode = Opcode - Prologue.OpcodeBase; 800 uint64_t AddrOffset = 801 (AdjustOpcode / Prologue.LineRange) * Prologue.MinInstLength; 802 int32_t LineOffset = 803 Prologue.LineBase + (AdjustOpcode % Prologue.LineRange); 804 State.Row.Line += LineOffset; 805 State.Row.Address += AddrOffset; 806 807 if (OS) { 808 *OS << "address += " << ((uint32_t)AdjustOpcode) 809 << ", line += " << LineOffset << "\n"; 810 OS->indent(12); 811 State.Row.dump(*OS); 812 } 813 814 State.appendRowToMatrix(*OffsetPtr); 815 // Reset discriminator to 0. 816 State.Row.Discriminator = 0; 817 } 818 if(OS) 819 *OS << "\n"; 820 } 821 822 if (!State.Sequence.Empty) { 823 fprintf(stderr, "warning: last sequence in debug line table is not" 824 "terminated!\n"); 825 } 826 827 // Sort all sequences so that address lookup will work faster. 828 if (!Sequences.empty()) { 829 std::sort(Sequences.begin(), Sequences.end(), Sequence::orderByLowPC); 830 // Note: actually, instruction address ranges of sequences should not 831 // overlap (in shared objects and executables). If they do, the address 832 // lookup would still work, though, but result would be ambiguous. 833 // We don't report warning in this case. For example, 834 // sometimes .so compiled from multiple object files contains a few 835 // rudimentary sequences for address ranges [0x0, 0xsomething). 836 } 837 838 return EndOffset; 839 } 840 841 uint32_t 842 DWARFDebugLine::LineTable::findRowInSeq(const DWARFDebugLine::Sequence &Seq, 843 uint64_t Address) const { 844 if (!Seq.containsPC(Address)) 845 return UnknownRowIndex; 846 // Search for instruction address in the rows describing the sequence. 847 // Rows are stored in a vector, so we may use arithmetical operations with 848 // iterators. 849 DWARFDebugLine::Row Row; 850 Row.Address = Address; 851 RowIter FirstRow = Rows.begin() + Seq.FirstRowIndex; 852 RowIter LastRow = Rows.begin() + Seq.LastRowIndex; 853 LineTable::RowIter RowPos = std::lower_bound( 854 FirstRow, LastRow, Row, DWARFDebugLine::Row::orderByAddress); 855 if (RowPos == LastRow) { 856 return Seq.LastRowIndex - 1; 857 } 858 uint32_t Index = Seq.FirstRowIndex + (RowPos - FirstRow); 859 if (RowPos->Address > Address) { 860 if (RowPos == FirstRow) 861 return UnknownRowIndex; 862 else 863 Index--; 864 } 865 return Index; 866 } 867 868 uint32_t DWARFDebugLine::LineTable::lookupAddress(uint64_t Address) const { 869 if (Sequences.empty()) 870 return UnknownRowIndex; 871 // First, find an instruction sequence containing the given address. 872 DWARFDebugLine::Sequence Sequence; 873 Sequence.LowPC = Address; 874 SequenceIter FirstSeq = Sequences.begin(); 875 SequenceIter LastSeq = Sequences.end(); 876 SequenceIter SeqPos = std::lower_bound( 877 FirstSeq, LastSeq, Sequence, DWARFDebugLine::Sequence::orderByLowPC); 878 DWARFDebugLine::Sequence FoundSeq; 879 if (SeqPos == LastSeq) { 880 FoundSeq = Sequences.back(); 881 } else if (SeqPos->LowPC == Address) { 882 FoundSeq = *SeqPos; 883 } else { 884 if (SeqPos == FirstSeq) 885 return UnknownRowIndex; 886 FoundSeq = *(SeqPos - 1); 887 } 888 return findRowInSeq(FoundSeq, Address); 889 } 890 891 bool DWARFDebugLine::LineTable::lookupAddressRange( 892 uint64_t Address, uint64_t Size, std::vector<uint32_t> &Result) const { 893 if (Sequences.empty()) 894 return false; 895 uint64_t EndAddr = Address + Size; 896 // First, find an instruction sequence containing the given address. 897 DWARFDebugLine::Sequence Sequence; 898 Sequence.LowPC = Address; 899 SequenceIter FirstSeq = Sequences.begin(); 900 SequenceIter LastSeq = Sequences.end(); 901 SequenceIter SeqPos = std::lower_bound( 902 FirstSeq, LastSeq, Sequence, DWARFDebugLine::Sequence::orderByLowPC); 903 if (SeqPos == LastSeq || SeqPos->LowPC != Address) { 904 if (SeqPos == FirstSeq) 905 return false; 906 SeqPos--; 907 } 908 if (!SeqPos->containsPC(Address)) 909 return false; 910 911 SequenceIter StartPos = SeqPos; 912 913 // Add the rows from the first sequence to the vector, starting with the 914 // index we just calculated 915 916 while (SeqPos != LastSeq && SeqPos->LowPC < EndAddr) { 917 const DWARFDebugLine::Sequence &CurSeq = *SeqPos; 918 // For the first sequence, we need to find which row in the sequence is the 919 // first in our range. 920 uint32_t FirstRowIndex = CurSeq.FirstRowIndex; 921 if (SeqPos == StartPos) 922 FirstRowIndex = findRowInSeq(CurSeq, Address); 923 924 // Figure out the last row in the range. 925 uint32_t LastRowIndex = findRowInSeq(CurSeq, EndAddr - 1); 926 if (LastRowIndex == UnknownRowIndex) 927 LastRowIndex = CurSeq.LastRowIndex - 1; 928 929 assert(FirstRowIndex != UnknownRowIndex); 930 assert(LastRowIndex != UnknownRowIndex); 931 932 for (uint32_t I = FirstRowIndex; I <= LastRowIndex; ++I) { 933 Result.push_back(I); 934 } 935 936 ++SeqPos; 937 } 938 939 return true; 940 } 941 942 bool DWARFDebugLine::LineTable::hasFileAtIndex(uint64_t FileIndex) const { 943 return FileIndex != 0 && FileIndex <= Prologue.FileNames.size(); 944 } 945 946 Optional<StringRef> DWARFDebugLine::LineTable::getSourceByIndex(uint64_t FileIndex, 947 FileLineInfoKind Kind) const { 948 if (Kind == FileLineInfoKind::None || !hasFileAtIndex(FileIndex)) 949 return None; 950 const FileNameEntry &Entry = Prologue.FileNames[FileIndex - 1]; 951 if (Optional<const char *> source = Entry.Source.getAsCString()) 952 return StringRef(*source); 953 return None; 954 } 955 956 bool DWARFDebugLine::LineTable::getFileNameByIndex(uint64_t FileIndex, 957 const char *CompDir, 958 FileLineInfoKind Kind, 959 std::string &Result) const { 960 if (Kind == FileLineInfoKind::None || !hasFileAtIndex(FileIndex)) 961 return false; 962 const FileNameEntry &Entry = Prologue.FileNames[FileIndex - 1]; 963 StringRef FileName = Entry.Name.getAsCString().getValue(); 964 if (Kind != FileLineInfoKind::AbsoluteFilePath || 965 sys::path::is_absolute(FileName)) { 966 Result = FileName; 967 return true; 968 } 969 970 SmallString<16> FilePath; 971 uint64_t IncludeDirIndex = Entry.DirIdx; 972 StringRef IncludeDir; 973 // Be defensive about the contents of Entry. 974 if (IncludeDirIndex > 0 && 975 IncludeDirIndex <= Prologue.IncludeDirectories.size()) 976 IncludeDir = Prologue.IncludeDirectories[IncludeDirIndex - 1] 977 .getAsCString() 978 .getValue(); 979 980 // We may still need to append compilation directory of compile unit. 981 // We know that FileName is not absolute, the only way to have an 982 // absolute path at this point would be if IncludeDir is absolute. 983 if (CompDir && Kind == FileLineInfoKind::AbsoluteFilePath && 984 sys::path::is_relative(IncludeDir)) 985 sys::path::append(FilePath, CompDir); 986 987 // sys::path::append skips empty strings. 988 sys::path::append(FilePath, IncludeDir, FileName); 989 Result = FilePath.str(); 990 return true; 991 } 992 993 bool DWARFDebugLine::LineTable::getFileLineInfoForAddress( 994 uint64_t Address, const char *CompDir, FileLineInfoKind Kind, 995 DILineInfo &Result) const { 996 // Get the index of row we're looking for in the line table. 997 uint32_t RowIndex = lookupAddress(Address); 998 if (RowIndex == -1U) 999 return false; 1000 // Take file number and line/column from the row. 1001 const auto &Row = Rows[RowIndex]; 1002 if (!getFileNameByIndex(Row.File, CompDir, Kind, Result.FileName)) 1003 return false; 1004 Result.Line = Row.Line; 1005 Result.Column = Row.Column; 1006 Result.Discriminator = Row.Discriminator; 1007 Result.Source = getSourceByIndex(Row.File, Kind); 1008 return true; 1009 } 1010