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