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