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("default_is_stmt: %u\n", DefaultIsStmt)
26 << format(" line_base: %i\n", LineBase)
27 << format(" line_range: %u\n", LineRange)
28 << format(" opcode_base: %u\n", OpcodeBase);
30 for (uint32_t i = 0; i < StandardOpcodeLengths.size(); ++i)
31 OS << format("standard_opcode_lengths[%s] = %u\n", LNStandardString(i+1),
32 StandardOpcodeLengths[i]);
34 if (!IncludeDirectories.empty())
35 for (uint32_t i = 0; i < IncludeDirectories.size(); ++i)
36 OS << format("include_directories[%3u] = '", i+1)
37 << IncludeDirectories[i] << "'\n";
39 if (!FileNames.empty()) {
40 OS << " Dir Mod Time File Len File Name\n"
41 << " ---- ---------- ---------- -----------"
43 for (uint32_t i = 0; i < FileNames.size(); ++i) {
44 const FileNameEntry& fileEntry = FileNames[i];
45 OS << format("file_names[%3u] %4" PRIu64 " ", i+1, fileEntry.DirIdx)
46 << format("0x%8.8" PRIx64 " 0x%8.8" PRIx64 " ",
47 fileEntry.ModTime, fileEntry.Length)
48 << fileEntry.Name << '\n';
53 void DWARFDebugLine::Row::postAppend() {
56 EpilogueBegin = false;
59 void DWARFDebugLine::Row::reset(bool default_is_stmt) {
66 IsStmt = default_is_stmt;
70 EpilogueBegin = false;
73 void DWARFDebugLine::Row::dump(raw_ostream &OS) const {
74 OS << format("0x%16.16" PRIx64 " %6u %6u", Address, Line, Column)
75 << format(" %6u %3u %13u ", File, Isa, Discriminator)
76 << (IsStmt ? " is_stmt" : "")
77 << (BasicBlock ? " basic_block" : "")
78 << (PrologueEnd ? " prologue_end" : "")
79 << (EpilogueBegin ? " epilogue_begin" : "")
80 << (EndSequence ? " end_sequence" : "")
84 void DWARFDebugLine::LineTable::dump(raw_ostream &OS) const {
89 OS << "Address Line Column File ISA Discriminator Flags\n"
90 << "------------------ ------ ------ ------ --- ------------- "
92 for (std::vector<Row>::const_iterator pos = Rows.begin(),
93 end = Rows.end(); pos != end; ++pos)
98 DWARFDebugLine::State::~State() {}
100 void DWARFDebugLine::State::appendRowToMatrix(uint32_t offset) {
101 if (Sequence::Empty) {
102 // Record the beginning of instruction sequence.
103 Sequence::Empty = false;
104 Sequence::LowPC = Address;
105 Sequence::FirstRowIndex = row;
107 ++row; // Increase the row number.
108 LineTable::appendRow(*this);
110 // Record the end of instruction sequence.
111 Sequence::HighPC = Address;
112 Sequence::LastRowIndex = row;
113 if (Sequence::isValid())
114 LineTable::appendSequence(*this);
120 void DWARFDebugLine::State::finalize() {
121 row = DoneParsingLineTable;
122 if (!Sequence::Empty) {
123 fprintf(stderr, "warning: last sequence in debug line table is not"
126 // Sort all sequences so that address lookup will work faster.
127 if (!Sequences.empty()) {
128 std::sort(Sequences.begin(), Sequences.end(), Sequence::orderByLowPC);
129 // Note: actually, instruction address ranges of sequences should not
130 // overlap (in shared objects and executables). If they do, the address
131 // lookup would still work, though, but result would be ambiguous.
132 // We don't report warning in this case. For example,
133 // sometimes .so compiled from multiple object files contains a few
134 // rudimentary sequences for address ranges [0x0, 0xsomething).
138 DWARFDebugLine::DumpingState::~DumpingState() {}
140 void DWARFDebugLine::DumpingState::finalize() {
144 const DWARFDebugLine::LineTable *
145 DWARFDebugLine::getLineTable(uint32_t offset) const {
146 LineTableConstIter pos = LineTableMap.find(offset);
147 if (pos != LineTableMap.end())
152 const DWARFDebugLine::LineTable *
153 DWARFDebugLine::getOrParseLineTable(DataExtractor debug_line_data,
155 std::pair<LineTableIter, bool> pos =
156 LineTableMap.insert(LineTableMapTy::value_type(offset, LineTable()));
158 // Parse and cache the line table for at this offset.
160 if (!parseStatementTable(debug_line_data, RelocMap, &offset, state))
162 pos.first->second = state;
164 return &pos.first->second;
168 DWARFDebugLine::parsePrologue(DataExtractor debug_line_data,
169 uint32_t *offset_ptr, Prologue *prologue) {
170 const uint32_t prologue_offset = *offset_ptr;
173 prologue->TotalLength = debug_line_data.getU32(offset_ptr);
174 prologue->Version = debug_line_data.getU16(offset_ptr);
175 if (prologue->Version != 2)
178 prologue->PrologueLength = debug_line_data.getU32(offset_ptr);
179 const uint32_t end_prologue_offset = prologue->PrologueLength + *offset_ptr;
180 prologue->MinInstLength = debug_line_data.getU8(offset_ptr);
181 prologue->DefaultIsStmt = debug_line_data.getU8(offset_ptr);
182 prologue->LineBase = debug_line_data.getU8(offset_ptr);
183 prologue->LineRange = debug_line_data.getU8(offset_ptr);
184 prologue->OpcodeBase = debug_line_data.getU8(offset_ptr);
186 prologue->StandardOpcodeLengths.reserve(prologue->OpcodeBase-1);
187 for (uint32_t i = 1; i < prologue->OpcodeBase; ++i) {
188 uint8_t op_len = debug_line_data.getU8(offset_ptr);
189 prologue->StandardOpcodeLengths.push_back(op_len);
192 while (*offset_ptr < end_prologue_offset) {
193 const char *s = debug_line_data.getCStr(offset_ptr);
195 prologue->IncludeDirectories.push_back(s);
200 while (*offset_ptr < end_prologue_offset) {
201 const char *name = debug_line_data.getCStr(offset_ptr);
202 if (name && name[0]) {
203 FileNameEntry fileEntry;
204 fileEntry.Name = name;
205 fileEntry.DirIdx = debug_line_data.getULEB128(offset_ptr);
206 fileEntry.ModTime = debug_line_data.getULEB128(offset_ptr);
207 fileEntry.Length = debug_line_data.getULEB128(offset_ptr);
208 prologue->FileNames.push_back(fileEntry);
214 if (*offset_ptr != end_prologue_offset) {
215 fprintf(stderr, "warning: parsing line table prologue at 0x%8.8x should"
216 " have ended at 0x%8.8x but it ended at 0x%8.8x\n",
217 prologue_offset, end_prologue_offset, *offset_ptr);
224 DWARFDebugLine::parseStatementTable(DataExtractor debug_line_data,
225 const RelocAddrMap *RMap,
226 uint32_t *offset_ptr, State &state) {
227 const uint32_t debug_line_offset = *offset_ptr;
229 Prologue *prologue = &state.Prologue;
231 if (!parsePrologue(debug_line_data, offset_ptr, prologue)) {
232 // Restore our offset and return false to indicate failure!
233 *offset_ptr = debug_line_offset;
237 const uint32_t end_offset = debug_line_offset + prologue->TotalLength +
238 sizeof(prologue->TotalLength);
242 while (*offset_ptr < end_offset) {
243 uint8_t opcode = debug_line_data.getU8(offset_ptr);
246 // Extended Opcodes always start with a zero opcode followed by
247 // a uleb128 length so you can skip ones you don't know about
248 uint32_t ext_offset = *offset_ptr;
249 uint64_t len = debug_line_data.getULEB128(offset_ptr);
250 uint32_t arg_size = len - (*offset_ptr - ext_offset);
252 uint8_t sub_opcode = debug_line_data.getU8(offset_ptr);
253 switch (sub_opcode) {
254 case DW_LNE_end_sequence:
255 // Set the end_sequence register of the state machine to true and
256 // append a row to the matrix using the current values of the
257 // state-machine registers. Then reset the registers to the initial
258 // values specified above. Every statement program sequence must end
259 // with a DW_LNE_end_sequence instruction which creates a row whose
260 // address is that of the byte after the last target machine instruction
262 state.EndSequence = true;
263 state.appendRowToMatrix(*offset_ptr);
267 case DW_LNE_set_address:
268 // Takes a single relocatable address as an operand. The size of the
269 // operand is the size appropriate to hold an address on the target
270 // machine. Set the address register to the value given by the
271 // relocatable address. All of the other statement program opcodes
272 // that affect the address register add a delta to it. This instruction
273 // stores a relocatable value into it instead.
275 // If this address is in our relocation map, apply the relocation.
276 RelocAddrMap::const_iterator AI = RMap->find(*offset_ptr);
277 if (AI != RMap->end()) {
278 const std::pair<uint8_t, int64_t> &R = AI->second;
279 state.Address = debug_line_data.getAddress(offset_ptr) + R.second;
281 state.Address = debug_line_data.getAddress(offset_ptr);
285 case DW_LNE_define_file:
286 // Takes 4 arguments. The first is a null terminated string containing
287 // a source file name. The second is an unsigned LEB128 number
288 // representing the directory index of the directory in which the file
289 // was found. The third is an unsigned LEB128 number representing the
290 // time of last modification of the file. The fourth is an unsigned
291 // LEB128 number representing the length in bytes of the file. The time
292 // and length fields may contain LEB128(0) if the information is not
295 // The directory index represents an entry in the include_directories
296 // section of the statement program prologue. The index is LEB128(0)
297 // if the file was found in the current directory of the compilation,
298 // LEB128(1) if it was found in the first directory in the
299 // include_directories section, and so on. The directory index is
300 // ignored for file names that represent full path names.
302 // The files are numbered, starting at 1, in the order in which they
303 // appear; the names in the prologue come before names defined by
304 // the DW_LNE_define_file instruction. These numbers are used in the
305 // the file register of the state machine.
307 FileNameEntry fileEntry;
308 fileEntry.Name = debug_line_data.getCStr(offset_ptr);
309 fileEntry.DirIdx = debug_line_data.getULEB128(offset_ptr);
310 fileEntry.ModTime = debug_line_data.getULEB128(offset_ptr);
311 fileEntry.Length = debug_line_data.getULEB128(offset_ptr);
312 prologue->FileNames.push_back(fileEntry);
316 case DW_LNE_set_discriminator:
317 state.Discriminator = debug_line_data.getULEB128(offset_ptr);
321 // Length doesn't include the zero opcode byte or the length itself, but
322 // it does include the sub_opcode, so we have to adjust for that below
323 (*offset_ptr) += arg_size;
326 } else if (opcode < prologue->OpcodeBase) {
330 // Takes no arguments. Append a row to the matrix using the
331 // current values of the state-machine registers. Then set
332 // the basic_block register to false.
333 state.appendRowToMatrix(*offset_ptr);
336 case DW_LNS_advance_pc:
337 // Takes a single unsigned LEB128 operand, multiplies it by the
338 // min_inst_length field of the prologue, and adds the
339 // result to the address register of the state machine.
340 state.Address += debug_line_data.getULEB128(offset_ptr) *
341 prologue->MinInstLength;
344 case DW_LNS_advance_line:
345 // Takes a single signed LEB128 operand and adds that value to
346 // the line register of the state machine.
347 state.Line += debug_line_data.getSLEB128(offset_ptr);
350 case DW_LNS_set_file:
351 // Takes a single unsigned LEB128 operand and stores it in the file
352 // register of the state machine.
353 state.File = debug_line_data.getULEB128(offset_ptr);
356 case DW_LNS_set_column:
357 // Takes a single unsigned LEB128 operand and stores it in the
358 // column register of the state machine.
359 state.Column = debug_line_data.getULEB128(offset_ptr);
362 case DW_LNS_negate_stmt:
363 // Takes no arguments. Set the is_stmt register of the state
364 // machine to the logical negation of its current value.
365 state.IsStmt = !state.IsStmt;
368 case DW_LNS_set_basic_block:
369 // Takes no arguments. Set the basic_block register of the
370 // state machine to true
371 state.BasicBlock = true;
374 case DW_LNS_const_add_pc:
375 // Takes no arguments. Add to the address register of the state
376 // machine the address increment value corresponding to special
377 // opcode 255. The motivation for DW_LNS_const_add_pc is this:
378 // when the statement program needs to advance the address by a
379 // small amount, it can use a single special opcode, which occupies
380 // a single byte. When it needs to advance the address by up to
381 // twice the range of the last special opcode, it can use
382 // DW_LNS_const_add_pc followed by a special opcode, for a total
383 // of two bytes. Only if it needs to advance the address by more
384 // than twice that range will it need to use both DW_LNS_advance_pc
385 // and a special opcode, requiring three or more bytes.
387 uint8_t adjust_opcode = 255 - prologue->OpcodeBase;
388 uint64_t addr_offset = (adjust_opcode / prologue->LineRange) *
389 prologue->MinInstLength;
390 state.Address += addr_offset;
394 case DW_LNS_fixed_advance_pc:
395 // Takes a single uhalf operand. Add to the address register of
396 // the state machine the value of the (unencoded) operand. This
397 // is the only extended opcode that takes an argument that is not
398 // a variable length number. The motivation for DW_LNS_fixed_advance_pc
399 // is this: existing assemblers cannot emit DW_LNS_advance_pc or
400 // special opcodes because they cannot encode LEB128 numbers or
401 // judge when the computation of a special opcode overflows and
402 // requires the use of DW_LNS_advance_pc. Such assemblers, however,
403 // can use DW_LNS_fixed_advance_pc instead, sacrificing compression.
404 state.Address += debug_line_data.getU16(offset_ptr);
407 case DW_LNS_set_prologue_end:
408 // Takes no arguments. Set the prologue_end register of the
409 // state machine to true
410 state.PrologueEnd = true;
413 case DW_LNS_set_epilogue_begin:
414 // Takes no arguments. Set the basic_block register of the
415 // state machine to true
416 state.EpilogueBegin = true;
420 // Takes a single unsigned LEB128 operand and stores it in the
421 // column register of the state machine.
422 state.Isa = debug_line_data.getULEB128(offset_ptr);
426 // Handle any unknown standard opcodes here. We know the lengths
427 // of such opcodes because they are specified in the prologue
428 // as a multiple of LEB128 operands for each opcode.
430 assert(opcode - 1U < prologue->StandardOpcodeLengths.size());
431 uint8_t opcode_length = prologue->StandardOpcodeLengths[opcode - 1];
432 for (uint8_t i=0; i<opcode_length; ++i)
433 debug_line_data.getULEB128(offset_ptr);
440 // A special opcode value is chosen based on the amount that needs
441 // to be added to the line and address registers. The maximum line
442 // increment for a special opcode is the value of the line_base
443 // field in the header, plus the value of the line_range field,
444 // minus 1 (line base + line range - 1). If the desired line
445 // increment is greater than the maximum line increment, a standard
446 // opcode must be used instead of a special opcode. The "address
447 // advance" is calculated by dividing the desired address increment
448 // by the minimum_instruction_length field from the header. The
449 // special opcode is then calculated using the following formula:
451 // opcode = (desired line increment - line_base) +
452 // (line_range * address advance) + opcode_base
454 // If the resulting opcode is greater than 255, a standard opcode
455 // must be used instead.
457 // To decode a special opcode, subtract the opcode_base from the
458 // opcode itself to give the adjusted opcode. The amount to
459 // increment the address register is the result of the adjusted
460 // opcode divided by the line_range multiplied by the
461 // minimum_instruction_length field from the header. That is:
463 // address increment = (adjusted opcode / line_range) *
464 // minimum_instruction_length
466 // The amount to increment the line register is the line_base plus
467 // the result of the adjusted opcode modulo the line_range. That is:
469 // line increment = line_base + (adjusted opcode % line_range)
471 uint8_t adjust_opcode = opcode - prologue->OpcodeBase;
472 uint64_t addr_offset = (adjust_opcode / prologue->LineRange) *
473 prologue->MinInstLength;
474 int32_t line_offset = prologue->LineBase +
475 (adjust_opcode % prologue->LineRange);
476 state.Line += line_offset;
477 state.Address += addr_offset;
478 state.appendRowToMatrix(*offset_ptr);
488 DWARFDebugLine::LineTable::lookupAddress(uint64_t address) const {
489 uint32_t unknown_index = UINT32_MAX;
490 if (Sequences.empty())
491 return unknown_index;
492 // First, find an instruction sequence containing the given address.
493 DWARFDebugLine::Sequence sequence;
494 sequence.LowPC = address;
495 SequenceIter first_seq = Sequences.begin();
496 SequenceIter last_seq = Sequences.end();
497 SequenceIter seq_pos = std::lower_bound(first_seq, last_seq, sequence,
498 DWARFDebugLine::Sequence::orderByLowPC);
499 DWARFDebugLine::Sequence found_seq;
500 if (seq_pos == last_seq) {
501 found_seq = Sequences.back();
502 } else if (seq_pos->LowPC == address) {
503 found_seq = *seq_pos;
505 if (seq_pos == first_seq)
506 return unknown_index;
507 found_seq = *(seq_pos - 1);
509 if (!found_seq.containsPC(address))
510 return unknown_index;
511 // Search for instruction address in the rows describing the sequence.
512 // Rows are stored in a vector, so we may use arithmetical operations with
514 DWARFDebugLine::Row row;
515 row.Address = address;
516 RowIter first_row = Rows.begin() + found_seq.FirstRowIndex;
517 RowIter last_row = Rows.begin() + found_seq.LastRowIndex;
518 RowIter row_pos = std::lower_bound(first_row, last_row, row,
519 DWARFDebugLine::Row::orderByAddress);
520 if (row_pos == last_row) {
521 return found_seq.LastRowIndex - 1;
523 uint32_t index = found_seq.FirstRowIndex + (row_pos - first_row);
524 if (row_pos->Address > address) {
525 if (row_pos == first_row)
526 return unknown_index;
534 DWARFDebugLine::LineTable::lookupAddressRange(uint64_t address,
536 std::vector<uint32_t>& result) const {
537 if (Sequences.empty())
539 uint64_t end_addr = address + size;
540 // First, find an instruction sequence containing the given address.
541 DWARFDebugLine::Sequence sequence;
542 sequence.LowPC = address;
543 SequenceIter first_seq = Sequences.begin();
544 SequenceIter last_seq = Sequences.end();
545 SequenceIter seq_pos = std::lower_bound(first_seq, last_seq, sequence,
546 DWARFDebugLine::Sequence::orderByLowPC);
547 if (seq_pos == last_seq || seq_pos->LowPC != address) {
548 if (seq_pos == first_seq)
552 if (!seq_pos->containsPC(address))
555 SequenceIter start_pos = seq_pos;
557 // Add the rows from the first sequence to the vector, starting with the
558 // index we just calculated
560 while (seq_pos != last_seq && seq_pos->LowPC < end_addr) {
561 DWARFDebugLine::Sequence cur_seq = *seq_pos;
562 uint32_t first_row_index;
563 uint32_t last_row_index;
564 if (seq_pos == start_pos) {
565 // For the first sequence, we need to find which row in the sequence is the
566 // first in our range. Rows are stored in a vector, so we may use
567 // arithmetical operations with iterators.
568 DWARFDebugLine::Row row;
569 row.Address = address;
570 RowIter first_row = Rows.begin() + cur_seq.FirstRowIndex;
571 RowIter last_row = Rows.begin() + cur_seq.LastRowIndex;
572 RowIter row_pos = std::upper_bound(first_row, last_row, row,
573 DWARFDebugLine::Row::orderByAddress);
574 // The 'row_pos' iterator references the first row that is greater than
575 // our start address. Unless that's the first row, we want to start at
576 // the row before that.
577 first_row_index = cur_seq.FirstRowIndex + (row_pos - first_row);
578 if (row_pos != first_row)
581 first_row_index = cur_seq.FirstRowIndex;
583 // For the last sequence in our range, we need to figure out the last row in
584 // range. For all other sequences we can go to the end of the sequence.
585 if (cur_seq.HighPC > end_addr) {
586 DWARFDebugLine::Row row;
587 row.Address = end_addr;
588 RowIter first_row = Rows.begin() + cur_seq.FirstRowIndex;
589 RowIter last_row = Rows.begin() + cur_seq.LastRowIndex;
590 RowIter row_pos = std::upper_bound(first_row, last_row, row,
591 DWARFDebugLine::Row::orderByAddress);
592 // The 'row_pos' iterator references the first row that is greater than
593 // our end address. The row before that is the last row we want.
594 last_row_index = cur_seq.FirstRowIndex + (row_pos - first_row) - 1;
596 // Contrary to what you might expect, DWARFDebugLine::SequenceLastRowIndex
597 // isn't a valid index within the current sequence. It's that plus one.
598 last_row_index = cur_seq.LastRowIndex - 1;
600 for (uint32_t i = first_row_index; i <= last_row_index; ++i) {
611 DWARFDebugLine::LineTable::getFileNameByIndex(uint64_t FileIndex,
612 bool NeedsAbsoluteFilePath,
613 std::string &Result) const {
614 if (FileIndex == 0 || FileIndex > Prologue.FileNames.size())
616 const FileNameEntry &Entry = Prologue.FileNames[FileIndex - 1];
617 const char *FileName = Entry.Name;
618 if (!NeedsAbsoluteFilePath ||
619 sys::path::is_absolute(FileName)) {
623 SmallString<16> FilePath;
624 uint64_t IncludeDirIndex = Entry.DirIdx;
625 // Be defensive about the contents of Entry.
626 if (IncludeDirIndex > 0 &&
627 IncludeDirIndex <= Prologue.IncludeDirectories.size()) {
628 const char *IncludeDir = Prologue.IncludeDirectories[IncludeDirIndex - 1];
629 sys::path::append(FilePath, IncludeDir);
631 sys::path::append(FilePath, FileName);
632 Result = FilePath.str();