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 "DWARFDebugLine.h"
11 #include "llvm/Support/Dwarf.h"
12 #include "llvm/Support/Format.h"
13 #include "llvm/Support/Path.h"
14 #include "llvm/Support/raw_ostream.h"
17 using namespace dwarf;
19 DWARFDebugLine::Prologue::Prologue() {
23 void DWARFDebugLine::Prologue::clear() {
24 TotalLength = Version = PrologueLength = 0;
25 MinInstLength = MaxOpsPerInst = DefaultIsStmt = LineBase = LineRange = 0;
27 StandardOpcodeLengths.clear();
28 IncludeDirectories.clear();
32 void DWARFDebugLine::Prologue::dump(raw_ostream &OS) const {
33 OS << "Line table prologue:\n"
34 << format(" total_length: 0x%8.8x\n", TotalLength)
35 << format(" version: %u\n", Version)
36 << format(" prologue_length: 0x%8.8x\n", PrologueLength)
37 << format(" min_inst_length: %u\n", MinInstLength)
38 << format(Version >= 4 ? "max_ops_per_inst: %u\n" : "", MaxOpsPerInst)
39 << format(" default_is_stmt: %u\n", DefaultIsStmt)
40 << format(" line_base: %i\n", LineBase)
41 << format(" line_range: %u\n", LineRange)
42 << format(" opcode_base: %u\n", OpcodeBase);
44 for (uint32_t i = 0; i < StandardOpcodeLengths.size(); ++i)
45 OS << format("standard_opcode_lengths[%s] = %u\n", LNStandardString(i+1),
46 StandardOpcodeLengths[i]);
48 if (!IncludeDirectories.empty())
49 for (uint32_t i = 0; i < IncludeDirectories.size(); ++i)
50 OS << format("include_directories[%3u] = '", i+1)
51 << IncludeDirectories[i] << "'\n";
53 if (!FileNames.empty()) {
54 OS << " Dir Mod Time File Len File Name\n"
55 << " ---- ---------- ---------- -----------"
57 for (uint32_t i = 0; i < FileNames.size(); ++i) {
58 const FileNameEntry& fileEntry = FileNames[i];
59 OS << format("file_names[%3u] %4" PRIu64 " ", i+1, fileEntry.DirIdx)
60 << format("0x%8.8" PRIx64 " 0x%8.8" PRIx64 " ",
61 fileEntry.ModTime, fileEntry.Length)
62 << fileEntry.Name << '\n';
67 bool DWARFDebugLine::Prologue::parse(DataExtractor debug_line_data,
68 uint32_t *offset_ptr) {
69 const uint32_t prologue_offset = *offset_ptr;
72 TotalLength = debug_line_data.getU32(offset_ptr);
73 Version = debug_line_data.getU16(offset_ptr);
77 PrologueLength = debug_line_data.getU32(offset_ptr);
78 const uint32_t end_prologue_offset = PrologueLength + *offset_ptr;
79 MinInstLength = debug_line_data.getU8(offset_ptr);
81 MaxOpsPerInst = debug_line_data.getU8(offset_ptr);
82 DefaultIsStmt = debug_line_data.getU8(offset_ptr);
83 LineBase = debug_line_data.getU8(offset_ptr);
84 LineRange = debug_line_data.getU8(offset_ptr);
85 OpcodeBase = debug_line_data.getU8(offset_ptr);
87 StandardOpcodeLengths.reserve(OpcodeBase - 1);
88 for (uint32_t i = 1; i < OpcodeBase; ++i) {
89 uint8_t op_len = debug_line_data.getU8(offset_ptr);
90 StandardOpcodeLengths.push_back(op_len);
93 while (*offset_ptr < end_prologue_offset) {
94 const char *s = debug_line_data.getCStr(offset_ptr);
96 IncludeDirectories.push_back(s);
101 while (*offset_ptr < end_prologue_offset) {
102 const char *name = debug_line_data.getCStr(offset_ptr);
103 if (name && name[0]) {
104 FileNameEntry fileEntry;
105 fileEntry.Name = name;
106 fileEntry.DirIdx = debug_line_data.getULEB128(offset_ptr);
107 fileEntry.ModTime = debug_line_data.getULEB128(offset_ptr);
108 fileEntry.Length = debug_line_data.getULEB128(offset_ptr);
109 FileNames.push_back(fileEntry);
115 if (*offset_ptr != end_prologue_offset) {
116 fprintf(stderr, "warning: parsing line table prologue at 0x%8.8x should"
117 " have ended at 0x%8.8x but it ended at 0x%8.8x\n",
118 prologue_offset, end_prologue_offset, *offset_ptr);
124 DWARFDebugLine::Row::Row(bool default_is_stmt) {
125 reset(default_is_stmt);
128 void DWARFDebugLine::Row::postAppend() {
131 EpilogueBegin = false;
134 void DWARFDebugLine::Row::reset(bool default_is_stmt) {
141 IsStmt = default_is_stmt;
145 EpilogueBegin = false;
148 void DWARFDebugLine::Row::dump(raw_ostream &OS) const {
149 OS << format("0x%16.16" PRIx64 " %6u %6u", Address, Line, Column)
150 << format(" %6u %3u %13u ", File, Isa, Discriminator)
151 << (IsStmt ? " is_stmt" : "")
152 << (BasicBlock ? " basic_block" : "")
153 << (PrologueEnd ? " prologue_end" : "")
154 << (EpilogueBegin ? " epilogue_begin" : "")
155 << (EndSequence ? " end_sequence" : "")
159 DWARFDebugLine::Sequence::Sequence() {
163 void DWARFDebugLine::Sequence::reset() {
171 DWARFDebugLine::LineTable::LineTable() {
175 void DWARFDebugLine::LineTable::dump(raw_ostream &OS) const {
180 OS << "Address Line Column File ISA Discriminator Flags\n"
181 << "------------------ ------ ------ ------ --- ------------- "
183 for (const Row &R : Rows) {
189 void DWARFDebugLine::LineTable::clear() {
195 DWARFDebugLine::ParsingState::ParsingState(struct LineTable *LT)
196 : LineTable(LT), RowNumber(0) {
197 resetRowAndSequence();
200 void DWARFDebugLine::ParsingState::resetRowAndSequence() {
201 Row.reset(LineTable->Prologue.DefaultIsStmt);
205 void DWARFDebugLine::ParsingState::appendRowToMatrix(uint32_t offset) {
206 if (Sequence.Empty) {
207 // Record the beginning of instruction sequence.
208 Sequence.Empty = false;
209 Sequence.LowPC = Row.Address;
210 Sequence.FirstRowIndex = RowNumber;
213 LineTable->appendRow(Row);
214 if (Row.EndSequence) {
215 // Record the end of instruction sequence.
216 Sequence.HighPC = Row.Address;
217 Sequence.LastRowIndex = RowNumber;
218 if (Sequence.isValid())
219 LineTable->appendSequence(Sequence);
225 const DWARFDebugLine::LineTable *
226 DWARFDebugLine::getLineTable(uint32_t offset) const {
227 LineTableConstIter pos = LineTableMap.find(offset);
228 if (pos != LineTableMap.end())
233 const DWARFDebugLine::LineTable *
234 DWARFDebugLine::getOrParseLineTable(DataExtractor debug_line_data,
236 std::pair<LineTableIter, bool> pos =
237 LineTableMap.insert(LineTableMapTy::value_type(offset, LineTable()));
238 LineTable *LT = &pos.first->second;
240 if (!LT->parse(debug_line_data, RelocMap, &offset))
246 bool DWARFDebugLine::LineTable::parse(DataExtractor debug_line_data,
247 const RelocAddrMap *RMap,
248 uint32_t *offset_ptr) {
249 const uint32_t debug_line_offset = *offset_ptr;
253 if (!Prologue.parse(debug_line_data, offset_ptr)) {
254 // Restore our offset and return false to indicate failure!
255 *offset_ptr = debug_line_offset;
259 const uint32_t end_offset = debug_line_offset + Prologue.TotalLength +
260 sizeof(Prologue.TotalLength);
262 ParsingState State(this);
264 while (*offset_ptr < end_offset) {
265 uint8_t opcode = debug_line_data.getU8(offset_ptr);
268 // Extended Opcodes always start with a zero opcode followed by
269 // a uleb128 length so you can skip ones you don't know about
270 uint32_t ext_offset = *offset_ptr;
271 uint64_t len = debug_line_data.getULEB128(offset_ptr);
272 uint32_t arg_size = len - (*offset_ptr - ext_offset);
274 uint8_t sub_opcode = debug_line_data.getU8(offset_ptr);
275 switch (sub_opcode) {
276 case DW_LNE_end_sequence:
277 // Set the end_sequence register of the state machine to true and
278 // append a row to the matrix using the current values of the
279 // state-machine registers. Then reset the registers to the initial
280 // values specified above. Every statement program sequence must end
281 // with a DW_LNE_end_sequence instruction which creates a row whose
282 // address is that of the byte after the last target machine instruction
284 State.Row.EndSequence = true;
285 State.appendRowToMatrix(*offset_ptr);
286 State.resetRowAndSequence();
289 case DW_LNE_set_address:
290 // Takes a single relocatable address as an operand. The size of the
291 // operand is the size appropriate to hold an address on the target
292 // machine. Set the address register to the value given by the
293 // relocatable address. All of the other statement program opcodes
294 // that affect the address register add a delta to it. This instruction
295 // stores a relocatable value into it instead.
297 // If this address is in our relocation map, apply the relocation.
298 RelocAddrMap::const_iterator AI = RMap->find(*offset_ptr);
299 if (AI != RMap->end()) {
300 const std::pair<uint8_t, int64_t> &R = AI->second;
302 debug_line_data.getAddress(offset_ptr) + R.second;
304 State.Row.Address = debug_line_data.getAddress(offset_ptr);
308 case DW_LNE_define_file:
309 // Takes 4 arguments. The first is a null terminated string containing
310 // a source file name. The second is an unsigned LEB128 number
311 // representing the directory index of the directory in which the file
312 // was found. The third is an unsigned LEB128 number representing the
313 // time of last modification of the file. The fourth is an unsigned
314 // LEB128 number representing the length in bytes of the file. The time
315 // and length fields may contain LEB128(0) if the information is not
318 // The directory index represents an entry in the include_directories
319 // section of the statement program prologue. The index is LEB128(0)
320 // if the file was found in the current directory of the compilation,
321 // LEB128(1) if it was found in the first directory in the
322 // include_directories section, and so on. The directory index is
323 // ignored for file names that represent full path names.
325 // The files are numbered, starting at 1, in the order in which they
326 // appear; the names in the prologue come before names defined by
327 // the DW_LNE_define_file instruction. These numbers are used in the
328 // the file register of the state machine.
330 FileNameEntry fileEntry;
331 fileEntry.Name = debug_line_data.getCStr(offset_ptr);
332 fileEntry.DirIdx = debug_line_data.getULEB128(offset_ptr);
333 fileEntry.ModTime = debug_line_data.getULEB128(offset_ptr);
334 fileEntry.Length = debug_line_data.getULEB128(offset_ptr);
335 Prologue.FileNames.push_back(fileEntry);
339 case DW_LNE_set_discriminator:
340 State.Row.Discriminator = debug_line_data.getULEB128(offset_ptr);
344 // Length doesn't include the zero opcode byte or the length itself, but
345 // it does include the sub_opcode, so we have to adjust for that below
346 (*offset_ptr) += arg_size;
349 } else if (opcode < Prologue.OpcodeBase) {
353 // Takes no arguments. Append a row to the matrix using the
354 // current values of the state-machine registers. Then set
355 // the basic_block register to false.
356 State.appendRowToMatrix(*offset_ptr);
359 case DW_LNS_advance_pc:
360 // Takes a single unsigned LEB128 operand, multiplies it by the
361 // min_inst_length field of the prologue, and adds the
362 // result to the address register of the state machine.
364 debug_line_data.getULEB128(offset_ptr) * Prologue.MinInstLength;
367 case DW_LNS_advance_line:
368 // Takes a single signed LEB128 operand and adds that value to
369 // the line register of the state machine.
370 State.Row.Line += debug_line_data.getSLEB128(offset_ptr);
373 case DW_LNS_set_file:
374 // Takes a single unsigned LEB128 operand and stores it in the file
375 // register of the state machine.
376 State.Row.File = debug_line_data.getULEB128(offset_ptr);
379 case DW_LNS_set_column:
380 // Takes a single unsigned LEB128 operand and stores it in the
381 // column register of the state machine.
382 State.Row.Column = debug_line_data.getULEB128(offset_ptr);
385 case DW_LNS_negate_stmt:
386 // Takes no arguments. Set the is_stmt register of the state
387 // machine to the logical negation of its current value.
388 State.Row.IsStmt = !State.Row.IsStmt;
391 case DW_LNS_set_basic_block:
392 // Takes no arguments. Set the basic_block register of the
393 // state machine to true
394 State.Row.BasicBlock = true;
397 case DW_LNS_const_add_pc:
398 // Takes no arguments. Add to the address register of the state
399 // machine the address increment value corresponding to special
400 // opcode 255. The motivation for DW_LNS_const_add_pc is this:
401 // when the statement program needs to advance the address by a
402 // small amount, it can use a single special opcode, which occupies
403 // a single byte. When it needs to advance the address by up to
404 // twice the range of the last special opcode, it can use
405 // DW_LNS_const_add_pc followed by a special opcode, for a total
406 // of two bytes. Only if it needs to advance the address by more
407 // than twice that range will it need to use both DW_LNS_advance_pc
408 // and a special opcode, requiring three or more bytes.
410 uint8_t adjust_opcode = 255 - Prologue.OpcodeBase;
411 uint64_t addr_offset =
412 (adjust_opcode / Prologue.LineRange) * Prologue.MinInstLength;
413 State.Row.Address += addr_offset;
417 case DW_LNS_fixed_advance_pc:
418 // Takes a single uhalf operand. Add to the address register of
419 // the state machine the value of the (unencoded) operand. This
420 // is the only extended opcode that takes an argument that is not
421 // a variable length number. The motivation for DW_LNS_fixed_advance_pc
422 // is this: existing assemblers cannot emit DW_LNS_advance_pc or
423 // special opcodes because they cannot encode LEB128 numbers or
424 // judge when the computation of a special opcode overflows and
425 // requires the use of DW_LNS_advance_pc. Such assemblers, however,
426 // can use DW_LNS_fixed_advance_pc instead, sacrificing compression.
427 State.Row.Address += debug_line_data.getU16(offset_ptr);
430 case DW_LNS_set_prologue_end:
431 // Takes no arguments. Set the prologue_end register of the
432 // state machine to true
433 State.Row.PrologueEnd = true;
436 case DW_LNS_set_epilogue_begin:
437 // Takes no arguments. Set the basic_block register of the
438 // state machine to true
439 State.Row.EpilogueBegin = true;
443 // Takes a single unsigned LEB128 operand and stores it in the
444 // column register of the state machine.
445 State.Row.Isa = debug_line_data.getULEB128(offset_ptr);
449 // Handle any unknown standard opcodes here. We know the lengths
450 // of such opcodes because they are specified in the prologue
451 // as a multiple of LEB128 operands for each opcode.
453 assert(opcode - 1U < Prologue.StandardOpcodeLengths.size());
454 uint8_t opcode_length = Prologue.StandardOpcodeLengths[opcode - 1];
455 for (uint8_t i = 0; i < opcode_length; ++i)
456 debug_line_data.getULEB128(offset_ptr);
463 // A special opcode value is chosen based on the amount that needs
464 // to be added to the line and address registers. The maximum line
465 // increment for a special opcode is the value of the line_base
466 // field in the header, plus the value of the line_range field,
467 // minus 1 (line base + line range - 1). If the desired line
468 // increment is greater than the maximum line increment, a standard
469 // opcode must be used instead of a special opcode. The "address
470 // advance" is calculated by dividing the desired address increment
471 // by the minimum_instruction_length field from the header. The
472 // special opcode is then calculated using the following formula:
474 // opcode = (desired line increment - line_base) +
475 // (line_range * address advance) + opcode_base
477 // If the resulting opcode is greater than 255, a standard opcode
478 // must be used instead.
480 // To decode a special opcode, subtract the opcode_base from the
481 // opcode itself to give the adjusted opcode. The amount to
482 // increment the address register is the result of the adjusted
483 // opcode divided by the line_range multiplied by the
484 // minimum_instruction_length field from the header. That is:
486 // address increment = (adjusted opcode / line_range) *
487 // minimum_instruction_length
489 // The amount to increment the line register is the line_base plus
490 // the result of the adjusted opcode modulo the line_range. That is:
492 // line increment = line_base + (adjusted opcode % line_range)
494 uint8_t adjust_opcode = opcode - Prologue.OpcodeBase;
495 uint64_t addr_offset =
496 (adjust_opcode / Prologue.LineRange) * Prologue.MinInstLength;
497 int32_t line_offset =
498 Prologue.LineBase + (adjust_opcode % Prologue.LineRange);
499 State.Row.Line += line_offset;
500 State.Row.Address += addr_offset;
501 State.appendRowToMatrix(*offset_ptr);
505 if (!State.Sequence.Empty) {
506 fprintf(stderr, "warning: last sequence in debug line table is not"
510 // Sort all sequences so that address lookup will work faster.
511 if (!Sequences.empty()) {
512 std::sort(Sequences.begin(), Sequences.end(), Sequence::orderByLowPC);
513 // Note: actually, instruction address ranges of sequences should not
514 // overlap (in shared objects and executables). If they do, the address
515 // lookup would still work, though, but result would be ambiguous.
516 // We don't report warning in this case. For example,
517 // sometimes .so compiled from multiple object files contains a few
518 // rudimentary sequences for address ranges [0x0, 0xsomething).
524 uint32_t DWARFDebugLine::LineTable::lookupAddress(uint64_t address) const {
525 uint32_t unknown_index = UINT32_MAX;
526 if (Sequences.empty())
527 return unknown_index;
528 // First, find an instruction sequence containing the given address.
529 DWARFDebugLine::Sequence sequence;
530 sequence.LowPC = address;
531 SequenceIter first_seq = Sequences.begin();
532 SequenceIter last_seq = Sequences.end();
533 SequenceIter seq_pos = std::lower_bound(first_seq, last_seq, sequence,
534 DWARFDebugLine::Sequence::orderByLowPC);
535 DWARFDebugLine::Sequence found_seq;
536 if (seq_pos == last_seq) {
537 found_seq = Sequences.back();
538 } else if (seq_pos->LowPC == address) {
539 found_seq = *seq_pos;
541 if (seq_pos == first_seq)
542 return unknown_index;
543 found_seq = *(seq_pos - 1);
545 if (!found_seq.containsPC(address))
546 return unknown_index;
547 // Search for instruction address in the rows describing the sequence.
548 // Rows are stored in a vector, so we may use arithmetical operations with
550 DWARFDebugLine::Row row;
551 row.Address = address;
552 RowIter first_row = Rows.begin() + found_seq.FirstRowIndex;
553 RowIter last_row = Rows.begin() + found_seq.LastRowIndex;
554 RowIter row_pos = std::lower_bound(first_row, last_row, row,
555 DWARFDebugLine::Row::orderByAddress);
556 if (row_pos == last_row) {
557 return found_seq.LastRowIndex - 1;
559 uint32_t index = found_seq.FirstRowIndex + (row_pos - first_row);
560 if (row_pos->Address > address) {
561 if (row_pos == first_row)
562 return unknown_index;
569 bool DWARFDebugLine::LineTable::lookupAddressRange(
570 uint64_t address, uint64_t size, std::vector<uint32_t> &result) const {
571 if (Sequences.empty())
573 uint64_t end_addr = address + size;
574 // First, find an instruction sequence containing the given address.
575 DWARFDebugLine::Sequence sequence;
576 sequence.LowPC = address;
577 SequenceIter first_seq = Sequences.begin();
578 SequenceIter last_seq = Sequences.end();
579 SequenceIter seq_pos = std::lower_bound(first_seq, last_seq, sequence,
580 DWARFDebugLine::Sequence::orderByLowPC);
581 if (seq_pos == last_seq || seq_pos->LowPC != address) {
582 if (seq_pos == first_seq)
586 if (!seq_pos->containsPC(address))
589 SequenceIter start_pos = seq_pos;
591 // Add the rows from the first sequence to the vector, starting with the
592 // index we just calculated
594 while (seq_pos != last_seq && seq_pos->LowPC < end_addr) {
595 DWARFDebugLine::Sequence cur_seq = *seq_pos;
596 uint32_t first_row_index;
597 uint32_t last_row_index;
598 if (seq_pos == start_pos) {
599 // For the first sequence, we need to find which row in the sequence is the
600 // first in our range. Rows are stored in a vector, so we may use
601 // arithmetical operations with iterators.
602 DWARFDebugLine::Row row;
603 row.Address = address;
604 RowIter first_row = Rows.begin() + cur_seq.FirstRowIndex;
605 RowIter last_row = Rows.begin() + cur_seq.LastRowIndex;
606 RowIter row_pos = std::upper_bound(first_row, last_row, row,
607 DWARFDebugLine::Row::orderByAddress);
608 // The 'row_pos' iterator references the first row that is greater than
609 // our start address. Unless that's the first row, we want to start at
610 // the row before that.
611 first_row_index = cur_seq.FirstRowIndex + (row_pos - first_row);
612 if (row_pos != first_row)
615 first_row_index = cur_seq.FirstRowIndex;
617 // For the last sequence in our range, we need to figure out the last row in
618 // range. For all other sequences we can go to the end of the sequence.
619 if (cur_seq.HighPC > end_addr) {
620 DWARFDebugLine::Row row;
621 row.Address = end_addr;
622 RowIter first_row = Rows.begin() + cur_seq.FirstRowIndex;
623 RowIter last_row = Rows.begin() + cur_seq.LastRowIndex;
624 RowIter row_pos = std::upper_bound(first_row, last_row, row,
625 DWARFDebugLine::Row::orderByAddress);
626 // The 'row_pos' iterator references the first row that is greater than
627 // our end address. The row before that is the last row we want.
628 last_row_index = cur_seq.FirstRowIndex + (row_pos - first_row) - 1;
630 // Contrary to what you might expect, DWARFDebugLine::SequenceLastRowIndex
631 // isn't a valid index within the current sequence. It's that plus one.
632 last_row_index = cur_seq.LastRowIndex - 1;
634 for (uint32_t i = first_row_index; i <= last_row_index; ++i) {
645 DWARFDebugLine::LineTable::getFileNameByIndex(uint64_t FileIndex,
646 bool NeedsAbsoluteFilePath,
647 std::string &Result) const {
648 if (FileIndex == 0 || FileIndex > Prologue.FileNames.size())
650 const FileNameEntry &Entry = Prologue.FileNames[FileIndex - 1];
651 const char *FileName = Entry.Name;
652 if (!NeedsAbsoluteFilePath ||
653 sys::path::is_absolute(FileName)) {
657 SmallString<16> FilePath;
658 uint64_t IncludeDirIndex = Entry.DirIdx;
659 // Be defensive about the contents of Entry.
660 if (IncludeDirIndex > 0 &&
661 IncludeDirIndex <= Prologue.IncludeDirectories.size()) {
662 const char *IncludeDir = Prologue.IncludeDirectories[IncludeDirIndex - 1];
663 sys::path::append(FilePath, IncludeDir);
665 sys::path::append(FilePath, FileName);
666 Result = FilePath.str();