1 //===- DWARFDebugLine.cpp -------------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "llvm/ADT/SmallString.h"
11 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
12 #include "llvm/DebugInfo/DWARF/DWARFDebugLine.h"
13 #include "llvm/DebugInfo/DWARF/DWARFRelocMap.h"
14 #include "llvm/Support/Dwarf.h"
15 #include "llvm/Support/Format.h"
16 #include "llvm/Support/Path.h"
17 #include "llvm/Support/raw_ostream.h"
26 using namespace dwarf;
28 typedef DILineInfoSpecifier::FileLineInfoKind FileLineInfoKind;
30 DWARFDebugLine::Prologue::Prologue() { clear(); }
32 void DWARFDebugLine::Prologue::clear() {
33 TotalLength = Version = PrologueLength = 0;
34 MinInstLength = MaxOpsPerInst = DefaultIsStmt = LineBase = LineRange = 0;
37 StandardOpcodeLengths.clear();
38 IncludeDirectories.clear();
42 void DWARFDebugLine::Prologue::dump(raw_ostream &OS) const {
43 OS << "Line table prologue:\n"
44 << format(" total_length: 0x%8.8" PRIx64 "\n", TotalLength)
45 << format(" version: %u\n", Version)
46 << format(" prologue_length: 0x%8.8" PRIx64 "\n", PrologueLength)
47 << format(" min_inst_length: %u\n", MinInstLength)
48 << format(Version >= 4 ? "max_ops_per_inst: %u\n" : "", MaxOpsPerInst)
49 << format(" default_is_stmt: %u\n", DefaultIsStmt)
50 << format(" line_base: %i\n", LineBase)
51 << format(" line_range: %u\n", LineRange)
52 << format(" opcode_base: %u\n", OpcodeBase);
54 for (uint32_t i = 0; i < StandardOpcodeLengths.size(); ++i)
55 OS << format("standard_opcode_lengths[%s] = %u\n",
56 LNStandardString(i + 1).data(), StandardOpcodeLengths[i]);
58 if (!IncludeDirectories.empty())
59 for (uint32_t i = 0; i < IncludeDirectories.size(); ++i)
60 OS << format("include_directories[%3u] = '", i + 1)
61 << IncludeDirectories[i] << "'\n";
63 if (!FileNames.empty()) {
64 OS << " Dir Mod Time File Len File Name\n"
65 << " ---- ---------- ---------- -----------"
67 for (uint32_t i = 0; i < FileNames.size(); ++i) {
68 const FileNameEntry &fileEntry = FileNames[i];
69 OS << format("file_names[%3u] %4" PRIu64 " ", i + 1, fileEntry.DirIdx)
70 << format("0x%8.8" PRIx64 " 0x%8.8" PRIx64 " ", fileEntry.ModTime,
72 << fileEntry.Name << '\n';
77 bool DWARFDebugLine::Prologue::parse(DataExtractor debug_line_data,
78 uint32_t *offset_ptr) {
79 const uint64_t prologue_offset = *offset_ptr;
82 TotalLength = debug_line_data.getU32(offset_ptr);
83 if (TotalLength == UINT32_MAX) {
85 TotalLength = debug_line_data.getU64(offset_ptr);
86 } else if (TotalLength > 0xffffff00) {
89 Version = debug_line_data.getU16(offset_ptr);
94 debug_line_data.getUnsigned(offset_ptr, sizeofPrologueLength());
95 const uint64_t end_prologue_offset = PrologueLength + *offset_ptr;
96 MinInstLength = debug_line_data.getU8(offset_ptr);
98 MaxOpsPerInst = debug_line_data.getU8(offset_ptr);
99 DefaultIsStmt = debug_line_data.getU8(offset_ptr);
100 LineBase = debug_line_data.getU8(offset_ptr);
101 LineRange = debug_line_data.getU8(offset_ptr);
102 OpcodeBase = debug_line_data.getU8(offset_ptr);
104 StandardOpcodeLengths.reserve(OpcodeBase - 1);
105 for (uint32_t i = 1; i < OpcodeBase; ++i) {
106 uint8_t op_len = debug_line_data.getU8(offset_ptr);
107 StandardOpcodeLengths.push_back(op_len);
110 while (*offset_ptr < end_prologue_offset) {
111 const char *s = debug_line_data.getCStr(offset_ptr);
113 IncludeDirectories.push_back(s);
118 while (*offset_ptr < end_prologue_offset) {
119 const char *name = debug_line_data.getCStr(offset_ptr);
120 if (name && name[0]) {
121 FileNameEntry fileEntry;
122 fileEntry.Name = name;
123 fileEntry.DirIdx = debug_line_data.getULEB128(offset_ptr);
124 fileEntry.ModTime = debug_line_data.getULEB128(offset_ptr);
125 fileEntry.Length = debug_line_data.getULEB128(offset_ptr);
126 FileNames.push_back(fileEntry);
132 if (*offset_ptr != end_prologue_offset) {
133 fprintf(stderr, "warning: parsing line table prologue at 0x%8.8" PRIx64
134 " should have ended at 0x%8.8" PRIx64
135 " but it ended at 0x%8.8" PRIx64 "\n",
136 prologue_offset, end_prologue_offset, (uint64_t)*offset_ptr);
142 DWARFDebugLine::Row::Row(bool default_is_stmt) { reset(default_is_stmt); }
144 void DWARFDebugLine::Row::postAppend() {
147 EpilogueBegin = false;
150 void DWARFDebugLine::Row::reset(bool default_is_stmt) {
157 IsStmt = default_is_stmt;
161 EpilogueBegin = false;
164 void DWARFDebugLine::Row::dump(raw_ostream &OS) const {
165 OS << format("0x%16.16" PRIx64 " %6u %6u", Address, Line, Column)
166 << format(" %6u %3u %13u ", File, Isa, Discriminator)
167 << (IsStmt ? " is_stmt" : "") << (BasicBlock ? " basic_block" : "")
168 << (PrologueEnd ? " prologue_end" : "")
169 << (EpilogueBegin ? " epilogue_begin" : "")
170 << (EndSequence ? " end_sequence" : "") << '\n';
173 DWARFDebugLine::Sequence::Sequence() { reset(); }
175 void DWARFDebugLine::Sequence::reset() {
183 DWARFDebugLine::LineTable::LineTable() { clear(); }
185 void DWARFDebugLine::LineTable::dump(raw_ostream &OS) const {
190 OS << "Address Line Column File ISA Discriminator Flags\n"
191 << "------------------ ------ ------ ------ --- ------------- "
193 for (const Row &R : Rows) {
199 void DWARFDebugLine::LineTable::clear() {
205 DWARFDebugLine::ParsingState::ParsingState(struct LineTable *LT)
206 : LineTable(LT), RowNumber(0) {
207 resetRowAndSequence();
210 void DWARFDebugLine::ParsingState::resetRowAndSequence() {
211 Row.reset(LineTable->Prologue.DefaultIsStmt);
215 void DWARFDebugLine::ParsingState::appendRowToMatrix(uint32_t offset) {
216 if (Sequence.Empty) {
217 // Record the beginning of instruction sequence.
218 Sequence.Empty = false;
219 Sequence.LowPC = Row.Address;
220 Sequence.FirstRowIndex = RowNumber;
223 LineTable->appendRow(Row);
224 if (Row.EndSequence) {
225 // Record the end of instruction sequence.
226 Sequence.HighPC = Row.Address;
227 Sequence.LastRowIndex = RowNumber;
228 if (Sequence.isValid())
229 LineTable->appendSequence(Sequence);
235 const DWARFDebugLine::LineTable *
236 DWARFDebugLine::getLineTable(uint32_t offset) const {
237 LineTableConstIter pos = LineTableMap.find(offset);
238 if (pos != LineTableMap.end())
243 const DWARFDebugLine::LineTable *
244 DWARFDebugLine::getOrParseLineTable(DataExtractor debug_line_data,
246 std::pair<LineTableIter, bool> pos =
247 LineTableMap.insert(LineTableMapTy::value_type(offset, LineTable()));
248 LineTable *LT = &pos.first->second;
250 if (!LT->parse(debug_line_data, RelocMap, &offset))
256 bool DWARFDebugLine::LineTable::parse(DataExtractor debug_line_data,
257 const RelocAddrMap *RMap,
258 uint32_t *offset_ptr) {
259 const uint32_t debug_line_offset = *offset_ptr;
263 if (!Prologue.parse(debug_line_data, offset_ptr)) {
264 // Restore our offset and return false to indicate failure!
265 *offset_ptr = debug_line_offset;
269 const uint32_t end_offset =
270 debug_line_offset + Prologue.TotalLength + Prologue.sizeofTotalLength();
272 ParsingState State(this);
274 while (*offset_ptr < end_offset) {
275 uint8_t opcode = debug_line_data.getU8(offset_ptr);
278 // Extended Opcodes always start with a zero opcode followed by
279 // a uleb128 length so you can skip ones you don't know about
280 uint32_t ext_offset = *offset_ptr;
281 uint64_t len = debug_line_data.getULEB128(offset_ptr);
282 uint32_t arg_size = len - (*offset_ptr - ext_offset);
284 uint8_t sub_opcode = debug_line_data.getU8(offset_ptr);
285 switch (sub_opcode) {
286 case DW_LNE_end_sequence:
287 // Set the end_sequence register of the state machine to true and
288 // append a row to the matrix using the current values of the
289 // state-machine registers. Then reset the registers to the initial
290 // values specified above. Every statement program sequence must end
291 // with a DW_LNE_end_sequence instruction which creates a row whose
292 // address is that of the byte after the last target machine instruction
294 State.Row.EndSequence = true;
295 State.appendRowToMatrix(*offset_ptr);
296 State.resetRowAndSequence();
299 case DW_LNE_set_address:
300 // Takes a single relocatable address as an operand. The size of the
301 // operand is the size appropriate to hold an address on the target
302 // machine. Set the address register to the value given by the
303 // relocatable address. All of the other statement program opcodes
304 // that affect the address register add a delta to it. This instruction
305 // stores a relocatable value into it instead.
307 getRelocatedValue(debug_line_data, debug_line_data.getAddressSize(),
311 case DW_LNE_define_file:
312 // Takes 4 arguments. The first is a null terminated string containing
313 // a source file name. The second is an unsigned LEB128 number
314 // representing the directory index of the directory in which the file
315 // was found. The third is an unsigned LEB128 number representing the
316 // time of last modification of the file. The fourth is an unsigned
317 // LEB128 number representing the length in bytes of the file. The time
318 // and length fields may contain LEB128(0) if the information is not
321 // The directory index represents an entry in the include_directories
322 // section of the statement program prologue. The index is LEB128(0)
323 // if the file was found in the current directory of the compilation,
324 // LEB128(1) if it was found in the first directory in the
325 // include_directories section, and so on. The directory index is
326 // ignored for file names that represent full path names.
328 // The files are numbered, starting at 1, in the order in which they
329 // appear; the names in the prologue come before names defined by
330 // the DW_LNE_define_file instruction. These numbers are used in the
331 // the file register of the state machine.
333 FileNameEntry fileEntry;
334 fileEntry.Name = debug_line_data.getCStr(offset_ptr);
335 fileEntry.DirIdx = debug_line_data.getULEB128(offset_ptr);
336 fileEntry.ModTime = debug_line_data.getULEB128(offset_ptr);
337 fileEntry.Length = debug_line_data.getULEB128(offset_ptr);
338 Prologue.FileNames.push_back(fileEntry);
342 case DW_LNE_set_discriminator:
343 State.Row.Discriminator = debug_line_data.getULEB128(offset_ptr);
347 // Length doesn't include the zero opcode byte or the length itself, but
348 // it does include the sub_opcode, so we have to adjust for that below
349 (*offset_ptr) += arg_size;
352 } else if (opcode < Prologue.OpcodeBase) {
356 // Takes no arguments. Append a row to the matrix using the
357 // current values of the state-machine registers. Then set
358 // the basic_block register to false.
359 State.appendRowToMatrix(*offset_ptr);
362 case DW_LNS_advance_pc:
363 // Takes a single unsigned LEB128 operand, multiplies it by the
364 // min_inst_length field of the prologue, and adds the
365 // result to the address register of the state machine.
367 debug_line_data.getULEB128(offset_ptr) * Prologue.MinInstLength;
370 case DW_LNS_advance_line:
371 // Takes a single signed LEB128 operand and adds that value to
372 // the line register of the state machine.
373 State.Row.Line += debug_line_data.getSLEB128(offset_ptr);
376 case DW_LNS_set_file:
377 // Takes a single unsigned LEB128 operand and stores it in the file
378 // register of the state machine.
379 State.Row.File = debug_line_data.getULEB128(offset_ptr);
382 case DW_LNS_set_column:
383 // Takes a single unsigned LEB128 operand and stores it in the
384 // column register of the state machine.
385 State.Row.Column = debug_line_data.getULEB128(offset_ptr);
388 case DW_LNS_negate_stmt:
389 // Takes no arguments. Set the is_stmt register of the state
390 // machine to the logical negation of its current value.
391 State.Row.IsStmt = !State.Row.IsStmt;
394 case DW_LNS_set_basic_block:
395 // Takes no arguments. Set the basic_block register of the
396 // state machine to true
397 State.Row.BasicBlock = true;
400 case DW_LNS_const_add_pc:
401 // Takes no arguments. Add to the address register of the state
402 // machine the address increment value corresponding to special
403 // opcode 255. The motivation for DW_LNS_const_add_pc is this:
404 // when the statement program needs to advance the address by a
405 // small amount, it can use a single special opcode, which occupies
406 // a single byte. When it needs to advance the address by up to
407 // twice the range of the last special opcode, it can use
408 // DW_LNS_const_add_pc followed by a special opcode, for a total
409 // of two bytes. Only if it needs to advance the address by more
410 // than twice that range will it need to use both DW_LNS_advance_pc
411 // and a special opcode, requiring three or more bytes.
413 uint8_t adjust_opcode = 255 - Prologue.OpcodeBase;
414 uint64_t addr_offset =
415 (adjust_opcode / Prologue.LineRange) * Prologue.MinInstLength;
416 State.Row.Address += addr_offset;
420 case DW_LNS_fixed_advance_pc:
421 // Takes a single uhalf operand. Add to the address register of
422 // the state machine the value of the (unencoded) operand. This
423 // is the only extended opcode that takes an argument that is not
424 // a variable length number. The motivation for DW_LNS_fixed_advance_pc
425 // is this: existing assemblers cannot emit DW_LNS_advance_pc or
426 // special opcodes because they cannot encode LEB128 numbers or
427 // judge when the computation of a special opcode overflows and
428 // requires the use of DW_LNS_advance_pc. Such assemblers, however,
429 // can use DW_LNS_fixed_advance_pc instead, sacrificing compression.
430 State.Row.Address += debug_line_data.getU16(offset_ptr);
433 case DW_LNS_set_prologue_end:
434 // Takes no arguments. Set the prologue_end register of the
435 // state machine to true
436 State.Row.PrologueEnd = true;
439 case DW_LNS_set_epilogue_begin:
440 // Takes no arguments. Set the basic_block register of the
441 // state machine to true
442 State.Row.EpilogueBegin = true;
446 // Takes a single unsigned LEB128 operand and stores it in the
447 // column register of the state machine.
448 State.Row.Isa = debug_line_data.getULEB128(offset_ptr);
452 // Handle any unknown standard opcodes here. We know the lengths
453 // of such opcodes because they are specified in the prologue
454 // as a multiple of LEB128 operands for each opcode.
456 assert(opcode - 1U < Prologue.StandardOpcodeLengths.size());
457 uint8_t opcode_length = Prologue.StandardOpcodeLengths[opcode - 1];
458 for (uint8_t i = 0; i < opcode_length; ++i)
459 debug_line_data.getULEB128(offset_ptr);
466 // A special opcode value is chosen based on the amount that needs
467 // to be added to the line and address registers. The maximum line
468 // increment for a special opcode is the value of the line_base
469 // field in the header, plus the value of the line_range field,
470 // minus 1 (line base + line range - 1). If the desired line
471 // increment is greater than the maximum line increment, a standard
472 // opcode must be used instead of a special opcode. The "address
473 // advance" is calculated by dividing the desired address increment
474 // by the minimum_instruction_length field from the header. The
475 // special opcode is then calculated using the following formula:
477 // opcode = (desired line increment - line_base) +
478 // (line_range * address advance) + opcode_base
480 // If the resulting opcode is greater than 255, a standard opcode
481 // must be used instead.
483 // To decode a special opcode, subtract the opcode_base from the
484 // opcode itself to give the adjusted opcode. The amount to
485 // increment the address register is the result of the adjusted
486 // opcode divided by the line_range multiplied by the
487 // minimum_instruction_length field from the header. That is:
489 // address increment = (adjusted opcode / line_range) *
490 // minimum_instruction_length
492 // The amount to increment the line register is the line_base plus
493 // the result of the adjusted opcode modulo the line_range. That is:
495 // line increment = line_base + (adjusted opcode % line_range)
497 uint8_t adjust_opcode = opcode - Prologue.OpcodeBase;
498 uint64_t addr_offset =
499 (adjust_opcode / Prologue.LineRange) * Prologue.MinInstLength;
500 int32_t line_offset =
501 Prologue.LineBase + (adjust_opcode % Prologue.LineRange);
502 State.Row.Line += line_offset;
503 State.Row.Address += addr_offset;
504 State.appendRowToMatrix(*offset_ptr);
505 // Reset discriminator to 0.
506 State.Row.Discriminator = 0;
510 if (!State.Sequence.Empty) {
511 fprintf(stderr, "warning: last sequence in debug line table is not"
515 // Sort all sequences so that address lookup will work faster.
516 if (!Sequences.empty()) {
517 std::sort(Sequences.begin(), Sequences.end(), Sequence::orderByLowPC);
518 // Note: actually, instruction address ranges of sequences should not
519 // overlap (in shared objects and executables). If they do, the address
520 // lookup would still work, though, but result would be ambiguous.
521 // We don't report warning in this case. For example,
522 // sometimes .so compiled from multiple object files contains a few
523 // rudimentary sequences for address ranges [0x0, 0xsomething).
530 DWARFDebugLine::LineTable::findRowInSeq(const DWARFDebugLine::Sequence &seq,
531 uint64_t address) const {
532 if (!seq.containsPC(address))
533 return UnknownRowIndex;
534 // Search for instruction address in the rows describing the sequence.
535 // Rows are stored in a vector, so we may use arithmetical operations with
537 DWARFDebugLine::Row row;
538 row.Address = address;
539 RowIter first_row = Rows.begin() + seq.FirstRowIndex;
540 RowIter last_row = Rows.begin() + seq.LastRowIndex;
541 LineTable::RowIter row_pos = std::lower_bound(
542 first_row, last_row, row, DWARFDebugLine::Row::orderByAddress);
543 if (row_pos == last_row) {
544 return seq.LastRowIndex - 1;
546 uint32_t index = seq.FirstRowIndex + (row_pos - first_row);
547 if (row_pos->Address > address) {
548 if (row_pos == first_row)
549 return UnknownRowIndex;
556 uint32_t DWARFDebugLine::LineTable::lookupAddress(uint64_t address) const {
557 if (Sequences.empty())
558 return UnknownRowIndex;
559 // First, find an instruction sequence containing the given address.
560 DWARFDebugLine::Sequence sequence;
561 sequence.LowPC = address;
562 SequenceIter first_seq = Sequences.begin();
563 SequenceIter last_seq = Sequences.end();
564 SequenceIter seq_pos = std::lower_bound(
565 first_seq, last_seq, sequence, DWARFDebugLine::Sequence::orderByLowPC);
566 DWARFDebugLine::Sequence found_seq;
567 if (seq_pos == last_seq) {
568 found_seq = Sequences.back();
569 } else if (seq_pos->LowPC == address) {
570 found_seq = *seq_pos;
572 if (seq_pos == first_seq)
573 return UnknownRowIndex;
574 found_seq = *(seq_pos - 1);
576 return findRowInSeq(found_seq, address);
579 bool DWARFDebugLine::LineTable::lookupAddressRange(
580 uint64_t address, uint64_t size, std::vector<uint32_t> &result) const {
581 if (Sequences.empty())
583 uint64_t end_addr = address + size;
584 // First, find an instruction sequence containing the given address.
585 DWARFDebugLine::Sequence sequence;
586 sequence.LowPC = address;
587 SequenceIter first_seq = Sequences.begin();
588 SequenceIter last_seq = Sequences.end();
589 SequenceIter seq_pos = std::lower_bound(
590 first_seq, last_seq, sequence, DWARFDebugLine::Sequence::orderByLowPC);
591 if (seq_pos == last_seq || seq_pos->LowPC != address) {
592 if (seq_pos == first_seq)
596 if (!seq_pos->containsPC(address))
599 SequenceIter start_pos = seq_pos;
601 // Add the rows from the first sequence to the vector, starting with the
602 // index we just calculated
604 while (seq_pos != last_seq && seq_pos->LowPC < end_addr) {
605 const DWARFDebugLine::Sequence &cur_seq = *seq_pos;
606 // For the first sequence, we need to find which row in the sequence is the
607 // first in our range.
608 uint32_t first_row_index = cur_seq.FirstRowIndex;
609 if (seq_pos == start_pos)
610 first_row_index = findRowInSeq(cur_seq, address);
612 // Figure out the last row in the range.
613 uint32_t last_row_index = findRowInSeq(cur_seq, end_addr - 1);
614 if (last_row_index == UnknownRowIndex)
615 last_row_index = cur_seq.LastRowIndex - 1;
617 assert(first_row_index != UnknownRowIndex);
618 assert(last_row_index != UnknownRowIndex);
620 for (uint32_t i = first_row_index; i <= last_row_index; ++i) {
631 DWARFDebugLine::LineTable::hasFileAtIndex(uint64_t FileIndex) const {
632 return FileIndex != 0 && FileIndex <= Prologue.FileNames.size();
636 DWARFDebugLine::LineTable::getFileNameByIndex(uint64_t FileIndex,
638 FileLineInfoKind Kind,
639 std::string &Result) const {
640 if (Kind == FileLineInfoKind::None || !hasFileAtIndex(FileIndex))
642 const FileNameEntry &Entry = Prologue.FileNames[FileIndex - 1];
643 const char *FileName = Entry.Name;
644 if (Kind != FileLineInfoKind::AbsoluteFilePath ||
645 sys::path::is_absolute(FileName)) {
650 SmallString<16> FilePath;
651 uint64_t IncludeDirIndex = Entry.DirIdx;
652 const char *IncludeDir = "";
653 // Be defensive about the contents of Entry.
654 if (IncludeDirIndex > 0 &&
655 IncludeDirIndex <= Prologue.IncludeDirectories.size())
656 IncludeDir = Prologue.IncludeDirectories[IncludeDirIndex - 1];
658 // We may still need to append compilation directory of compile unit.
659 // We know that FileName is not absolute, the only way to have an
660 // absolute path at this point would be if IncludeDir is absolute.
661 if (CompDir && Kind == FileLineInfoKind::AbsoluteFilePath &&
662 sys::path::is_relative(IncludeDir))
663 sys::path::append(FilePath, CompDir);
665 // sys::path::append skips empty strings.
666 sys::path::append(FilePath, IncludeDir, FileName);
667 Result = FilePath.str();
671 bool DWARFDebugLine::LineTable::getFileLineInfoForAddress(
672 uint64_t Address, const char *CompDir, FileLineInfoKind Kind,
673 DILineInfo &Result) const {
674 // Get the index of row we're looking for in the line table.
675 uint32_t RowIndex = lookupAddress(Address);
678 // Take file number and line/column from the row.
679 const auto &Row = Rows[RowIndex];
680 if (!getFileNameByIndex(Row.File, CompDir, Kind, Result.FileName))
682 Result.Line = Row.Line;
683 Result.Column = Row.Column;
684 Result.Discriminator = Row.Discriminator;