1//===-- 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/Path.h"
14#include "llvm/Support/raw_ostream.h"
15#include <algorithm>
16using namespace llvm;
17using namespace dwarf;
18
19void 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);
29
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]);
33
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";
38
39  if (!FileNames.empty()) {
40    OS << "                Dir  Mod Time   File Len   File Name\n"
41       << "                ---- ---------- ---------- -----------"
42          "----------------\n";
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';
49    }
50  }
51}
52
53void DWARFDebugLine::Row::postAppend() {
54  BasicBlock = false;
55  PrologueEnd = false;
56  EpilogueBegin = false;
57}
58
59void DWARFDebugLine::Row::reset(bool default_is_stmt) {
60  Address = 0;
61  Line = 1;
62  Column = 0;
63  File = 1;
64  Isa = 0;
65  IsStmt = default_is_stmt;
66  BasicBlock = false;
67  EndSequence = false;
68  PrologueEnd = false;
69  EpilogueBegin = false;
70}
71
72void DWARFDebugLine::Row::dump(raw_ostream &OS) const {
73  OS << format("0x%16.16" PRIx64 " %6u %6u", Address, Line, Column)
74     << format(" %6u %3u ", File, Isa)
75     << (IsStmt ? " is_stmt" : "")
76     << (BasicBlock ? " basic_block" : "")
77     << (PrologueEnd ? " prologue_end" : "")
78     << (EpilogueBegin ? " epilogue_begin" : "")
79     << (EndSequence ? " end_sequence" : "")
80     << '\n';
81}
82
83void DWARFDebugLine::LineTable::dump(raw_ostream &OS) const {
84  Prologue.dump(OS);
85  OS << '\n';
86
87  if (!Rows.empty()) {
88    OS << "Address            Line   Column File   ISA Flags\n"
89       << "------------------ ------ ------ ------ --- -------------\n";
90    for (std::vector<Row>::const_iterator pos = Rows.begin(),
91         end = Rows.end(); pos != end; ++pos)
92      pos->dump(OS);
93  }
94}
95
96DWARFDebugLine::State::~State() {}
97
98void DWARFDebugLine::State::appendRowToMatrix(uint32_t offset) {
99  if (Sequence::Empty) {
100    // Record the beginning of instruction sequence.
101    Sequence::Empty = false;
102    Sequence::LowPC = Address;
103    Sequence::FirstRowIndex = row;
104  }
105  ++row;  // Increase the row number.
106  LineTable::appendRow(*this);
107  if (EndSequence) {
108    // Record the end of instruction sequence.
109    Sequence::HighPC = Address;
110    Sequence::LastRowIndex = row;
111    if (Sequence::isValid())
112      LineTable::appendSequence(*this);
113    Sequence::reset();
114  }
115  Row::postAppend();
116}
117
118void DWARFDebugLine::State::finalize() {
119  row = DoneParsingLineTable;
120  if (!Sequence::Empty) {
121    fprintf(stderr, "warning: last sequence in debug line table is not"
122                    "terminated!\n");
123  }
124  // Sort all sequences so that address lookup will work faster.
125  if (!Sequences.empty()) {
126    std::sort(Sequences.begin(), Sequences.end(), Sequence::orderByLowPC);
127    // Note: actually, instruction address ranges of sequences should not
128    // overlap (in shared objects and executables). If they do, the address
129    // lookup would still work, though, but result would be ambiguous.
130    // We don't report warning in this case. For example,
131    // sometimes .so compiled from multiple object files contains a few
132    // rudimentary sequences for address ranges [0x0, 0xsomething).
133  }
134}
135
136DWARFDebugLine::DumpingState::~DumpingState() {}
137
138void DWARFDebugLine::DumpingState::finalize() {
139  LineTable::dump(OS);
140}
141
142const DWARFDebugLine::LineTable *
143DWARFDebugLine::getLineTable(uint32_t offset) const {
144  LineTableConstIter pos = LineTableMap.find(offset);
145  if (pos != LineTableMap.end())
146    return &pos->second;
147  return 0;
148}
149
150const DWARFDebugLine::LineTable *
151DWARFDebugLine::getOrParseLineTable(DataExtractor debug_line_data,
152                                    uint32_t offset) {
153  std::pair<LineTableIter, bool> pos =
154    LineTableMap.insert(LineTableMapTy::value_type(offset, LineTable()));
155  if (pos.second) {
156    // Parse and cache the line table for at this offset.
157    State state;
158    if (!parseStatementTable(debug_line_data, &offset, state))
159      return 0;
160    pos.first->second = state;
161  }
162  return &pos.first->second;
163}
164
165bool
166DWARFDebugLine::parsePrologue(DataExtractor debug_line_data,
167                              uint32_t *offset_ptr, Prologue *prologue) {
168  const uint32_t prologue_offset = *offset_ptr;
169
170  prologue->clear();
171  prologue->TotalLength = debug_line_data.getU32(offset_ptr);
172  prologue->Version = debug_line_data.getU16(offset_ptr);
173  if (prologue->Version != 2)
174    return false;
175
176  prologue->PrologueLength = debug_line_data.getU32(offset_ptr);
177  const uint32_t end_prologue_offset = prologue->PrologueLength + *offset_ptr;
178  prologue->MinInstLength = debug_line_data.getU8(offset_ptr);
179  prologue->DefaultIsStmt = debug_line_data.getU8(offset_ptr);
180  prologue->LineBase = debug_line_data.getU8(offset_ptr);
181  prologue->LineRange = debug_line_data.getU8(offset_ptr);
182  prologue->OpcodeBase = debug_line_data.getU8(offset_ptr);
183
184  prologue->StandardOpcodeLengths.reserve(prologue->OpcodeBase-1);
185  for (uint32_t i = 1; i < prologue->OpcodeBase; ++i) {
186    uint8_t op_len = debug_line_data.getU8(offset_ptr);
187    prologue->StandardOpcodeLengths.push_back(op_len);
188  }
189
190  while (*offset_ptr < end_prologue_offset) {
191    const char *s = debug_line_data.getCStr(offset_ptr);
192    if (s && s[0])
193      prologue->IncludeDirectories.push_back(s);
194    else
195      break;
196  }
197
198  while (*offset_ptr < end_prologue_offset) {
199    const char *name = debug_line_data.getCStr(offset_ptr);
200    if (name && name[0]) {
201      FileNameEntry fileEntry;
202      fileEntry.Name = name;
203      fileEntry.DirIdx = debug_line_data.getULEB128(offset_ptr);
204      fileEntry.ModTime = debug_line_data.getULEB128(offset_ptr);
205      fileEntry.Length = debug_line_data.getULEB128(offset_ptr);
206      prologue->FileNames.push_back(fileEntry);
207    } else {
208      break;
209    }
210  }
211
212  if (*offset_ptr != end_prologue_offset) {
213    fprintf(stderr, "warning: parsing line table prologue at 0x%8.8x should"
214                    " have ended at 0x%8.8x but it ended ad 0x%8.8x\n",
215            prologue_offset, end_prologue_offset, *offset_ptr);
216    return false;
217  }
218  return true;
219}
220
221bool
222DWARFDebugLine::parseStatementTable(DataExtractor debug_line_data,
223                                    uint32_t *offset_ptr, State &state) {
224  const uint32_t debug_line_offset = *offset_ptr;
225
226  Prologue *prologue = &state.Prologue;
227
228  if (!parsePrologue(debug_line_data, offset_ptr, prologue)) {
229    // Restore our offset and return false to indicate failure!
230    *offset_ptr = debug_line_offset;
231    return false;
232  }
233
234  const uint32_t end_offset = debug_line_offset + prologue->TotalLength +
235                              sizeof(prologue->TotalLength);
236
237  state.reset();
238
239  while (*offset_ptr < end_offset) {
240    uint8_t opcode = debug_line_data.getU8(offset_ptr);
241
242    if (opcode == 0) {
243      // Extended Opcodes always start with a zero opcode followed by
244      // a uleb128 length so you can skip ones you don't know about
245      uint32_t ext_offset = *offset_ptr;
246      uint64_t len = debug_line_data.getULEB128(offset_ptr);
247      uint32_t arg_size = len - (*offset_ptr - ext_offset);
248
249      uint8_t sub_opcode = debug_line_data.getU8(offset_ptr);
250      switch (sub_opcode) {
251      case DW_LNE_end_sequence:
252        // Set the end_sequence register of the state machine to true and
253        // append a row to the matrix using the current values of the
254        // state-machine registers. Then reset the registers to the initial
255        // values specified above. Every statement program sequence must end
256        // with a DW_LNE_end_sequence instruction which creates a row whose
257        // address is that of the byte after the last target machine instruction
258        // of the sequence.
259        state.EndSequence = true;
260        state.appendRowToMatrix(*offset_ptr);
261        state.reset();
262        break;
263
264      case DW_LNE_set_address:
265        // Takes a single relocatable address as an operand. The size of the
266        // operand is the size appropriate to hold an address on the target
267        // machine. Set the address register to the value given by the
268        // relocatable address. All of the other statement program opcodes
269        // that affect the address register add a delta to it. This instruction
270        // stores a relocatable value into it instead.
271        state.Address = debug_line_data.getAddress(offset_ptr);
272        break;
273
274      case DW_LNE_define_file:
275        // Takes 4 arguments. The first is a null terminated string containing
276        // a source file name. The second is an unsigned LEB128 number
277        // representing the directory index of the directory in which the file
278        // was found. The third is an unsigned LEB128 number representing the
279        // time of last modification of the file. The fourth is an unsigned
280        // LEB128 number representing the length in bytes of the file. The time
281        // and length fields may contain LEB128(0) if the information is not
282        // available.
283        //
284        // The directory index represents an entry in the include_directories
285        // section of the statement program prologue. The index is LEB128(0)
286        // if the file was found in the current directory of the compilation,
287        // LEB128(1) if it was found in the first directory in the
288        // include_directories section, and so on. The directory index is
289        // ignored for file names that represent full path names.
290        //
291        // The files are numbered, starting at 1, in the order in which they
292        // appear; the names in the prologue come before names defined by
293        // the DW_LNE_define_file instruction. These numbers are used in the
294        // the file register of the state machine.
295        {
296          FileNameEntry fileEntry;
297          fileEntry.Name = debug_line_data.getCStr(offset_ptr);
298          fileEntry.DirIdx = debug_line_data.getULEB128(offset_ptr);
299          fileEntry.ModTime = debug_line_data.getULEB128(offset_ptr);
300          fileEntry.Length = debug_line_data.getULEB128(offset_ptr);
301          prologue->FileNames.push_back(fileEntry);
302        }
303        break;
304
305      default:
306        // Length doesn't include the zero opcode byte or the length itself, but
307        // it does include the sub_opcode, so we have to adjust for that below
308        (*offset_ptr) += arg_size;
309        break;
310      }
311    } else if (opcode < prologue->OpcodeBase) {
312      switch (opcode) {
313      // Standard Opcodes
314      case DW_LNS_copy:
315        // Takes no arguments. Append a row to the matrix using the
316        // current values of the state-machine registers. Then set
317        // the basic_block register to false.
318        state.appendRowToMatrix(*offset_ptr);
319        break;
320
321      case DW_LNS_advance_pc:
322        // Takes a single unsigned LEB128 operand, multiplies it by the
323        // min_inst_length field of the prologue, and adds the
324        // result to the address register of the state machine.
325        state.Address += debug_line_data.getULEB128(offset_ptr) *
326                         prologue->MinInstLength;
327        break;
328
329      case DW_LNS_advance_line:
330        // Takes a single signed LEB128 operand and adds that value to
331        // the line register of the state machine.
332        state.Line += debug_line_data.getSLEB128(offset_ptr);
333        break;
334
335      case DW_LNS_set_file:
336        // Takes a single unsigned LEB128 operand and stores it in the file
337        // register of the state machine.
338        state.File = debug_line_data.getULEB128(offset_ptr);
339        break;
340
341      case DW_LNS_set_column:
342        // Takes a single unsigned LEB128 operand and stores it in the
343        // column register of the state machine.
344        state.Column = debug_line_data.getULEB128(offset_ptr);
345        break;
346
347      case DW_LNS_negate_stmt:
348        // Takes no arguments. Set the is_stmt register of the state
349        // machine to the logical negation of its current value.
350        state.IsStmt = !state.IsStmt;
351        break;
352
353      case DW_LNS_set_basic_block:
354        // Takes no arguments. Set the basic_block register of the
355        // state machine to true
356        state.BasicBlock = true;
357        break;
358
359      case DW_LNS_const_add_pc:
360        // Takes no arguments. Add to the address register of the state
361        // machine the address increment value corresponding to special
362        // opcode 255. The motivation for DW_LNS_const_add_pc is this:
363        // when the statement program needs to advance the address by a
364        // small amount, it can use a single special opcode, which occupies
365        // a single byte. When it needs to advance the address by up to
366        // twice the range of the last special opcode, it can use
367        // DW_LNS_const_add_pc followed by a special opcode, for a total
368        // of two bytes. Only if it needs to advance the address by more
369        // than twice that range will it need to use both DW_LNS_advance_pc
370        // and a special opcode, requiring three or more bytes.
371        {
372          uint8_t adjust_opcode = 255 - prologue->OpcodeBase;
373          uint64_t addr_offset = (adjust_opcode / prologue->LineRange) *
374                                 prologue->MinInstLength;
375          state.Address += addr_offset;
376        }
377        break;
378
379      case DW_LNS_fixed_advance_pc:
380        // Takes a single uhalf operand. Add to the address register of
381        // the state machine the value of the (unencoded) operand. This
382        // is the only extended opcode that takes an argument that is not
383        // a variable length number. The motivation for DW_LNS_fixed_advance_pc
384        // is this: existing assemblers cannot emit DW_LNS_advance_pc or
385        // special opcodes because they cannot encode LEB128 numbers or
386        // judge when the computation of a special opcode overflows and
387        // requires the use of DW_LNS_advance_pc. Such assemblers, however,
388        // can use DW_LNS_fixed_advance_pc instead, sacrificing compression.
389        state.Address += debug_line_data.getU16(offset_ptr);
390        break;
391
392      case DW_LNS_set_prologue_end:
393        // Takes no arguments. Set the prologue_end register of the
394        // state machine to true
395        state.PrologueEnd = true;
396        break;
397
398      case DW_LNS_set_epilogue_begin:
399        // Takes no arguments. Set the basic_block register of the
400        // state machine to true
401        state.EpilogueBegin = true;
402        break;
403
404      case DW_LNS_set_isa:
405        // Takes a single unsigned LEB128 operand and stores it in the
406        // column register of the state machine.
407        state.Isa = debug_line_data.getULEB128(offset_ptr);
408        break;
409
410      default:
411        // Handle any unknown standard opcodes here. We know the lengths
412        // of such opcodes because they are specified in the prologue
413        // as a multiple of LEB128 operands for each opcode.
414        {
415          assert(opcode - 1U < prologue->StandardOpcodeLengths.size());
416          uint8_t opcode_length = prologue->StandardOpcodeLengths[opcode - 1];
417          for (uint8_t i=0; i<opcode_length; ++i)
418            debug_line_data.getULEB128(offset_ptr);
419        }
420        break;
421      }
422    } else {
423      // Special Opcodes
424
425      // A special opcode value is chosen based on the amount that needs
426      // to be added to the line and address registers. The maximum line
427      // increment for a special opcode is the value of the line_base
428      // field in the header, plus the value of the line_range field,
429      // minus 1 (line base + line range - 1). If the desired line
430      // increment is greater than the maximum line increment, a standard
431      // opcode must be used instead of a special opcode. The "address
432      // advance" is calculated by dividing the desired address increment
433      // by the minimum_instruction_length field from the header. The
434      // special opcode is then calculated using the following formula:
435      //
436      //  opcode = (desired line increment - line_base) +
437      //           (line_range * address advance) + opcode_base
438      //
439      // If the resulting opcode is greater than 255, a standard opcode
440      // must be used instead.
441      //
442      // To decode a special opcode, subtract the opcode_base from the
443      // opcode itself to give the adjusted opcode. The amount to
444      // increment the address register is the result of the adjusted
445      // opcode divided by the line_range multiplied by the
446      // minimum_instruction_length field from the header. That is:
447      //
448      //  address increment = (adjusted opcode / line_range) *
449      //                      minimum_instruction_length
450      //
451      // The amount to increment the line register is the line_base plus
452      // the result of the adjusted opcode modulo the line_range. That is:
453      //
454      // line increment = line_base + (adjusted opcode % line_range)
455
456      uint8_t adjust_opcode = opcode - prologue->OpcodeBase;
457      uint64_t addr_offset = (adjust_opcode / prologue->LineRange) *
458                             prologue->MinInstLength;
459      int32_t line_offset = prologue->LineBase +
460                            (adjust_opcode % prologue->LineRange);
461      state.Line += line_offset;
462      state.Address += addr_offset;
463      state.appendRowToMatrix(*offset_ptr);
464    }
465  }
466
467  state.finalize();
468
469  return end_offset;
470}
471
472uint32_t
473DWARFDebugLine::LineTable::lookupAddress(uint64_t address) const {
474  uint32_t unknown_index = UINT32_MAX;
475  if (Sequences.empty())
476    return unknown_index;
477  // First, find an instruction sequence containing the given address.
478  DWARFDebugLine::Sequence sequence;
479  sequence.LowPC = address;
480  SequenceIter first_seq = Sequences.begin();
481  SequenceIter last_seq = Sequences.end();
482  SequenceIter seq_pos = std::lower_bound(first_seq, last_seq, sequence,
483      DWARFDebugLine::Sequence::orderByLowPC);
484  DWARFDebugLine::Sequence found_seq;
485  if (seq_pos == last_seq) {
486    found_seq = Sequences.back();
487  } else if (seq_pos->LowPC == address) {
488    found_seq = *seq_pos;
489  } else {
490    if (seq_pos == first_seq)
491      return unknown_index;
492    found_seq = *(seq_pos - 1);
493  }
494  if (!found_seq.containsPC(address))
495    return unknown_index;
496  // Search for instruction address in the rows describing the sequence.
497  // Rows are stored in a vector, so we may use arithmetical operations with
498  // iterators.
499  DWARFDebugLine::Row row;
500  row.Address = address;
501  RowIter first_row = Rows.begin() + found_seq.FirstRowIndex;
502  RowIter last_row = Rows.begin() + found_seq.LastRowIndex;
503  RowIter row_pos = std::lower_bound(first_row, last_row, row,
504      DWARFDebugLine::Row::orderByAddress);
505  if (row_pos == last_row) {
506    return found_seq.LastRowIndex - 1;
507  }
508  uint32_t index = found_seq.FirstRowIndex + (row_pos - first_row);
509  if (row_pos->Address > address) {
510    if (row_pos == first_row)
511      return unknown_index;
512    else
513      index--;
514  }
515  return index;
516}
517
518bool
519DWARFDebugLine::LineTable::getFileNameByIndex(uint64_t FileIndex,
520                                              bool NeedsAbsoluteFilePath,
521                                              std::string &Result) const {
522  if (FileIndex == 0 || FileIndex > Prologue.FileNames.size())
523    return false;
524  const FileNameEntry &Entry = Prologue.FileNames[FileIndex - 1];
525  const char *FileName = Entry.Name;
526  if (!NeedsAbsoluteFilePath ||
527      sys::path::is_absolute(FileName)) {
528    Result = FileName;
529    return true;
530  }
531  SmallString<16> FilePath;
532  uint64_t IncludeDirIndex = Entry.DirIdx;
533  // Be defensive about the contents of Entry.
534  if (IncludeDirIndex > 0 &&
535      IncludeDirIndex <= Prologue.IncludeDirectories.size()) {
536    const char *IncludeDir = Prologue.IncludeDirectories[IncludeDirIndex - 1];
537    sys::path::append(FilePath, IncludeDir);
538  }
539  sys::path::append(FilePath, FileName);
540  Result = FilePath.str();
541  return true;
542}
543