Add support for applying in-memory relocations to the .debug_line section and, in...
[oota-llvm.git] / lib / DebugInfo / DWARFDebugLine.cpp
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>
16 using namespace llvm;
17 using namespace dwarf;
18
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);
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
53 void DWARFDebugLine::Row::postAppend() {
54   BasicBlock = false;
55   PrologueEnd = false;
56   EpilogueBegin = false;
57 }
58
59 void 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
72 void 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
83 void 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
96 DWARFDebugLine::State::~State() {}
97
98 void 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
118 void 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
136 DWARFDebugLine::DumpingState::~DumpingState() {}
137
138 void DWARFDebugLine::DumpingState::finalize() {
139   LineTable::dump(OS);
140 }
141
142 const DWARFDebugLine::LineTable *
143 DWARFDebugLine::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
150 const DWARFDebugLine::LineTable *
151 DWARFDebugLine::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, RelocMap, &offset, state))
159       return 0;
160     pos.first->second = state;
161   }
162   return &pos.first->second;
163 }
164
165 bool
166 DWARFDebugLine::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
221 bool
222 DWARFDebugLine::parseStatementTable(DataExtractor debug_line_data, 
223                                     const RelocAddrMap *RMap,
224                                     uint32_t *offset_ptr, State &state) {
225   const uint32_t debug_line_offset = *offset_ptr;
226
227   Prologue *prologue = &state.Prologue;
228
229   if (!parsePrologue(debug_line_data, offset_ptr, prologue)) {
230     // Restore our offset and return false to indicate failure!
231     *offset_ptr = debug_line_offset;
232     return false;
233   }
234
235   const uint32_t end_offset = debug_line_offset + prologue->TotalLength +
236                               sizeof(prologue->TotalLength);
237
238   state.reset();
239
240   while (*offset_ptr < end_offset) {
241     uint8_t opcode = debug_line_data.getU8(offset_ptr);
242
243     if (opcode == 0) {
244       // Extended Opcodes always start with a zero opcode followed by
245       // a uleb128 length so you can skip ones you don't know about
246       uint32_t ext_offset = *offset_ptr;
247       uint64_t len = debug_line_data.getULEB128(offset_ptr);
248       uint32_t arg_size = len - (*offset_ptr - ext_offset);
249
250       uint8_t sub_opcode = debug_line_data.getU8(offset_ptr);
251       switch (sub_opcode) {
252       case DW_LNE_end_sequence:
253         // Set the end_sequence register of the state machine to true and
254         // append a row to the matrix using the current values of the
255         // state-machine registers. Then reset the registers to the initial
256         // values specified above. Every statement program sequence must end
257         // with a DW_LNE_end_sequence instruction which creates a row whose
258         // address is that of the byte after the last target machine instruction
259         // of the sequence.
260         state.EndSequence = true;
261         state.appendRowToMatrix(*offset_ptr);
262         state.reset();
263         break;
264
265       case DW_LNE_set_address:
266         // Takes a single relocatable address as an operand. The size of the
267         // operand is the size appropriate to hold an address on the target
268         // machine. Set the address register to the value given by the
269         // relocatable address. All of the other statement program opcodes
270         // that affect the address register add a delta to it. This instruction
271         // stores a relocatable value into it instead.
272         {
273           // If this address is in our relocation map, apply the relocation.
274           RelocAddrMap::const_iterator AI = RMap->find(*offset_ptr);
275           if (AI != RMap->end()) {
276              const std::pair<uint8_t, int64_t> &R = AI->second;
277              state.Address = debug_line_data.getAddress(offset_ptr) + R.second;
278           } else
279             state.Address = debug_line_data.getAddress(offset_ptr);
280         }
281         break;
282
283       case DW_LNE_define_file:
284         // Takes 4 arguments. The first is a null terminated string containing
285         // a source file name. The second is an unsigned LEB128 number
286         // representing the directory index of the directory in which the file
287         // was found. The third is an unsigned LEB128 number representing the
288         // time of last modification of the file. The fourth is an unsigned
289         // LEB128 number representing the length in bytes of the file. The time
290         // and length fields may contain LEB128(0) if the information is not
291         // available.
292         //
293         // The directory index represents an entry in the include_directories
294         // section of the statement program prologue. The index is LEB128(0)
295         // if the file was found in the current directory of the compilation,
296         // LEB128(1) if it was found in the first directory in the
297         // include_directories section, and so on. The directory index is
298         // ignored for file names that represent full path names.
299         //
300         // The files are numbered, starting at 1, in the order in which they
301         // appear; the names in the prologue come before names defined by
302         // the DW_LNE_define_file instruction. These numbers are used in the
303         // the file register of the state machine.
304         {
305           FileNameEntry fileEntry;
306           fileEntry.Name = debug_line_data.getCStr(offset_ptr);
307           fileEntry.DirIdx = debug_line_data.getULEB128(offset_ptr);
308           fileEntry.ModTime = debug_line_data.getULEB128(offset_ptr);
309           fileEntry.Length = debug_line_data.getULEB128(offset_ptr);
310           prologue->FileNames.push_back(fileEntry);
311         }
312         break;
313
314       default:
315         // Length doesn't include the zero opcode byte or the length itself, but
316         // it does include the sub_opcode, so we have to adjust for that below
317         (*offset_ptr) += arg_size;
318         break;
319       }
320     } else if (opcode < prologue->OpcodeBase) {
321       switch (opcode) {
322       // Standard Opcodes
323       case DW_LNS_copy:
324         // Takes no arguments. Append a row to the matrix using the
325         // current values of the state-machine registers. Then set
326         // the basic_block register to false.
327         state.appendRowToMatrix(*offset_ptr);
328         break;
329
330       case DW_LNS_advance_pc:
331         // Takes a single unsigned LEB128 operand, multiplies it by the
332         // min_inst_length field of the prologue, and adds the
333         // result to the address register of the state machine.
334         state.Address += debug_line_data.getULEB128(offset_ptr) *
335                          prologue->MinInstLength;
336         break;
337
338       case DW_LNS_advance_line:
339         // Takes a single signed LEB128 operand and adds that value to
340         // the line register of the state machine.
341         state.Line += debug_line_data.getSLEB128(offset_ptr);
342         break;
343
344       case DW_LNS_set_file:
345         // Takes a single unsigned LEB128 operand and stores it in the file
346         // register of the state machine.
347         state.File = debug_line_data.getULEB128(offset_ptr);
348         break;
349
350       case DW_LNS_set_column:
351         // Takes a single unsigned LEB128 operand and stores it in the
352         // column register of the state machine.
353         state.Column = debug_line_data.getULEB128(offset_ptr);
354         break;
355
356       case DW_LNS_negate_stmt:
357         // Takes no arguments. Set the is_stmt register of the state
358         // machine to the logical negation of its current value.
359         state.IsStmt = !state.IsStmt;
360         break;
361
362       case DW_LNS_set_basic_block:
363         // Takes no arguments. Set the basic_block register of the
364         // state machine to true
365         state.BasicBlock = true;
366         break;
367
368       case DW_LNS_const_add_pc:
369         // Takes no arguments. Add to the address register of the state
370         // machine the address increment value corresponding to special
371         // opcode 255. The motivation for DW_LNS_const_add_pc is this:
372         // when the statement program needs to advance the address by a
373         // small amount, it can use a single special opcode, which occupies
374         // a single byte. When it needs to advance the address by up to
375         // twice the range of the last special opcode, it can use
376         // DW_LNS_const_add_pc followed by a special opcode, for a total
377         // of two bytes. Only if it needs to advance the address by more
378         // than twice that range will it need to use both DW_LNS_advance_pc
379         // and a special opcode, requiring three or more bytes.
380         {
381           uint8_t adjust_opcode = 255 - prologue->OpcodeBase;
382           uint64_t addr_offset = (adjust_opcode / prologue->LineRange) *
383                                  prologue->MinInstLength;
384           state.Address += addr_offset;
385         }
386         break;
387
388       case DW_LNS_fixed_advance_pc:
389         // Takes a single uhalf operand. Add to the address register of
390         // the state machine the value of the (unencoded) operand. This
391         // is the only extended opcode that takes an argument that is not
392         // a variable length number. The motivation for DW_LNS_fixed_advance_pc
393         // is this: existing assemblers cannot emit DW_LNS_advance_pc or
394         // special opcodes because they cannot encode LEB128 numbers or
395         // judge when the computation of a special opcode overflows and
396         // requires the use of DW_LNS_advance_pc. Such assemblers, however,
397         // can use DW_LNS_fixed_advance_pc instead, sacrificing compression.
398         state.Address += debug_line_data.getU16(offset_ptr);
399         break;
400
401       case DW_LNS_set_prologue_end:
402         // Takes no arguments. Set the prologue_end register of the
403         // state machine to true
404         state.PrologueEnd = true;
405         break;
406
407       case DW_LNS_set_epilogue_begin:
408         // Takes no arguments. Set the basic_block register of the
409         // state machine to true
410         state.EpilogueBegin = true;
411         break;
412
413       case DW_LNS_set_isa:
414         // Takes a single unsigned LEB128 operand and stores it in the
415         // column register of the state machine.
416         state.Isa = debug_line_data.getULEB128(offset_ptr);
417         break;
418
419       default:
420         // Handle any unknown standard opcodes here. We know the lengths
421         // of such opcodes because they are specified in the prologue
422         // as a multiple of LEB128 operands for each opcode.
423         {
424           assert(opcode - 1U < prologue->StandardOpcodeLengths.size());
425           uint8_t opcode_length = prologue->StandardOpcodeLengths[opcode - 1];
426           for (uint8_t i=0; i<opcode_length; ++i)
427             debug_line_data.getULEB128(offset_ptr);
428         }
429         break;
430       }
431     } else {
432       // Special Opcodes
433
434       // A special opcode value is chosen based on the amount that needs
435       // to be added to the line and address registers. The maximum line
436       // increment for a special opcode is the value of the line_base
437       // field in the header, plus the value of the line_range field,
438       // minus 1 (line base + line range - 1). If the desired line
439       // increment is greater than the maximum line increment, a standard
440       // opcode must be used instead of a special opcode. The "address
441       // advance" is calculated by dividing the desired address increment
442       // by the minimum_instruction_length field from the header. The
443       // special opcode is then calculated using the following formula:
444       //
445       //  opcode = (desired line increment - line_base) +
446       //           (line_range * address advance) + opcode_base
447       //
448       // If the resulting opcode is greater than 255, a standard opcode
449       // must be used instead.
450       //
451       // To decode a special opcode, subtract the opcode_base from the
452       // opcode itself to give the adjusted opcode. The amount to
453       // increment the address register is the result of the adjusted
454       // opcode divided by the line_range multiplied by the
455       // minimum_instruction_length field from the header. That is:
456       //
457       //  address increment = (adjusted opcode / line_range) *
458       //                      minimum_instruction_length
459       //
460       // The amount to increment the line register is the line_base plus
461       // the result of the adjusted opcode modulo the line_range. That is:
462       //
463       // line increment = line_base + (adjusted opcode % line_range)
464
465       uint8_t adjust_opcode = opcode - prologue->OpcodeBase;
466       uint64_t addr_offset = (adjust_opcode / prologue->LineRange) *
467                              prologue->MinInstLength;
468       int32_t line_offset = prologue->LineBase +
469                             (adjust_opcode % prologue->LineRange);
470       state.Line += line_offset;
471       state.Address += addr_offset;
472       state.appendRowToMatrix(*offset_ptr);
473     }
474   }
475
476   state.finalize();
477
478   return end_offset;
479 }
480
481 uint32_t
482 DWARFDebugLine::LineTable::lookupAddress(uint64_t address) const {
483   uint32_t unknown_index = UINT32_MAX;
484   if (Sequences.empty())
485     return unknown_index;
486   // First, find an instruction sequence containing the given address.
487   DWARFDebugLine::Sequence sequence;
488   sequence.LowPC = address;
489   SequenceIter first_seq = Sequences.begin();
490   SequenceIter last_seq = Sequences.end();
491   SequenceIter seq_pos = std::lower_bound(first_seq, last_seq, sequence,
492       DWARFDebugLine::Sequence::orderByLowPC);
493   DWARFDebugLine::Sequence found_seq;
494   if (seq_pos == last_seq) {
495     found_seq = Sequences.back();
496   } else if (seq_pos->LowPC == address) {
497     found_seq = *seq_pos;
498   } else {
499     if (seq_pos == first_seq)
500       return unknown_index;
501     found_seq = *(seq_pos - 1);
502   }
503   if (!found_seq.containsPC(address))
504     return unknown_index;
505   // Search for instruction address in the rows describing the sequence.
506   // Rows are stored in a vector, so we may use arithmetical operations with
507   // iterators.
508   DWARFDebugLine::Row row;
509   row.Address = address;
510   RowIter first_row = Rows.begin() + found_seq.FirstRowIndex;
511   RowIter last_row = Rows.begin() + found_seq.LastRowIndex;
512   RowIter row_pos = std::lower_bound(first_row, last_row, row,
513       DWARFDebugLine::Row::orderByAddress);
514   if (row_pos == last_row) {
515     return found_seq.LastRowIndex - 1;
516   }
517   uint32_t index = found_seq.FirstRowIndex + (row_pos - first_row);
518   if (row_pos->Address > address) {
519     if (row_pos == first_row)
520       return unknown_index;
521     else
522       index--;
523   }
524   return index;
525 }
526
527 bool
528 DWARFDebugLine::LineTable::getFileNameByIndex(uint64_t FileIndex,
529                                               bool NeedsAbsoluteFilePath,
530                                               std::string &Result) const {
531   if (FileIndex == 0 || FileIndex > Prologue.FileNames.size())
532     return false;
533   const FileNameEntry &Entry = Prologue.FileNames[FileIndex - 1];
534   const char *FileName = Entry.Name;
535   if (!NeedsAbsoluteFilePath ||
536       sys::path::is_absolute(FileName)) {
537     Result = FileName;
538     return true;
539   }
540   SmallString<16> FilePath;
541   uint64_t IncludeDirIndex = Entry.DirIdx;
542   // Be defensive about the contents of Entry.
543   if (IncludeDirIndex > 0 &&
544       IncludeDirIndex <= Prologue.IncludeDirectories.size()) {
545     const char *IncludeDir = Prologue.IncludeDirectories[IncludeDirIndex - 1];
546     sys::path::append(FilePath, IncludeDir);
547   }
548   sys::path::append(FilePath, FileName);
549   Result = FilePath.str();
550   return true;
551 }