blob: d99575d80033327cbf35cd711868643565fb4090 [file] [log] [blame]
Benjamin Kramerb848e972011-09-15 02:12:05 +00001//===-- DWARFDebugLine.cpp ------------------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "DWARFDebugLine.h"
11#include "llvm/Support/Dwarf.h"
12#include "llvm/Support/Format.h"
13#include "llvm/Support/raw_ostream.h"
Benjamin Kramer7393c7f2011-09-15 02:19:33 +000014#include <algorithm>
Benjamin Kramerb848e972011-09-15 02:12:05 +000015using namespace llvm;
16using namespace dwarf;
17
18void 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);
28
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]);
32
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";
37
38 if (!FileNames.empty()) {
39 OS << " Dir Mod Time File Len File Name\n"
40 << " ---- ---------- ---------- -----------"
41 "----------------\n";
42 for (uint32_t i = 0; i < FileNames.size(); ++i) {
43 const FileNameEntry& fileEntry = FileNames[i];
Benjamin Kramer5eccd362011-11-05 16:01:13 +000044 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)
Benjamin Kramerb848e972011-09-15 02:12:05 +000047 << fileEntry.Name << '\n';
48 }
49 }
50}
51
52void DWARFDebugLine::Row::postAppend() {
53 BasicBlock = false;
54 PrologueEnd = false;
55 EpilogueBegin = false;
56}
57
58void DWARFDebugLine::Row::reset(bool default_is_stmt) {
59 Address = 0;
60 Line = 1;
61 Column = 0;
62 File = 1;
63 Isa = 0;
64 IsStmt = default_is_stmt;
65 BasicBlock = false;
66 EndSequence = false;
67 PrologueEnd = false;
68 EpilogueBegin = false;
69}
70
71void DWARFDebugLine::Row::dump(raw_ostream &OS) const {
Benjamin Kramer41a96492011-11-05 08:57:40 +000072 OS << format("0x%16.16" PRIx64 " %6u %6u", Address, Line, Column)
Benjamin Kramerb848e972011-09-15 02:12:05 +000073 << 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" : "")
79 << '\n';
80}
81
82void DWARFDebugLine::LineTable::dump(raw_ostream &OS) const {
83 Prologue.dump(OS);
84 OS << '\n';
85
86 if (!Rows.empty()) {
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)
91 pos->dump(OS);
92 }
93}
94
Nick Lewycky6bc4e712011-09-15 03:41:51 +000095DWARFDebugLine::State::~State() {}
96
Benjamin Kramerb848e972011-09-15 02:12:05 +000097void DWARFDebugLine::State::appendRowToMatrix(uint32_t offset) {
Alexey Samsonov351f83b2012-08-07 11:46:57 +000098 if (Sequence::Empty) {
99 // Record the beginning of instruction sequence.
100 Sequence::Empty = false;
101 Sequence::LowPC = Address;
102 Sequence::FirstRowIndex = row;
103 }
Benjamin Kramerb848e972011-09-15 02:12:05 +0000104 ++row; // Increase the row number.
105 LineTable::appendRow(*this);
Alexey Samsonov351f83b2012-08-07 11:46:57 +0000106 if (EndSequence) {
107 // Record the end of instruction sequence.
108 Sequence::HighPC = Address;
109 Sequence::LastRowIndex = row;
110 if (Sequence::isValid())
111 LineTable::appendSequence(*this);
112 Sequence::reset();
113 }
Benjamin Kramerb848e972011-09-15 02:12:05 +0000114 Row::postAppend();
115}
116
Alexey Samsonov351f83b2012-08-07 11:46:57 +0000117void DWARFDebugLine::State::finalize() {
118 row = DoneParsingLineTable;
119 if (!Sequence::Empty) {
120 fprintf(stderr, "warning: last sequence in debug line table is not"
121 "terminated!\n");
122 }
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).
132 }
133}
134
Nick Lewycky6bc4e712011-09-15 03:41:51 +0000135DWARFDebugLine::DumpingState::~DumpingState() {}
136
Alexey Samsonov351f83b2012-08-07 11:46:57 +0000137void DWARFDebugLine::DumpingState::finalize() {
Benjamin Kramerb848e972011-09-15 02:12:05 +0000138 LineTable::dump(OS);
139}
140
Benjamin Kramerb848e972011-09-15 02:12:05 +0000141const DWARFDebugLine::LineTable *
142DWARFDebugLine::getLineTable(uint32_t offset) const {
143 LineTableConstIter pos = LineTableMap.find(offset);
144 if (pos != LineTableMap.end())
145 return &pos->second;
146 return 0;
147}
148
Benjamin Kramerc26ed9b2011-09-15 20:43:18 +0000149const DWARFDebugLine::LineTable *
150DWARFDebugLine::getOrParseLineTable(DataExtractor debug_line_data,
151 uint32_t offset) {
Benjamin Kramer1d13d9e2011-09-21 17:31:42 +0000152 std::pair<LineTableIter, bool> pos =
153 LineTableMap.insert(LineTableMapTy::value_type(offset, LineTable()));
154 if (pos.second) {
Benjamin Kramerc26ed9b2011-09-15 20:43:18 +0000155 // Parse and cache the line table for at this offset.
156 State state;
157 if (!parseStatementTable(debug_line_data, &offset, state))
158 return 0;
Benjamin Kramer1d13d9e2011-09-21 17:31:42 +0000159 pos.first->second = state;
Benjamin Kramerc26ed9b2011-09-15 20:43:18 +0000160 }
Benjamin Kramer1d13d9e2011-09-21 17:31:42 +0000161 return &pos.first->second;
Benjamin Kramerc26ed9b2011-09-15 20:43:18 +0000162}
163
Benjamin Kramerb848e972011-09-15 02:12:05 +0000164bool
165DWARFDebugLine::parsePrologue(DataExtractor debug_line_data,
166 uint32_t *offset_ptr, Prologue *prologue) {
167 const uint32_t prologue_offset = *offset_ptr;
168
169 prologue->clear();
170 prologue->TotalLength = debug_line_data.getU32(offset_ptr);
171 prologue->Version = debug_line_data.getU16(offset_ptr);
172 if (prologue->Version != 2)
173 return false;
174
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);
182
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);
187 }
188
189 while (*offset_ptr < end_prologue_offset) {
190 const char *s = debug_line_data.getCStr(offset_ptr);
191 if (s && s[0])
192 prologue->IncludeDirectories.push_back(s);
193 else
194 break;
195 }
196
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);
206 } else {
207 break;
208 }
209 }
210
211 if (*offset_ptr != end_prologue_offset) {
212 fprintf(stderr, "warning: parsing line table prologue at 0x%8.8x should"
NAKAMURA Takumi3a79eac2011-10-08 11:22:41 +0000213 " have ended at 0x%8.8x but it ended ad 0x%8.8x\n",
Benjamin Kramerb848e972011-09-15 02:12:05 +0000214 prologue_offset, end_prologue_offset, *offset_ptr);
Alexey Samsonov351f83b2012-08-07 11:46:57 +0000215 return false;
Benjamin Kramerb848e972011-09-15 02:12:05 +0000216 }
Alexey Samsonov351f83b2012-08-07 11:46:57 +0000217 return true;
Benjamin Kramerb848e972011-09-15 02:12:05 +0000218}
219
220bool
221DWARFDebugLine::parseStatementTable(DataExtractor debug_line_data,
222 uint32_t *offset_ptr, State &state) {
223 const uint32_t debug_line_offset = *offset_ptr;
224
225 Prologue *prologue = &state.Prologue;
226
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;
230 return false;
231 }
232
233 const uint32_t end_offset = debug_line_offset + prologue->TotalLength +
234 sizeof(prologue->TotalLength);
235
Benjamin Kramer9013db32011-09-15 21:59:13 +0000236 state.reset();
237
Benjamin Kramerb848e972011-09-15 02:12:05 +0000238 while (*offset_ptr < end_offset) {
239 uint8_t opcode = debug_line_data.getU8(offset_ptr);
240
241 if (opcode == 0) {
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);
247
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
257 // of the sequence.
258 state.EndSequence = true;
259 state.appendRowToMatrix(*offset_ptr);
260 state.reset();
261 break;
262
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);
271 break;
272
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
281 // available.
282 //
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.
289 //
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.
294 {
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);
301 }
302 break;
303
304 default:
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;
308 break;
309 }
310 } else if (opcode < prologue->OpcodeBase) {
311 switch (opcode) {
312 // Standard Opcodes
313 case DW_LNS_copy:
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);
318 break;
319
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;
326 break;
327
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);
332 break;
333
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);
338 break;
339
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);
344 break;
345
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;
350 break;
351
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;
356 break;
357
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.
370 {
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;
375 }
376 break;
377
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);
389 break;
390
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;
395 break;
396
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;
401 break;
402
403 case DW_LNS_set_isa:
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);
407 break;
408
409 default:
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.
413 {
Benjamin Kramer068d9a52011-09-15 03:20:04 +0000414 assert(opcode - 1U < prologue->StandardOpcodeLengths.size());
Benjamin Kramerb848e972011-09-15 02:12:05 +0000415 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);
418 }
419 break;
420 }
421 } else {
422 // Special Opcodes
423
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
NAKAMURA Takumi017449d2011-10-08 11:22:47 +0000430 // opcode must be used instead of a special opcode. The "address
431 // advance" is calculated by dividing the desired address increment
Benjamin Kramerb848e972011-09-15 02:12:05 +0000432 // by the minimum_instruction_length field from the header. The
433 // special opcode is then calculated using the following formula:
434 //
435 // opcode = (desired line increment - line_base) +
436 // (line_range * address advance) + opcode_base
437 //
438 // If the resulting opcode is greater than 255, a standard opcode
439 // must be used instead.
440 //
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:
446 //
447 // address increment = (adjusted opcode / line_range) *
448 // minimum_instruction_length
449 //
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:
452 //
453 // line increment = line_base + (adjusted opcode % line_range)
454
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);
463 }
464 }
465
Alexey Samsonov351f83b2012-08-07 11:46:57 +0000466 state.finalize();
Benjamin Kramerb848e972011-09-15 02:12:05 +0000467
468 return end_offset;
469}
470
Benjamin Kramerb848e972011-09-15 02:12:05 +0000471uint32_t
Alexey Samsonov351f83b2012-08-07 11:46:57 +0000472DWARFDebugLine::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;
488 } else {
489 if (seq_pos == first_seq)
490 return unknown_index;
491 found_seq = *(seq_pos - 1);
Benjamin Kramerb848e972011-09-15 02:12:05 +0000492 }
Alexey Samsonov351f83b2012-08-07 11:46:57 +0000493 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
497 // iterators.
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;
506 }
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;
511 else
512 index--;
513 }
514 return index;
Benjamin Kramerb848e972011-09-15 02:12:05 +0000515}