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/raw_ostream.h"
16 using namespace dwarf;
18 void DWARFDebugLine::Prologue::dump(raw_ostream &OS) const {
19 OS << "Line table prologue:\n"
20 << format(" total_length: 0x%8.8x\n", TotalLength)
21 << format(" version: %u\n", Version)
22 << format("prologue_length: 0x%8.8x\n", PrologueLength)
23 << format("min_inst_length: %u\n", MinInstLength)
24 << format("default_is_stmt: %u\n", DefaultIsStmt)
25 << format(" line_base: %i\n", LineBase)
26 << format(" line_range: %u\n", LineRange)
27 << format(" opcode_base: %u\n", OpcodeBase);
29 for (uint32_t i = 0; i < StandardOpcodeLengths.size(); ++i)
30 OS << format("standard_opcode_lengths[%s] = %u\n", LNStandardString(i+1),
31 StandardOpcodeLengths[i]);
33 if (!IncludeDirectories.empty())
34 for (uint32_t i = 0; i < IncludeDirectories.size(); ++i)
35 OS << format("include_directories[%3u] = '", i+1)
36 << IncludeDirectories[i] << "'\n";
38 if (!FileNames.empty()) {
39 OS << " Dir Mod Time File Len File Name\n"
40 << " ---- ---------- ---------- -----------"
42 for (uint32_t i = 0; i < FileNames.size(); ++i) {
43 const FileNameEntry& fileEntry = FileNames[i];
44 OS << format("file_names[%3u] %4" PRIu64 " ", i+1, fileEntry.DirIdx)
45 << format("0x%8.8" PRIx64 " 0x%8.8" PRIx64 " ",
46 fileEntry.ModTime, fileEntry.Length)
47 << fileEntry.Name << '\n';
52 void DWARFDebugLine::Row::postAppend() {
55 EpilogueBegin = false;
58 void DWARFDebugLine::Row::reset(bool default_is_stmt) {
64 IsStmt = default_is_stmt;
68 EpilogueBegin = false;
71 void DWARFDebugLine::Row::dump(raw_ostream &OS) const {
72 OS << format("0x%16.16" PRIx64 " %6u %6u", Address, Line, Column)
73 << format(" %6u %3u ", File, Isa)
74 << (IsStmt ? " is_stmt" : "")
75 << (BasicBlock ? " basic_block" : "")
76 << (PrologueEnd ? " prologue_end" : "")
77 << (EpilogueBegin ? " epilogue_begin" : "")
78 << (EndSequence ? " end_sequence" : "")
82 void DWARFDebugLine::LineTable::dump(raw_ostream &OS) const {
87 OS << "Address Line Column File ISA Flags\n"
88 << "------------------ ------ ------ ------ --- -------------\n";
89 for (std::vector<Row>::const_iterator pos = Rows.begin(),
90 end = Rows.end(); pos != end; ++pos)
95 DWARFDebugLine::State::~State() {}
97 void DWARFDebugLine::State::appendRowToMatrix(uint32_t offset) {
98 if (Sequence::Empty) {
99 // Record the beginning of instruction sequence.
100 Sequence::Empty = false;
101 Sequence::LowPC = Address;
102 Sequence::FirstRowIndex = row;
104 ++row; // Increase the row number.
105 LineTable::appendRow(*this);
107 // Record the end of instruction sequence.
108 Sequence::HighPC = Address;
109 Sequence::LastRowIndex = row;
110 if (Sequence::isValid())
111 LineTable::appendSequence(*this);
117 void DWARFDebugLine::State::finalize() {
118 row = DoneParsingLineTable;
119 if (!Sequence::Empty) {
120 fprintf(stderr, "warning: last sequence in debug line table is not"
123 // Sort all sequences so that address lookup will work faster.
124 if (!Sequences.empty()) {
125 std::sort(Sequences.begin(), Sequences.end(), Sequence::orderByLowPC);
126 // Note: actually, instruction address ranges of sequences should not
127 // overlap (in shared objects and executables). If they do, the address
128 // lookup would still work, though, but result would be ambiguous.
129 // We don't report warning in this case. For example,
130 // sometimes .so compiled from multiple object files contains a few
131 // rudimentary sequences for address ranges [0x0, 0xsomething).
135 DWARFDebugLine::DumpingState::~DumpingState() {}
137 void DWARFDebugLine::DumpingState::finalize() {
141 const DWARFDebugLine::LineTable *
142 DWARFDebugLine::getLineTable(uint32_t offset) const {
143 LineTableConstIter pos = LineTableMap.find(offset);
144 if (pos != LineTableMap.end())
149 const DWARFDebugLine::LineTable *
150 DWARFDebugLine::getOrParseLineTable(DataExtractor debug_line_data,
152 std::pair<LineTableIter, bool> pos =
153 LineTableMap.insert(LineTableMapTy::value_type(offset, LineTable()));
155 // Parse and cache the line table for at this offset.
157 if (!parseStatementTable(debug_line_data, &offset, state))
159 pos.first->second = state;
161 return &pos.first->second;
165 DWARFDebugLine::parsePrologue(DataExtractor debug_line_data,
166 uint32_t *offset_ptr, Prologue *prologue) {
167 const uint32_t prologue_offset = *offset_ptr;
170 prologue->TotalLength = debug_line_data.getU32(offset_ptr);
171 prologue->Version = debug_line_data.getU16(offset_ptr);
172 if (prologue->Version != 2)
175 prologue->PrologueLength = debug_line_data.getU32(offset_ptr);
176 const uint32_t end_prologue_offset = prologue->PrologueLength + *offset_ptr;
177 prologue->MinInstLength = debug_line_data.getU8(offset_ptr);
178 prologue->DefaultIsStmt = debug_line_data.getU8(offset_ptr);
179 prologue->LineBase = debug_line_data.getU8(offset_ptr);
180 prologue->LineRange = debug_line_data.getU8(offset_ptr);
181 prologue->OpcodeBase = debug_line_data.getU8(offset_ptr);
183 prologue->StandardOpcodeLengths.reserve(prologue->OpcodeBase-1);
184 for (uint32_t i = 1; i < prologue->OpcodeBase; ++i) {
185 uint8_t op_len = debug_line_data.getU8(offset_ptr);
186 prologue->StandardOpcodeLengths.push_back(op_len);
189 while (*offset_ptr < end_prologue_offset) {
190 const char *s = debug_line_data.getCStr(offset_ptr);
192 prologue->IncludeDirectories.push_back(s);
197 while (*offset_ptr < end_prologue_offset) {
198 const char *name = debug_line_data.getCStr(offset_ptr);
199 if (name && name[0]) {
200 FileNameEntry fileEntry;
201 fileEntry.Name = name;
202 fileEntry.DirIdx = debug_line_data.getULEB128(offset_ptr);
203 fileEntry.ModTime = debug_line_data.getULEB128(offset_ptr);
204 fileEntry.Length = debug_line_data.getULEB128(offset_ptr);
205 prologue->FileNames.push_back(fileEntry);
211 if (*offset_ptr != end_prologue_offset) {
212 fprintf(stderr, "warning: parsing line table prologue at 0x%8.8x should"
213 " have ended at 0x%8.8x but it ended ad 0x%8.8x\n",
214 prologue_offset, end_prologue_offset, *offset_ptr);
221 DWARFDebugLine::parseStatementTable(DataExtractor debug_line_data,
222 uint32_t *offset_ptr, State &state) {
223 const uint32_t debug_line_offset = *offset_ptr;
225 Prologue *prologue = &state.Prologue;
227 if (!parsePrologue(debug_line_data, offset_ptr, prologue)) {
228 // Restore our offset and return false to indicate failure!
229 *offset_ptr = debug_line_offset;
233 const uint32_t end_offset = debug_line_offset + prologue->TotalLength +
234 sizeof(prologue->TotalLength);
238 while (*offset_ptr < end_offset) {
239 uint8_t opcode = debug_line_data.getU8(offset_ptr);
242 // Extended Opcodes always start with a zero opcode followed by
243 // a uleb128 length so you can skip ones you don't know about
244 uint32_t ext_offset = *offset_ptr;
245 uint64_t len = debug_line_data.getULEB128(offset_ptr);
246 uint32_t arg_size = len - (*offset_ptr - ext_offset);
248 uint8_t sub_opcode = debug_line_data.getU8(offset_ptr);
249 switch (sub_opcode) {
250 case DW_LNE_end_sequence:
251 // Set the end_sequence register of the state machine to true and
252 // append a row to the matrix using the current values of the
253 // state-machine registers. Then reset the registers to the initial
254 // values specified above. Every statement program sequence must end
255 // with a DW_LNE_end_sequence instruction which creates a row whose
256 // address is that of the byte after the last target machine instruction
258 state.EndSequence = true;
259 state.appendRowToMatrix(*offset_ptr);
263 case DW_LNE_set_address:
264 // Takes a single relocatable address as an operand. The size of the
265 // operand is the size appropriate to hold an address on the target
266 // machine. Set the address register to the value given by the
267 // relocatable address. All of the other statement program opcodes
268 // that affect the address register add a delta to it. This instruction
269 // stores a relocatable value into it instead.
270 state.Address = debug_line_data.getAddress(offset_ptr);
273 case DW_LNE_define_file:
274 // Takes 4 arguments. The first is a null terminated string containing
275 // a source file name. The second is an unsigned LEB128 number
276 // representing the directory index of the directory in which the file
277 // was found. The third is an unsigned LEB128 number representing the
278 // time of last modification of the file. The fourth is an unsigned
279 // LEB128 number representing the length in bytes of the file. The time
280 // and length fields may contain LEB128(0) if the information is not
283 // The directory index represents an entry in the include_directories
284 // section of the statement program prologue. The index is LEB128(0)
285 // if the file was found in the current directory of the compilation,
286 // LEB128(1) if it was found in the first directory in the
287 // include_directories section, and so on. The directory index is
288 // ignored for file names that represent full path names.
290 // The files are numbered, starting at 1, in the order in which they
291 // appear; the names in the prologue come before names defined by
292 // the DW_LNE_define_file instruction. These numbers are used in the
293 // the file register of the state machine.
295 FileNameEntry fileEntry;
296 fileEntry.Name = debug_line_data.getCStr(offset_ptr);
297 fileEntry.DirIdx = debug_line_data.getULEB128(offset_ptr);
298 fileEntry.ModTime = debug_line_data.getULEB128(offset_ptr);
299 fileEntry.Length = debug_line_data.getULEB128(offset_ptr);
300 prologue->FileNames.push_back(fileEntry);
305 // Length doesn't include the zero opcode byte or the length itself, but
306 // it does include the sub_opcode, so we have to adjust for that below
307 (*offset_ptr) += arg_size;
310 } else if (opcode < prologue->OpcodeBase) {
314 // Takes no arguments. Append a row to the matrix using the
315 // current values of the state-machine registers. Then set
316 // the basic_block register to false.
317 state.appendRowToMatrix(*offset_ptr);
320 case DW_LNS_advance_pc:
321 // Takes a single unsigned LEB128 operand, multiplies it by the
322 // min_inst_length field of the prologue, and adds the
323 // result to the address register of the state machine.
324 state.Address += debug_line_data.getULEB128(offset_ptr) *
325 prologue->MinInstLength;
328 case DW_LNS_advance_line:
329 // Takes a single signed LEB128 operand and adds that value to
330 // the line register of the state machine.
331 state.Line += debug_line_data.getSLEB128(offset_ptr);
334 case DW_LNS_set_file:
335 // Takes a single unsigned LEB128 operand and stores it in the file
336 // register of the state machine.
337 state.File = debug_line_data.getULEB128(offset_ptr);
340 case DW_LNS_set_column:
341 // Takes a single unsigned LEB128 operand and stores it in the
342 // column register of the state machine.
343 state.Column = debug_line_data.getULEB128(offset_ptr);
346 case DW_LNS_negate_stmt:
347 // Takes no arguments. Set the is_stmt register of the state
348 // machine to the logical negation of its current value.
349 state.IsStmt = !state.IsStmt;
352 case DW_LNS_set_basic_block:
353 // Takes no arguments. Set the basic_block register of the
354 // state machine to true
355 state.BasicBlock = true;
358 case DW_LNS_const_add_pc:
359 // Takes no arguments. Add to the address register of the state
360 // machine the address increment value corresponding to special
361 // opcode 255. The motivation for DW_LNS_const_add_pc is this:
362 // when the statement program needs to advance the address by a
363 // small amount, it can use a single special opcode, which occupies
364 // a single byte. When it needs to advance the address by up to
365 // twice the range of the last special opcode, it can use
366 // DW_LNS_const_add_pc followed by a special opcode, for a total
367 // of two bytes. Only if it needs to advance the address by more
368 // than twice that range will it need to use both DW_LNS_advance_pc
369 // and a special opcode, requiring three or more bytes.
371 uint8_t adjust_opcode = 255 - prologue->OpcodeBase;
372 uint64_t addr_offset = (adjust_opcode / prologue->LineRange) *
373 prologue->MinInstLength;
374 state.Address += addr_offset;
378 case DW_LNS_fixed_advance_pc:
379 // Takes a single uhalf operand. Add to the address register of
380 // the state machine the value of the (unencoded) operand. This
381 // is the only extended opcode that takes an argument that is not
382 // a variable length number. The motivation for DW_LNS_fixed_advance_pc
383 // is this: existing assemblers cannot emit DW_LNS_advance_pc or
384 // special opcodes because they cannot encode LEB128 numbers or
385 // judge when the computation of a special opcode overflows and
386 // requires the use of DW_LNS_advance_pc. Such assemblers, however,
387 // can use DW_LNS_fixed_advance_pc instead, sacrificing compression.
388 state.Address += debug_line_data.getU16(offset_ptr);
391 case DW_LNS_set_prologue_end:
392 // Takes no arguments. Set the prologue_end register of the
393 // state machine to true
394 state.PrologueEnd = true;
397 case DW_LNS_set_epilogue_begin:
398 // Takes no arguments. Set the basic_block register of the
399 // state machine to true
400 state.EpilogueBegin = true;
404 // Takes a single unsigned LEB128 operand and stores it in the
405 // column register of the state machine.
406 state.Isa = debug_line_data.getULEB128(offset_ptr);
410 // Handle any unknown standard opcodes here. We know the lengths
411 // of such opcodes because they are specified in the prologue
412 // as a multiple of LEB128 operands for each opcode.
414 assert(opcode - 1U < prologue->StandardOpcodeLengths.size());
415 uint8_t opcode_length = prologue->StandardOpcodeLengths[opcode - 1];
416 for (uint8_t i=0; i<opcode_length; ++i)
417 debug_line_data.getULEB128(offset_ptr);
424 // A special opcode value is chosen based on the amount that needs
425 // to be added to the line and address registers. The maximum line
426 // increment for a special opcode is the value of the line_base
427 // field in the header, plus the value of the line_range field,
428 // minus 1 (line base + line range - 1). If the desired line
429 // increment is greater than the maximum line increment, a standard
430 // opcode must be used instead of a special opcode. The "address
431 // advance" is calculated by dividing the desired address increment
432 // by the minimum_instruction_length field from the header. The
433 // special opcode is then calculated using the following formula:
435 // opcode = (desired line increment - line_base) +
436 // (line_range * address advance) + opcode_base
438 // If the resulting opcode is greater than 255, a standard opcode
439 // must be used instead.
441 // To decode a special opcode, subtract the opcode_base from the
442 // opcode itself to give the adjusted opcode. The amount to
443 // increment the address register is the result of the adjusted
444 // opcode divided by the line_range multiplied by the
445 // minimum_instruction_length field from the header. That is:
447 // address increment = (adjusted opcode / line_range) *
448 // minimum_instruction_length
450 // The amount to increment the line register is the line_base plus
451 // the result of the adjusted opcode modulo the line_range. That is:
453 // line increment = line_base + (adjusted opcode % line_range)
455 uint8_t adjust_opcode = opcode - prologue->OpcodeBase;
456 uint64_t addr_offset = (adjust_opcode / prologue->LineRange) *
457 prologue->MinInstLength;
458 int32_t line_offset = prologue->LineBase +
459 (adjust_opcode % prologue->LineRange);
460 state.Line += line_offset;
461 state.Address += addr_offset;
462 state.appendRowToMatrix(*offset_ptr);
472 DWARFDebugLine::LineTable::lookupAddress(uint64_t address) const {
473 uint32_t unknown_index = UINT32_MAX;
474 if (Sequences.empty())
475 return unknown_index;
476 // First, find an instruction sequence containing the given address.
477 DWARFDebugLine::Sequence sequence;
478 sequence.LowPC = address;
479 SequenceIter first_seq = Sequences.begin();
480 SequenceIter last_seq = Sequences.end();
481 SequenceIter seq_pos = std::lower_bound(first_seq, last_seq, sequence,
482 DWARFDebugLine::Sequence::orderByLowPC);
483 DWARFDebugLine::Sequence found_seq;
484 if (seq_pos == last_seq) {
485 found_seq = Sequences.back();
486 } else if (seq_pos->LowPC == address) {
487 found_seq = *seq_pos;
489 if (seq_pos == first_seq)
490 return unknown_index;
491 found_seq = *(seq_pos - 1);
493 if (!found_seq.containsPC(address))
494 return unknown_index;
495 // Search for instruction address in the rows describing the sequence.
496 // Rows are stored in a vector, so we may use arithmetical operations with
498 DWARFDebugLine::Row row;
499 row.Address = address;
500 RowIter first_row = Rows.begin() + found_seq.FirstRowIndex;
501 RowIter last_row = Rows.begin() + found_seq.LastRowIndex;
502 RowIter row_pos = std::lower_bound(first_row, last_row, row,
503 DWARFDebugLine::Row::orderByAddress);
504 if (row_pos == last_row) {
505 return found_seq.LastRowIndex - 1;
507 uint32_t index = found_seq.FirstRowIndex + (row_pos - first_row);
508 if (row_pos->Address > address) {
509 if (row_pos == first_row)
510 return unknown_index;