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