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