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 void DWARFDebugLine::Prologue::dump(raw_ostream &OS) const {
20 OS << "Line table prologue:\n"
21 << format(" total_length: 0x%8.8x\n", TotalLength)
22 << format(" version: %u\n", Version)
23 << format(" prologue_length: 0x%8.8x\n", PrologueLength)
24 << format(" min_inst_length: %u\n", MinInstLength)
25 << format(Version >= 4 ? "max_ops_per_inst: %u\n" : "", MaxOpsPerInst)
26 << format(" default_is_stmt: %u\n", DefaultIsStmt)
27 << format(" line_base: %i\n", LineBase)
28 << format(" line_range: %u\n", LineRange)
29 << format(" opcode_base: %u\n", OpcodeBase);
31 for (uint32_t i = 0; i < StandardOpcodeLengths.size(); ++i)
32 OS << format("standard_opcode_lengths[%s] = %u\n", LNStandardString(i+1),
33 StandardOpcodeLengths[i]);
35 if (!IncludeDirectories.empty())
36 for (uint32_t i = 0; i < IncludeDirectories.size(); ++i)
37 OS << format("include_directories[%3u] = '", i+1)
38 << IncludeDirectories[i] << "'\n";
40 if (!FileNames.empty()) {
41 OS << " Dir Mod Time File Len File Name\n"
42 << " ---- ---------- ---------- -----------"
44 for (uint32_t i = 0; i < FileNames.size(); ++i) {
45 const FileNameEntry& fileEntry = FileNames[i];
46 OS << format("file_names[%3u] %4" PRIu64 " ", i+1, fileEntry.DirIdx)
47 << format("0x%8.8" PRIx64 " 0x%8.8" PRIx64 " ",
48 fileEntry.ModTime, fileEntry.Length)
49 << fileEntry.Name << '\n';
54 void DWARFDebugLine::Row::postAppend() {
57 EpilogueBegin = false;
60 void DWARFDebugLine::Row::reset(bool default_is_stmt) {
67 IsStmt = default_is_stmt;
71 EpilogueBegin = false;
74 void DWARFDebugLine::Row::dump(raw_ostream &OS) const {
75 OS << format("0x%16.16" PRIx64 " %6u %6u", Address, Line, Column)
76 << format(" %6u %3u %13u ", File, Isa, Discriminator)
77 << (IsStmt ? " is_stmt" : "")
78 << (BasicBlock ? " basic_block" : "")
79 << (PrologueEnd ? " prologue_end" : "")
80 << (EpilogueBegin ? " epilogue_begin" : "")
81 << (EndSequence ? " end_sequence" : "")
85 void DWARFDebugLine::LineTable::dump(raw_ostream &OS) const {
90 OS << "Address Line Column File ISA Discriminator Flags\n"
91 << "------------------ ------ ------ ------ --- ------------- "
93 for (const Row &R : Rows) {
99 DWARFDebugLine::State::~State() {}
101 void DWARFDebugLine::State::appendRowToMatrix(uint32_t offset) {
102 if (Sequence::Empty) {
103 // Record the beginning of instruction sequence.
104 Sequence::Empty = false;
105 Sequence::LowPC = Address;
106 Sequence::FirstRowIndex = row;
108 ++row; // Increase the row number.
109 LineTable::appendRow(*this);
111 // Record the end of instruction sequence.
112 Sequence::HighPC = Address;
113 Sequence::LastRowIndex = row;
114 if (Sequence::isValid())
115 LineTable::appendSequence(*this);
121 void DWARFDebugLine::State::finalize() {
122 row = DoneParsingLineTable;
123 if (!Sequence::Empty) {
124 fprintf(stderr, "warning: last sequence in debug line table is not"
127 // Sort all sequences so that address lookup will work faster.
128 if (!Sequences.empty()) {
129 std::sort(Sequences.begin(), Sequences.end(), Sequence::orderByLowPC);
130 // Note: actually, instruction address ranges of sequences should not
131 // overlap (in shared objects and executables). If they do, the address
132 // lookup would still work, though, but result would be ambiguous.
133 // We don't report warning in this case. For example,
134 // sometimes .so compiled from multiple object files contains a few
135 // rudimentary sequences for address ranges [0x0, 0xsomething).
139 DWARFDebugLine::DumpingState::~DumpingState() {}
141 void DWARFDebugLine::DumpingState::finalize() {
145 const DWARFDebugLine::LineTable *
146 DWARFDebugLine::getLineTable(uint32_t offset) const {
147 LineTableConstIter pos = LineTableMap.find(offset);
148 if (pos != LineTableMap.end())
153 const DWARFDebugLine::LineTable *
154 DWARFDebugLine::getOrParseLineTable(DataExtractor debug_line_data,
156 std::pair<LineTableIter, bool> pos =
157 LineTableMap.insert(LineTableMapTy::value_type(offset, LineTable()));
159 // Parse and cache the line table for at this offset.
161 if (!parseStatementTable(debug_line_data, RelocMap, &offset, state))
163 pos.first->second = state;
165 return &pos.first->second;
169 DWARFDebugLine::parsePrologue(DataExtractor debug_line_data,
170 uint32_t *offset_ptr, Prologue *prologue) {
171 const uint32_t prologue_offset = *offset_ptr;
174 prologue->TotalLength = debug_line_data.getU32(offset_ptr);
175 prologue->Version = debug_line_data.getU16(offset_ptr);
176 if (prologue->Version < 2)
179 prologue->PrologueLength = debug_line_data.getU32(offset_ptr);
180 const uint32_t end_prologue_offset = prologue->PrologueLength + *offset_ptr;
181 prologue->MinInstLength = debug_line_data.getU8(offset_ptr);
182 if (prologue->Version >= 4)
183 prologue->MaxOpsPerInst = debug_line_data.getU8(offset_ptr);
184 prologue->DefaultIsStmt = debug_line_data.getU8(offset_ptr);
185 prologue->LineBase = debug_line_data.getU8(offset_ptr);
186 prologue->LineRange = debug_line_data.getU8(offset_ptr);
187 prologue->OpcodeBase = debug_line_data.getU8(offset_ptr);
189 prologue->StandardOpcodeLengths.reserve(prologue->OpcodeBase-1);
190 for (uint32_t i = 1; i < prologue->OpcodeBase; ++i) {
191 uint8_t op_len = debug_line_data.getU8(offset_ptr);
192 prologue->StandardOpcodeLengths.push_back(op_len);
195 while (*offset_ptr < end_prologue_offset) {
196 const char *s = debug_line_data.getCStr(offset_ptr);
198 prologue->IncludeDirectories.push_back(s);
203 while (*offset_ptr < end_prologue_offset) {
204 const char *name = debug_line_data.getCStr(offset_ptr);
205 if (name && name[0]) {
206 FileNameEntry fileEntry;
207 fileEntry.Name = name;
208 fileEntry.DirIdx = debug_line_data.getULEB128(offset_ptr);
209 fileEntry.ModTime = debug_line_data.getULEB128(offset_ptr);
210 fileEntry.Length = debug_line_data.getULEB128(offset_ptr);
211 prologue->FileNames.push_back(fileEntry);
217 if (*offset_ptr != end_prologue_offset) {
218 fprintf(stderr, "warning: parsing line table prologue at 0x%8.8x should"
219 " have ended at 0x%8.8x but it ended at 0x%8.8x\n",
220 prologue_offset, end_prologue_offset, *offset_ptr);
226 bool DWARFDebugLine::parseStatementTable(DataExtractor debug_line_data,
227 const RelocAddrMap *RMap,
228 uint32_t *offset_ptr, State &state) {
229 const uint32_t debug_line_offset = *offset_ptr;
231 Prologue *prologue = &state.Prologue;
233 if (!parsePrologue(debug_line_data, offset_ptr, prologue)) {
234 // Restore our offset and return false to indicate failure!
235 *offset_ptr = debug_line_offset;
239 const uint32_t end_offset = debug_line_offset + prologue->TotalLength +
240 sizeof(prologue->TotalLength);
244 while (*offset_ptr < end_offset) {
245 uint8_t opcode = debug_line_data.getU8(offset_ptr);
248 // Extended Opcodes always start with a zero opcode followed by
249 // a uleb128 length so you can skip ones you don't know about
250 uint32_t ext_offset = *offset_ptr;
251 uint64_t len = debug_line_data.getULEB128(offset_ptr);
252 uint32_t arg_size = len - (*offset_ptr - ext_offset);
254 uint8_t sub_opcode = debug_line_data.getU8(offset_ptr);
255 switch (sub_opcode) {
256 case DW_LNE_end_sequence:
257 // Set the end_sequence register of the state machine to true and
258 // append a row to the matrix using the current values of the
259 // state-machine registers. Then reset the registers to the initial
260 // values specified above. Every statement program sequence must end
261 // with a DW_LNE_end_sequence instruction which creates a row whose
262 // address is that of the byte after the last target machine instruction
264 state.EndSequence = true;
265 state.appendRowToMatrix(*offset_ptr);
269 case DW_LNE_set_address:
270 // Takes a single relocatable address as an operand. The size of the
271 // operand is the size appropriate to hold an address on the target
272 // machine. Set the address register to the value given by the
273 // relocatable address. All of the other statement program opcodes
274 // that affect the address register add a delta to it. This instruction
275 // stores a relocatable value into it instead.
277 // If this address is in our relocation map, apply the relocation.
278 RelocAddrMap::const_iterator AI = RMap->find(*offset_ptr);
279 if (AI != RMap->end()) {
280 const std::pair<uint8_t, int64_t> &R = AI->second;
281 state.Address = debug_line_data.getAddress(offset_ptr) + R.second;
283 state.Address = debug_line_data.getAddress(offset_ptr);
287 case DW_LNE_define_file:
288 // Takes 4 arguments. The first is a null terminated string containing
289 // a source file name. The second is an unsigned LEB128 number
290 // representing the directory index of the directory in which the file
291 // was found. The third is an unsigned LEB128 number representing the
292 // time of last modification of the file. The fourth is an unsigned
293 // LEB128 number representing the length in bytes of the file. The time
294 // and length fields may contain LEB128(0) if the information is not
297 // The directory index represents an entry in the include_directories
298 // section of the statement program prologue. The index is LEB128(0)
299 // if the file was found in the current directory of the compilation,
300 // LEB128(1) if it was found in the first directory in the
301 // include_directories section, and so on. The directory index is
302 // ignored for file names that represent full path names.
304 // The files are numbered, starting at 1, in the order in which they
305 // appear; the names in the prologue come before names defined by
306 // the DW_LNE_define_file instruction. These numbers are used in the
307 // the file register of the state machine.
309 FileNameEntry fileEntry;
310 fileEntry.Name = debug_line_data.getCStr(offset_ptr);
311 fileEntry.DirIdx = debug_line_data.getULEB128(offset_ptr);
312 fileEntry.ModTime = debug_line_data.getULEB128(offset_ptr);
313 fileEntry.Length = debug_line_data.getULEB128(offset_ptr);
314 prologue->FileNames.push_back(fileEntry);
318 case DW_LNE_set_discriminator:
319 state.Discriminator = debug_line_data.getULEB128(offset_ptr);
323 // Length doesn't include the zero opcode byte or the length itself, but
324 // it does include the sub_opcode, so we have to adjust for that below
325 (*offset_ptr) += arg_size;
328 } else if (opcode < prologue->OpcodeBase) {
332 // Takes no arguments. Append a row to the matrix using the
333 // current values of the state-machine registers. Then set
334 // the basic_block register to false.
335 state.appendRowToMatrix(*offset_ptr);
338 case DW_LNS_advance_pc:
339 // Takes a single unsigned LEB128 operand, multiplies it by the
340 // min_inst_length field of the prologue, and adds the
341 // result to the address register of the state machine.
342 state.Address += debug_line_data.getULEB128(offset_ptr) *
343 prologue->MinInstLength;
346 case DW_LNS_advance_line:
347 // Takes a single signed LEB128 operand and adds that value to
348 // the line register of the state machine.
349 state.Line += debug_line_data.getSLEB128(offset_ptr);
352 case DW_LNS_set_file:
353 // Takes a single unsigned LEB128 operand and stores it in the file
354 // register of the state machine.
355 state.File = debug_line_data.getULEB128(offset_ptr);
358 case DW_LNS_set_column:
359 // Takes a single unsigned LEB128 operand and stores it in the
360 // column register of the state machine.
361 state.Column = debug_line_data.getULEB128(offset_ptr);
364 case DW_LNS_negate_stmt:
365 // Takes no arguments. Set the is_stmt register of the state
366 // machine to the logical negation of its current value.
367 state.IsStmt = !state.IsStmt;
370 case DW_LNS_set_basic_block:
371 // Takes no arguments. Set the basic_block register of the
372 // state machine to true
373 state.BasicBlock = true;
376 case DW_LNS_const_add_pc:
377 // Takes no arguments. Add to the address register of the state
378 // machine the address increment value corresponding to special
379 // opcode 255. The motivation for DW_LNS_const_add_pc is this:
380 // when the statement program needs to advance the address by a
381 // small amount, it can use a single special opcode, which occupies
382 // a single byte. When it needs to advance the address by up to
383 // twice the range of the last special opcode, it can use
384 // DW_LNS_const_add_pc followed by a special opcode, for a total
385 // of two bytes. Only if it needs to advance the address by more
386 // than twice that range will it need to use both DW_LNS_advance_pc
387 // and a special opcode, requiring three or more bytes.
389 uint8_t adjust_opcode = 255 - prologue->OpcodeBase;
390 uint64_t addr_offset = (adjust_opcode / prologue->LineRange) *
391 prologue->MinInstLength;
392 state.Address += addr_offset;
396 case DW_LNS_fixed_advance_pc:
397 // Takes a single uhalf operand. Add to the address register of
398 // the state machine the value of the (unencoded) operand. This
399 // is the only extended opcode that takes an argument that is not
400 // a variable length number. The motivation for DW_LNS_fixed_advance_pc
401 // is this: existing assemblers cannot emit DW_LNS_advance_pc or
402 // special opcodes because they cannot encode LEB128 numbers or
403 // judge when the computation of a special opcode overflows and
404 // requires the use of DW_LNS_advance_pc. Such assemblers, however,
405 // can use DW_LNS_fixed_advance_pc instead, sacrificing compression.
406 state.Address += debug_line_data.getU16(offset_ptr);
409 case DW_LNS_set_prologue_end:
410 // Takes no arguments. Set the prologue_end register of the
411 // state machine to true
412 state.PrologueEnd = true;
415 case DW_LNS_set_epilogue_begin:
416 // Takes no arguments. Set the basic_block register of the
417 // state machine to true
418 state.EpilogueBegin = true;
422 // Takes a single unsigned LEB128 operand and stores it in the
423 // column register of the state machine.
424 state.Isa = debug_line_data.getULEB128(offset_ptr);
428 // Handle any unknown standard opcodes here. We know the lengths
429 // of such opcodes because they are specified in the prologue
430 // as a multiple of LEB128 operands for each opcode.
432 assert(opcode - 1U < prologue->StandardOpcodeLengths.size());
433 uint8_t opcode_length = prologue->StandardOpcodeLengths[opcode - 1];
434 for (uint8_t i=0; i<opcode_length; ++i)
435 debug_line_data.getULEB128(offset_ptr);
442 // A special opcode value is chosen based on the amount that needs
443 // to be added to the line and address registers. The maximum line
444 // increment for a special opcode is the value of the line_base
445 // field in the header, plus the value of the line_range field,
446 // minus 1 (line base + line range - 1). If the desired line
447 // increment is greater than the maximum line increment, a standard
448 // opcode must be used instead of a special opcode. The "address
449 // advance" is calculated by dividing the desired address increment
450 // by the minimum_instruction_length field from the header. The
451 // special opcode is then calculated using the following formula:
453 // opcode = (desired line increment - line_base) +
454 // (line_range * address advance) + opcode_base
456 // If the resulting opcode is greater than 255, a standard opcode
457 // must be used instead.
459 // To decode a special opcode, subtract the opcode_base from the
460 // opcode itself to give the adjusted opcode. The amount to
461 // increment the address register is the result of the adjusted
462 // opcode divided by the line_range multiplied by the
463 // minimum_instruction_length field from the header. That is:
465 // address increment = (adjusted opcode / line_range) *
466 // minimum_instruction_length
468 // The amount to increment the line register is the line_base plus
469 // the result of the adjusted opcode modulo the line_range. That is:
471 // line increment = line_base + (adjusted opcode % line_range)
473 uint8_t adjust_opcode = opcode - prologue->OpcodeBase;
474 uint64_t addr_offset = (adjust_opcode / prologue->LineRange) *
475 prologue->MinInstLength;
476 int32_t line_offset = prologue->LineBase +
477 (adjust_opcode % prologue->LineRange);
478 state.Line += line_offset;
479 state.Address += addr_offset;
480 state.appendRowToMatrix(*offset_ptr);
490 DWARFDebugLine::LineTable::lookupAddress(uint64_t address) const {
491 uint32_t unknown_index = UINT32_MAX;
492 if (Sequences.empty())
493 return unknown_index;
494 // First, find an instruction sequence containing the given address.
495 DWARFDebugLine::Sequence sequence;
496 sequence.LowPC = address;
497 SequenceIter first_seq = Sequences.begin();
498 SequenceIter last_seq = Sequences.end();
499 SequenceIter seq_pos = std::lower_bound(first_seq, last_seq, sequence,
500 DWARFDebugLine::Sequence::orderByLowPC);
501 DWARFDebugLine::Sequence found_seq;
502 if (seq_pos == last_seq) {
503 found_seq = Sequences.back();
504 } else if (seq_pos->LowPC == address) {
505 found_seq = *seq_pos;
507 if (seq_pos == first_seq)
508 return unknown_index;
509 found_seq = *(seq_pos - 1);
511 if (!found_seq.containsPC(address))
512 return unknown_index;
513 // Search for instruction address in the rows describing the sequence.
514 // Rows are stored in a vector, so we may use arithmetical operations with
516 DWARFDebugLine::Row row;
517 row.Address = address;
518 RowIter first_row = Rows.begin() + found_seq.FirstRowIndex;
519 RowIter last_row = Rows.begin() + found_seq.LastRowIndex;
520 RowIter row_pos = std::lower_bound(first_row, last_row, row,
521 DWARFDebugLine::Row::orderByAddress);
522 if (row_pos == last_row) {
523 return found_seq.LastRowIndex - 1;
525 uint32_t index = found_seq.FirstRowIndex + (row_pos - first_row);
526 if (row_pos->Address > address) {
527 if (row_pos == first_row)
528 return unknown_index;
536 DWARFDebugLine::LineTable::lookupAddressRange(uint64_t address,
538 std::vector<uint32_t>& result) const {
539 if (Sequences.empty())
541 uint64_t end_addr = address + size;
542 // First, find an instruction sequence containing the given address.
543 DWARFDebugLine::Sequence sequence;
544 sequence.LowPC = address;
545 SequenceIter first_seq = Sequences.begin();
546 SequenceIter last_seq = Sequences.end();
547 SequenceIter seq_pos = std::lower_bound(first_seq, last_seq, sequence,
548 DWARFDebugLine::Sequence::orderByLowPC);
549 if (seq_pos == last_seq || seq_pos->LowPC != address) {
550 if (seq_pos == first_seq)
554 if (!seq_pos->containsPC(address))
557 SequenceIter start_pos = seq_pos;
559 // Add the rows from the first sequence to the vector, starting with the
560 // index we just calculated
562 while (seq_pos != last_seq && seq_pos->LowPC < end_addr) {
563 DWARFDebugLine::Sequence cur_seq = *seq_pos;
564 uint32_t first_row_index;
565 uint32_t last_row_index;
566 if (seq_pos == start_pos) {
567 // For the first sequence, we need to find which row in the sequence is the
568 // first in our range. Rows are stored in a vector, so we may use
569 // arithmetical operations with iterators.
570 DWARFDebugLine::Row row;
571 row.Address = address;
572 RowIter first_row = Rows.begin() + cur_seq.FirstRowIndex;
573 RowIter last_row = Rows.begin() + cur_seq.LastRowIndex;
574 RowIter row_pos = std::upper_bound(first_row, last_row, row,
575 DWARFDebugLine::Row::orderByAddress);
576 // The 'row_pos' iterator references the first row that is greater than
577 // our start address. Unless that's the first row, we want to start at
578 // the row before that.
579 first_row_index = cur_seq.FirstRowIndex + (row_pos - first_row);
580 if (row_pos != first_row)
583 first_row_index = cur_seq.FirstRowIndex;
585 // For the last sequence in our range, we need to figure out the last row in
586 // range. For all other sequences we can go to the end of the sequence.
587 if (cur_seq.HighPC > end_addr) {
588 DWARFDebugLine::Row row;
589 row.Address = end_addr;
590 RowIter first_row = Rows.begin() + cur_seq.FirstRowIndex;
591 RowIter last_row = Rows.begin() + cur_seq.LastRowIndex;
592 RowIter row_pos = std::upper_bound(first_row, last_row, row,
593 DWARFDebugLine::Row::orderByAddress);
594 // The 'row_pos' iterator references the first row that is greater than
595 // our end address. The row before that is the last row we want.
596 last_row_index = cur_seq.FirstRowIndex + (row_pos - first_row) - 1;
598 // Contrary to what you might expect, DWARFDebugLine::SequenceLastRowIndex
599 // isn't a valid index within the current sequence. It's that plus one.
600 last_row_index = cur_seq.LastRowIndex - 1;
602 for (uint32_t i = first_row_index; i <= last_row_index; ++i) {
613 DWARFDebugLine::LineTable::getFileNameByIndex(uint64_t FileIndex,
614 bool NeedsAbsoluteFilePath,
615 std::string &Result) const {
616 if (FileIndex == 0 || FileIndex > Prologue.FileNames.size())
618 const FileNameEntry &Entry = Prologue.FileNames[FileIndex - 1];
619 const char *FileName = Entry.Name;
620 if (!NeedsAbsoluteFilePath ||
621 sys::path::is_absolute(FileName)) {
625 SmallString<16> FilePath;
626 uint64_t IncludeDirIndex = Entry.DirIdx;
627 // Be defensive about the contents of Entry.
628 if (IncludeDirIndex > 0 &&
629 IncludeDirIndex <= Prologue.IncludeDirectories.size()) {
630 const char *IncludeDir = Prologue.IncludeDirectories[IncludeDirIndex - 1];
631 sys::path::append(FilePath, IncludeDir);
633 sys::path::append(FilePath, FileName);
634 Result = FilePath.str();