1 : // -*- mode: C++ -*-
2 :
3 : // Copyright (c) 2010 Google Inc. All Rights Reserved.
4 : //
5 : // Redistribution and use in source and binary forms, with or without
6 : // modification, are permitted provided that the following conditions are
7 : // met:
8 : //
9 : // * Redistributions of source code must retain the above copyright
10 : // notice, this list of conditions and the following disclaimer.
11 : // * Redistributions in binary form must reproduce the above
12 : // copyright notice, this list of conditions and the following disclaimer
13 : // in the documentation and/or other materials provided with the
14 : // distribution.
15 : // * Neither the name of Google Inc. nor the names of its
16 : // contributors may be used to endorse or promote products derived from
17 : // this software without specific prior written permission.
18 : //
19 : // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 : // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 : // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 : // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23 : // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 : // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25 : // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26 : // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27 : // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 : // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29 : // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 :
31 : // CFI reader author: Jim Blandy <jimb@mozilla.com> <jimb@red-bean.com>
32 :
33 : // This file contains definitions related to the DWARF2/3 reader and
34 : // it's handler interfaces.
35 : // The DWARF2/3 specification can be found at
36 : // http://dwarf.freestandards.org and should be considered required
37 : // reading if you wish to modify the implementation.
38 : // Only a cursory attempt is made to explain terminology that is
39 : // used here, as it is much better explained in the standard documents
40 : #ifndef COMMON_DWARF_DWARF2READER_H__
41 : #define COMMON_DWARF_DWARF2READER_H__
42 :
43 : #include <list>
44 : #include <map>
45 : #include <string>
46 : #include <utility>
47 : #include <vector>
48 :
49 : #include "common/dwarf/bytereader.h"
50 : #include "common/dwarf/dwarf2enums.h"
51 : #include "common/dwarf/types.h"
52 :
53 : using namespace std;
54 :
55 : namespace dwarf2reader {
56 : struct LineStateMachine;
57 : class Dwarf2Handler;
58 : class LineInfoHandler;
59 :
60 : // This maps from a string naming a section to a pair containing a
61 : // the data for the section, and the size of the section.
62 : typedef map<string, pair<const char*, uint64> > SectionMap;
63 : typedef list<pair<enum DwarfAttribute, enum DwarfForm> > AttributeList;
64 : typedef AttributeList::iterator AttributeIterator;
65 : typedef AttributeList::const_iterator ConstAttributeIterator;
66 :
67 : struct LineInfoHeader {
68 : uint64 total_length;
69 : uint16 version;
70 : uint64 prologue_length;
71 : uint8 min_insn_length; // insn stands for instructin
72 : bool default_is_stmt; // stmt stands for statement
73 : int8 line_base;
74 : uint8 line_range;
75 : uint8 opcode_base;
76 : // Use a pointer so that signalsafe_addr2line is able to use this structure
77 : // without heap allocation problem.
78 : vector<unsigned char> *std_opcode_lengths;
79 : };
80 :
81 : class LineInfo {
82 : public:
83 :
84 : // Initializes a .debug_line reader. Buffer and buffer length point
85 : // to the beginning and length of the line information to read.
86 : // Reader is a ByteReader class that has the endianness set
87 : // properly.
88 : LineInfo(const char* buffer_, uint64 buffer_length,
89 : ByteReader* reader, LineInfoHandler* handler);
90 :
91 4723 : virtual ~LineInfo() {
92 4723 : if (header_.std_opcode_lengths) {
93 4723 : delete header_.std_opcode_lengths;
94 : }
95 4723 : }
96 :
97 : // Start processing line info, and calling callbacks in the handler.
98 : // Consumes the line number information for a single compilation unit.
99 : // Returns the number of bytes processed.
100 : uint64 Start();
101 :
102 : // Process a single line info opcode at START using the state
103 : // machine at LSM. Return true if we should define a line using the
104 : // current state of the line state machine. Place the length of the
105 : // opcode in LEN.
106 : // If LSM_PASSES_PC is non-NULL, this function also checks if the lsm
107 : // passes the address of PC. In other words, LSM_PASSES_PC will be
108 : // set to true, if the following condition is met.
109 : //
110 : // lsm's old address < PC <= lsm's new address
111 : static bool ProcessOneOpcode(ByteReader* reader,
112 : LineInfoHandler* handler,
113 : const struct LineInfoHeader &header,
114 : const char* start,
115 : struct LineStateMachine* lsm,
116 : size_t* len,
117 : uintptr pc,
118 : bool *lsm_passes_pc);
119 :
120 : private:
121 : // Reads the DWARF2/3 header for this line info.
122 : void ReadHeader();
123 :
124 : // Reads the DWARF2/3 line information
125 : void ReadLines();
126 :
127 : // The associated handler to call processing functions in
128 : LineInfoHandler* handler_;
129 :
130 : // The associated ByteReader that handles endianness issues for us
131 : ByteReader* reader_;
132 :
133 : // A DWARF2/3 line info header. This is not the same size as
134 : // in the actual file, as the one in the file may have a 32 bit or
135 : // 64 bit lengths
136 :
137 : struct LineInfoHeader header_;
138 :
139 : // buffer is the buffer for our line info, starting at exactly where
140 : // the line info to read is. after_header is the place right after
141 : // the end of the line information header.
142 : const char* buffer_;
143 : uint64 buffer_length_;
144 : const char* after_header_;
145 : };
146 :
147 : // This class is the main interface between the line info reader and
148 : // the client. The virtual functions inside this get called for
149 : // interesting events that happen during line info reading. The
150 : // default implementation does nothing
151 :
152 : class LineInfoHandler {
153 : public:
154 4723 : LineInfoHandler() { }
155 :
156 4723 : virtual ~LineInfoHandler() { }
157 :
158 : // Called when we define a directory. NAME is the directory name,
159 : // DIR_NUM is the directory number
160 0 : virtual void DefineDir(const string& name, uint32 dir_num) { }
161 :
162 : // Called when we define a filename. NAME is the filename, FILE_NUM
163 : // is the file number which is -1 if the file index is the next
164 : // index after the last numbered index (this happens when files are
165 : // dynamically defined by the line program), DIR_NUM is the
166 : // directory index for the directory name of this file, MOD_TIME is
167 : // the modification time of the file, and LENGTH is the length of
168 : // the file
169 0 : virtual void DefineFile(const string& name, int32 file_num,
170 : uint32 dir_num, uint64 mod_time,
171 0 : uint64 length) { }
172 :
173 : // Called when the line info reader has a new line, address pair
174 : // ready for us. ADDRESS is the address of the code, LENGTH is the
175 : // length of its machine code in bytes, FILE_NUM is the file number
176 : // containing the code, LINE_NUM is the line number in that file for
177 : // the code, and COLUMN_NUM is the column number the code starts at,
178 : // if we know it (0 otherwise).
179 0 : virtual void AddLine(uint64 address, uint64 length,
180 0 : uint32 file_num, uint32 line_num, uint32 column_num) { }
181 : };
182 :
183 : // The base of DWARF2/3 debug info is a DIE (Debugging Information
184 : // Entry.
185 : // DWARF groups DIE's into a tree and calls the root of this tree a
186 : // "compilation unit". Most of the time, there is one compilation
187 : // unit in the .debug_info section for each file that had debug info
188 : // generated.
189 : // Each DIE consists of
190 :
191 : // 1. a tag specifying a thing that is being described (ie
192 : // DW_TAG_subprogram for functions, DW_TAG_variable for variables, etc
193 : // 2. attributes (such as DW_AT_location for location in memory,
194 : // DW_AT_name for name), and data for each attribute.
195 : // 3. A flag saying whether the DIE has children or not
196 :
197 : // In order to gain some amount of compression, the format of
198 : // each DIE (tag name, attributes and data forms for the attributes)
199 : // are stored in a separate table called the "abbreviation table".
200 : // This is done because a large number of DIEs have the exact same tag
201 : // and list of attributes, but different data for those attributes.
202 : // As a result, the .debug_info section is just a stream of data, and
203 : // requires reading of the .debug_abbrev section to say what the data
204 : // means.
205 :
206 : // As a warning to the user, it should be noted that the reason for
207 : // using absolute offsets from the beginning of .debug_info is that
208 : // DWARF2/3 supports referencing DIE's from other DIE's by their offset
209 : // from either the current compilation unit start, *or* the beginning
210 : // of the .debug_info section. This means it is possible to reference
211 : // a DIE in one compilation unit from a DIE in another compilation
212 : // unit. This style of reference is usually used to eliminate
213 : // duplicated information that occurs across compilation
214 : // units, such as base types, etc. GCC 3.4+ support this with
215 : // -feliminate-dwarf2-dups. Other toolchains will sometimes do
216 : // duplicate elimination in the linker.
217 :
218 : class CompilationUnit {
219 : public:
220 :
221 : // Initialize a compilation unit. This requires a map of sections,
222 : // the offset of this compilation unit in the .debug_info section, a
223 : // ByteReader, and a Dwarf2Handler class to call callbacks in.
224 : CompilationUnit(const SectionMap& sections, uint64 offset,
225 : ByteReader* reader, Dwarf2Handler* handler);
226 4773 : virtual ~CompilationUnit() {
227 4773 : if (abbrevs_) delete abbrevs_;
228 4773 : }
229 :
230 : // Begin reading a Dwarf2 compilation unit, and calling the
231 : // callbacks in the Dwarf2Handler
232 :
233 : // Return the full length of the compilation unit, including
234 : // headers. This plus the starting offset passed to the constructor
235 : // is the offset of the end of the compilation unit --- and the
236 : // start of the next compilation unit, if there is one.
237 : uint64 Start();
238 :
239 : private:
240 :
241 : // This struct represents a single DWARF2/3 abbreviation
242 : // The abbreviation tells how to read a DWARF2/3 DIE, and consist of a
243 : // tag and a list of attributes, as well as the data form of each attribute.
244 1826322 : struct Abbrev {
245 : uint64 number;
246 : enum DwarfTag tag;
247 : bool has_children;
248 : AttributeList attributes;
249 : };
250 :
251 : // A DWARF2/3 compilation unit header. This is not the same size as
252 : // in the actual file, as the one in the file may have a 32 bit or
253 : // 64 bit length.
254 : struct CompilationUnitHeader {
255 : uint64 length;
256 : uint16 version;
257 : uint64 abbrev_offset;
258 : uint8 address_size;
259 : } header_;
260 :
261 : // Reads the DWARF2/3 header for this compilation unit.
262 : void ReadHeader();
263 :
264 : // Reads the DWARF2/3 abbreviations for this compilation unit
265 : void ReadAbbrevs();
266 :
267 : // Processes a single DIE for this compilation unit and return a new
268 : // pointer just past the end of it
269 : const char* ProcessDIE(uint64 dieoffset,
270 : const char* start,
271 : const Abbrev& abbrev);
272 :
273 : // Processes a single attribute and return a new pointer just past the
274 : // end of it
275 : const char* ProcessAttribute(uint64 dieoffset,
276 : const char* start,
277 : enum DwarfAttribute attr,
278 : enum DwarfForm form);
279 :
280 : // Processes all DIEs for this compilation unit
281 : void ProcessDIEs();
282 :
283 : // Skips the die with attributes specified in ABBREV starting at
284 : // START, and return the new place to position the stream to.
285 : const char* SkipDIE(const char* start,
286 : const Abbrev& abbrev);
287 :
288 : // Skips the attribute starting at START, with FORM, and return the
289 : // new place to position the stream to.
290 : const char* SkipAttribute(const char* start,
291 : enum DwarfForm form);
292 :
293 : // Offset from section start is the offset of this compilation unit
294 : // from the beginning of the .debug_info section.
295 : uint64 offset_from_section_start_;
296 :
297 : // buffer is the buffer for our CU, starting at .debug_info + offset
298 : // passed in from constructor.
299 : // after_header points to right after the compilation unit header.
300 : const char* buffer_;
301 : uint64 buffer_length_;
302 : const char* after_header_;
303 :
304 : // The associated ByteReader that handles endianness issues for us
305 : ByteReader* reader_;
306 :
307 : // The map of sections in our file to buffers containing their data
308 : const SectionMap& sections_;
309 :
310 : // The associated handler to call processing functions in
311 : Dwarf2Handler* handler_;
312 :
313 : // Set of DWARF2/3 abbreviations for this compilation unit. Indexed
314 : // by abbreviation number, which means that abbrevs_[0] is not
315 : // valid.
316 : vector<Abbrev>* abbrevs_;
317 :
318 : // String section buffer and length, if we have a string section.
319 : // This is here to avoid doing a section lookup for strings in
320 : // ProcessAttribute, which is in the hot path for DWARF2 reading.
321 : const char* string_buffer_;
322 : uint64 string_buffer_length_;
323 : };
324 :
325 : // This class is the main interface between the reader and the
326 : // client. The virtual functions inside this get called for
327 : // interesting events that happen during DWARF2 reading.
328 : // The default implementation skips everything.
329 :
330 : class Dwarf2Handler {
331 : public:
332 4773 : Dwarf2Handler() { }
333 :
334 4773 : virtual ~Dwarf2Handler() { }
335 :
336 : // Start to process a compilation unit at OFFSET from the beginning of the
337 : // .debug_info section. Return false if you would like to skip this
338 : // compilation unit.
339 0 : virtual bool StartCompilationUnit(uint64 offset, uint8 address_size,
340 : uint8 offset_size, uint64 cu_length,
341 0 : uint8 dwarf_version) { return false; }
342 :
343 : // Start to process a DIE at OFFSET from the beginning of the .debug_info
344 : // section. Return false if you would like to skip this DIE.
345 0 : virtual bool StartDIE(uint64 offset, enum DwarfTag tag,
346 0 : const AttributeList& attrs) { return false; }
347 :
348 : // Called when we have an attribute with unsigned data to give to our
349 : // handler. The attribute is for the DIE at OFFSET from the beginning of the
350 : // .debug_info section. Its name is ATTR, its form is FORM, and its value is
351 : // DATA.
352 0 : virtual void ProcessAttributeUnsigned(uint64 offset,
353 : enum DwarfAttribute attr,
354 : enum DwarfForm form,
355 0 : uint64 data) { }
356 :
357 : // Called when we have an attribute with signed data to give to our handler.
358 : // The attribute is for the DIE at OFFSET from the beginning of the
359 : // .debug_info section. Its name is ATTR, its form is FORM, and its value is
360 : // DATA.
361 0 : virtual void ProcessAttributeSigned(uint64 offset,
362 : enum DwarfAttribute attr,
363 : enum DwarfForm form,
364 0 : int64 data) { }
365 :
366 : // Called when we have an attribute whose value is a reference to
367 : // another DIE. The attribute belongs to the DIE at OFFSET from the
368 : // beginning of the .debug_info section. Its name is ATTR, its form
369 : // is FORM, and the offset of the DIE being referred to from the
370 : // beginning of the .debug_info section is DATA.
371 0 : virtual void ProcessAttributeReference(uint64 offset,
372 : enum DwarfAttribute attr,
373 : enum DwarfForm form,
374 0 : uint64 data) { }
375 :
376 : // Called when we have an attribute with a buffer of data to give to our
377 : // handler. The attribute is for the DIE at OFFSET from the beginning of the
378 : // .debug_info section. Its name is ATTR, its form is FORM, DATA points to
379 : // the buffer's contents, and its length in bytes is LENGTH. The buffer is
380 : // owned by the caller, not the callee, and may not persist for very long.
381 : // If you want the data to be available later, it needs to be copied.
382 0 : virtual void ProcessAttributeBuffer(uint64 offset,
383 : enum DwarfAttribute attr,
384 : enum DwarfForm form,
385 : const char* data,
386 0 : uint64 len) { }
387 :
388 : // Called when we have an attribute with string data to give to our handler.
389 : // The attribute is for the DIE at OFFSET from the beginning of the
390 : // .debug_info section. Its name is ATTR, its form is FORM, and its value is
391 : // DATA.
392 0 : virtual void ProcessAttributeString(uint64 offset,
393 : enum DwarfAttribute attr,
394 : enum DwarfForm form,
395 0 : const string& data) { }
396 :
397 : // Called when we have an attribute whose value is the 64-bit signature
398 : // of a type unit in the .debug_types section. OFFSET is the offset of
399 : // the DIE whose attribute we're reporting. ATTR and FORM are the
400 : // attribute's name and form. SIGNATURE is the type unit's signature.
401 0 : virtual void ProcessAttributeSignature(uint64 offset,
402 : enum DwarfAttribute attr,
403 : enum DwarfForm form,
404 0 : uint64 signature) { }
405 :
406 : // Called when finished processing the DIE at OFFSET.
407 : // Because DWARF2/3 specifies a tree of DIEs, you may get starts
408 : // before ends of the previous DIE, as we process children before
409 : // ending the parent.
410 0 : virtual void EndDIE(uint64 offset) { }
411 :
412 : };
413 :
414 : // This class is a reader for DWARF's Call Frame Information. CFI
415 : // describes how to unwind stack frames --- even for functions that do
416 : // not follow fixed conventions for saving registers, whose frame size
417 : // varies as they execute, etc.
418 : //
419 : // CFI describes, at each machine instruction, how to compute the
420 : // stack frame's base address, how to find the return address, and
421 : // where to find the saved values of the caller's registers (if the
422 : // callee has stashed them somewhere to free up the registers for its
423 : // own use).
424 : //
425 : // For example, suppose we have a function whose machine code looks
426 : // like this (imagine an assembly language that looks like C, for a
427 : // machine with 32-bit registers, and a stack that grows towards lower
428 : // addresses):
429 : //
430 : // func: ; entry point; return address at sp
431 : // func+0: sp = sp - 16 ; allocate space for stack frame
432 : // func+1: sp[12] = r0 ; save r0 at sp+12
433 : // ... ; other code, not frame-related
434 : // func+10: sp -= 4; *sp = x ; push some x on the stack
435 : // ... ; other code, not frame-related
436 : // func+20: r0 = sp[16] ; restore saved r0
437 : // func+21: sp += 20 ; pop whole stack frame
438 : // func+22: pc = *sp; sp += 4 ; pop return address and jump to it
439 : //
440 : // DWARF CFI is (a very compressed representation of) a table with a
441 : // row for each machine instruction address and a column for each
442 : // register showing how to restore it, if possible.
443 : //
444 : // A special column named "CFA", for "Canonical Frame Address", tells how
445 : // to compute the base address of the frame; registers' entries may
446 : // refer to the CFA in describing where the registers are saved.
447 : //
448 : // Another special column, named "RA", represents the return address.
449 : //
450 : // For example, here is a complete (uncompressed) table describing the
451 : // function above:
452 : //
453 : // insn cfa r0 r1 ... ra
454 : // =======================================
455 : // func+0: sp cfa[0]
456 : // func+1: sp+16 cfa[0]
457 : // func+2: sp+16 cfa[-4] cfa[0]
458 : // func+11: sp+20 cfa[-4] cfa[0]
459 : // func+21: sp+20 cfa[0]
460 : // func+22: sp cfa[0]
461 : //
462 : // Some things to note here:
463 : //
464 : // - Each row describes the state of affairs *before* executing the
465 : // instruction at the given address. Thus, the row for func+0
466 : // describes the state before we allocate the stack frame. In the
467 : // next row, the formula for computing the CFA has changed,
468 : // reflecting that allocation.
469 : //
470 : // - The other entries are written in terms of the CFA; this allows
471 : // them to remain unchanged as the stack pointer gets bumped around.
472 : // For example, the rule for recovering the return address (the "ra"
473 : // column) remains unchanged throughout the function, even as the
474 : // stack pointer takes on three different offsets from the return
475 : // address.
476 : //
477 : // - Although we haven't shown it, most calling conventions designate
478 : // "callee-saves" and "caller-saves" registers. The callee must
479 : // preserve the values of callee-saves registers; if it uses them,
480 : // it must save their original values somewhere, and restore them
481 : // before it returns. In contrast, the callee is free to trash
482 : // caller-saves registers; if the callee uses these, it will
483 : // probably not bother to save them anywhere, and the CFI will
484 : // probably mark their values as "unrecoverable".
485 : //
486 : // (However, since the caller cannot assume the callee was going to
487 : // save them, caller-saves registers are probably dead in the caller
488 : // anyway, so compilers usually don't generate CFA for caller-saves
489 : // registers.)
490 : //
491 : // - Exactly where the CFA points is a matter of convention that
492 : // depends on the architecture and ABI in use. In the example, the
493 : // CFA is the value the stack pointer had upon entry to the
494 : // function, pointing at the saved return address. But on the x86,
495 : // the call frame information generated by GCC follows the
496 : // convention that the CFA is the address *after* the saved return
497 : // address.
498 : //
499 : // But by definition, the CFA remains constant throughout the
500 : // lifetime of the frame. This makes it a useful value for other
501 : // columns to refer to. It is also gives debuggers a useful handle
502 : // for identifying a frame.
503 : //
504 : // If you look at the table above, you'll notice that a given entry is
505 : // often the same as the one immediately above it: most instructions
506 : // change only one or two aspects of the stack frame, if they affect
507 : // it at all. The DWARF format takes advantage of this fact, and
508 : // reduces the size of the data by mentioning only the addresses and
509 : // columns at which changes take place. So for the above, DWARF CFI
510 : // data would only actually mention the following:
511 : //
512 : // insn cfa r0 r1 ... ra
513 : // =======================================
514 : // func+0: sp cfa[0]
515 : // func+1: sp+16
516 : // func+2: cfa[-4]
517 : // func+11: sp+20
518 : // func+21: r0
519 : // func+22: sp
520 : //
521 : // In fact, this is the way the parser reports CFI to the consumer: as
522 : // a series of statements of the form, "At address X, column Y changed
523 : // to Z," and related conventions for describing the initial state.
524 : //
525 : // Naturally, it would be impractical to have to scan the entire
526 : // program's CFI, noting changes as we go, just to recover the
527 : // unwinding rules in effect at one particular instruction. To avoid
528 : // this, CFI data is grouped into "entries", each of which covers a
529 : // specified range of addresses and begins with a complete statement
530 : // of the rules for all recoverable registers at that starting
531 : // address. Each entry typically covers a single function.
532 : //
533 : // Thus, to compute the contents of a given row of the table --- that
534 : // is, rules for recovering the CFA, RA, and registers at a given
535 : // instruction --- the consumer should find the entry that covers that
536 : // instruction's address, start with the initial state supplied at the
537 : // beginning of the entry, and work forward until it has processed all
538 : // the changes up to and including those for the present instruction.
539 : //
540 : // There are seven kinds of rules that can appear in an entry of the
541 : // table:
542 : //
543 : // - "undefined": The given register is not preserved by the callee;
544 : // its value cannot be recovered.
545 : //
546 : // - "same value": This register has the same value it did in the callee.
547 : //
548 : // - offset(N): The register is saved at offset N from the CFA.
549 : //
550 : // - val_offset(N): The value the register had in the caller is the
551 : // CFA plus offset N. (This is usually only useful for describing
552 : // the stack pointer.)
553 : //
554 : // - register(R): The register's value was saved in another register R.
555 : //
556 : // - expression(E): Evaluating the DWARF expression E using the
557 : // current frame's registers' values yields the address at which the
558 : // register was saved.
559 : //
560 : // - val_expression(E): Evaluating the DWARF expression E using the
561 : // current frame's registers' values yields the value the register
562 : // had in the caller.
563 :
564 : class CallFrameInfo {
565 : public:
566 : // The different kinds of entries one finds in CFI. Used internally,
567 : // and for error reporting.
568 : enum EntryKind { kUnknown, kCIE, kFDE, kTerminator };
569 :
570 : // The handler class to which the parser hands the parsed call frame
571 : // information. Defined below.
572 : class Handler;
573 :
574 : // A reporter class, which CallFrameInfo uses to report errors
575 : // encountered while parsing call frame information. Defined below.
576 : class Reporter;
577 :
578 : // Create a DWARF CFI parser. BUFFER points to the contents of the
579 : // .debug_frame section to parse; BUFFER_LENGTH is its length in bytes.
580 : // REPORTER is an error reporter the parser should use to report
581 : // problems. READER is a ByteReader instance that has the endianness and
582 : // address size set properly. Report the data we find to HANDLER.
583 : //
584 : // This class can also parse Linux C++ exception handling data, as found
585 : // in '.eh_frame' sections. This data is a variant of DWARF CFI that is
586 : // placed in loadable segments so that it is present in the program's
587 : // address space, and is interpreted by the C++ runtime to search the
588 : // call stack for a handler interested in the exception being thrown,
589 : // actually pop the frames, and find cleanup code to run.
590 : //
591 : // There are two differences between the call frame information described
592 : // in the DWARF standard and the exception handling data Linux places in
593 : // the .eh_frame section:
594 : //
595 : // - Exception handling data uses uses a different format for call frame
596 : // information entry headers. The distinguished CIE id, the way FDEs
597 : // refer to their CIEs, and the way the end of the series of entries is
598 : // determined are all slightly different.
599 : //
600 : // If the constructor's EH_FRAME argument is true, then the
601 : // CallFrameInfo parses the entry headers as Linux C++ exception
602 : // handling data. If EH_FRAME is false or omitted, the CallFrameInfo
603 : // parses standard DWARF call frame information.
604 : //
605 : // - Linux C++ exception handling data uses CIE augmentation strings
606 : // beginning with 'z' to specify the presence of additional data after
607 : // the CIE and FDE headers and special encodings used for addresses in
608 : // frame description entries.
609 : //
610 : // CallFrameInfo can handle 'z' augmentations in either DWARF CFI or
611 : // exception handling data if you have supplied READER with the base
612 : // addresses needed to interpret the pointer encodings that 'z'
613 : // augmentations can specify. See the ByteReader interface for details
614 : // about the base addresses. See the CallFrameInfo::Handler interface
615 : // for details about the additional information one might find in
616 : // 'z'-augmented data.
617 : //
618 : // Thus:
619 : //
620 : // - If you are parsing standard DWARF CFI, as found in a .debug_frame
621 : // section, you should pass false for the EH_FRAME argument, or omit
622 : // it, and you need not worry about providing READER with the
623 : // additional base addresses.
624 : //
625 : // - If you want to parse Linux C++ exception handling data from a
626 : // .eh_frame section, you should pass EH_FRAME as true, and call
627 : // READER's Set*Base member functions before calling our Start method.
628 : //
629 : // - If you want to parse DWARF CFI that uses the 'z' augmentations
630 : // (although I don't think any toolchain ever emits such data), you
631 : // could pass false for EH_FRAME, but call READER's Set*Base members.
632 : //
633 : // The extensions the Linux C++ ABI makes to DWARF for exception
634 : // handling are described here, rather poorly:
635 : // http://refspecs.linux-foundation.org/LSB_4.0.0/LSB-Core-generic/LSB-Core-generic/dwarfext.html
636 : // http://refspecs.linux-foundation.org/LSB_4.0.0/LSB-Core-generic/LSB-Core-generic/ehframechpt.html
637 : //
638 : // The mechanics of C++ exception handling, personality routines,
639 : // and language-specific data areas are described here, rather nicely:
640 : // http://www.codesourcery.com/public/cxx-abi/abi-eh.html
641 248 : CallFrameInfo(const char *buffer, size_t buffer_length,
642 : ByteReader *reader, Handler *handler, Reporter *reporter,
643 : bool eh_frame = false)
644 : : buffer_(buffer), buffer_length_(buffer_length),
645 : reader_(reader), handler_(handler), reporter_(reporter),
646 248 : eh_frame_(eh_frame) { }
647 :
648 248 : ~CallFrameInfo() { }
649 :
650 : // Parse the entries in BUFFER, reporting what we find to HANDLER.
651 : // Return true if we reach the end of the section successfully, or
652 : // false if we encounter an error.
653 : bool Start();
654 :
655 : // Return the textual name of KIND. For error reporting.
656 : static const char *KindName(EntryKind kind);
657 :
658 : private:
659 :
660 : struct CIE;
661 :
662 : // A CFI entry, either an FDE or a CIE.
663 : struct Entry {
664 : // The starting offset of the entry in the section, for error
665 : // reporting.
666 : size_t offset;
667 :
668 : // The start of this entry in the buffer.
669 : const char *start;
670 :
671 : // Which kind of entry this is.
672 : //
673 : // We want to be able to use this for error reporting even while we're
674 : // in the midst of parsing. Error reporting code may assume that kind,
675 : // offset, and start fields are valid, although kind may be kUnknown.
676 : EntryKind kind;
677 :
678 : // The end of this entry's common prologue (initial length and id), and
679 : // the start of this entry's kind-specific fields.
680 : const char *fields;
681 :
682 : // The start of this entry's instructions.
683 : const char *instructions;
684 :
685 : // The address past the entry's last byte in the buffer. (Note that
686 : // since offset points to the entry's initial length field, and the
687 : // length field is the number of bytes after that field, this is not
688 : // simply buffer_ + offset + length.)
689 : const char *end;
690 :
691 : // For both DWARF CFI and .eh_frame sections, this is the CIE id in a
692 : // CIE, and the offset of the associated CIE in an FDE.
693 : uint64 id;
694 :
695 : // The CIE that applies to this entry, if we've parsed it. If this is a
696 : // CIE, then this field points to this structure.
697 : CIE *cie;
698 : };
699 :
700 : // A common information entry (CIE).
701 : struct CIE: public Entry {
702 : uint8 version; // CFI data version number
703 : string augmentation; // vendor format extension markers
704 : uint64 code_alignment_factor; // scale for code address adjustments
705 : int data_alignment_factor; // scale for stack pointer adjustments
706 : unsigned return_address_register; // which register holds the return addr
707 :
708 : // True if this CIE includes Linux C++ ABI 'z' augmentation data.
709 : bool has_z_augmentation;
710 :
711 : // Parsed 'z' augmentation data. These are meaningful only if
712 : // has_z_augmentation is true.
713 : bool has_z_lsda; // The 'z' augmentation included 'L'.
714 : bool has_z_personality; // The 'z' augmentation included 'P'.
715 : bool has_z_signal_frame; // The 'z' augmentation included 'S'.
716 :
717 : // If has_z_lsda is true, this is the encoding to be used for language-
718 : // specific data area pointers in FDEs.
719 : DwarfPointerEncoding lsda_encoding;
720 :
721 : // If has_z_personality is true, this is the encoding used for the
722 : // personality routine pointer in the augmentation data.
723 : DwarfPointerEncoding personality_encoding;
724 :
725 : // If has_z_personality is true, this is the address of the personality
726 : // routine --- or, if personality_encoding & DW_EH_PE_indirect, the
727 : // address where the personality routine's address is stored.
728 : uint64 personality_address;
729 :
730 : // This is the encoding used for addresses in the FDE header and
731 : // in DW_CFA_set_loc instructions. This is always valid, whether
732 : // or not we saw a 'z' augmentation string; its default value is
733 : // DW_EH_PE_absptr, which is what normal DWARF CFI uses.
734 : DwarfPointerEncoding pointer_encoding;
735 : };
736 :
737 : // A frame description entry (FDE).
738 : struct FDE: public Entry {
739 : uint64 address; // start address of described code
740 : uint64 size; // size of described code, in bytes
741 :
742 : // If cie->has_z_lsda is true, then this is the language-specific data
743 : // area's address --- or its address's address, if cie->lsda_encoding
744 : // has the DW_EH_PE_indirect bit set.
745 : uint64 lsda_address;
746 : };
747 :
748 : // Internal use.
749 : class Rule;
750 : class UndefinedRule;
751 : class SameValueRule;
752 : class OffsetRule;
753 : class ValOffsetRule;
754 : class RegisterRule;
755 : class ExpressionRule;
756 : class ValExpressionRule;
757 : class RuleMap;
758 : class State;
759 :
760 : // Parse the initial length and id of a CFI entry, either a CIE, an FDE,
761 : // or a .eh_frame end-of-data mark. CURSOR points to the beginning of the
762 : // data to parse. On success, populate ENTRY as appropriate, and return
763 : // true. On failure, report the problem, and return false. Even if we
764 : // return false, set ENTRY->end to the first byte after the entry if we
765 : // were able to figure that out, or NULL if we weren't.
766 : bool ReadEntryPrologue(const char *cursor, Entry *entry);
767 :
768 : // Parse the fields of a CIE after the entry prologue, including any 'z'
769 : // augmentation data. Assume that the 'Entry' fields of CIE are
770 : // populated; use CIE->fields and CIE->end as the start and limit for
771 : // parsing. On success, populate the rest of *CIE, and return true; on
772 : // failure, report the problem and return false.
773 : bool ReadCIEFields(CIE *cie);
774 :
775 : // Parse the fields of an FDE after the entry prologue, including any 'z'
776 : // augmentation data. Assume that the 'Entry' fields of *FDE are
777 : // initialized; use FDE->fields and FDE->end as the start and limit for
778 : // parsing. Assume that FDE->cie is fully initialized. On success,
779 : // populate the rest of *FDE, and return true; on failure, report the
780 : // problem and return false.
781 : bool ReadFDEFields(FDE *fde);
782 :
783 : // Report that ENTRY is incomplete, and return false. This is just a
784 : // trivial wrapper for invoking reporter_->Incomplete; it provides a
785 : // little brevity.
786 : bool ReportIncomplete(Entry *entry);
787 :
788 : // Return true if ENCODING has the DW_EH_PE_indirect bit set.
789 : static bool IsIndirectEncoding(DwarfPointerEncoding encoding) {
790 : return encoding & DW_EH_PE_indirect;
791 : }
792 :
793 : // The contents of the DWARF .debug_info section we're parsing.
794 : const char *buffer_;
795 : size_t buffer_length_;
796 :
797 : // For reading multi-byte values with the appropriate endianness.
798 : ByteReader *reader_;
799 :
800 : // The handler to which we should report the data we find.
801 : Handler *handler_;
802 :
803 : // For reporting problems in the info we're parsing.
804 : Reporter *reporter_;
805 :
806 : // True if we are processing .eh_frame-format data.
807 : bool eh_frame_;
808 : };
809 :
810 : // The handler class for CallFrameInfo. The a CFI parser calls the
811 : // member functions of a handler object to report the data it finds.
812 : class CallFrameInfo::Handler {
813 : public:
814 : // The pseudo-register number for the canonical frame address.
815 : enum { kCFARegister = -1 };
816 :
817 248 : Handler() { }
818 248 : virtual ~Handler() { }
819 :
820 : // The parser has found CFI for the machine code at ADDRESS,
821 : // extending for LENGTH bytes. OFFSET is the offset of the frame
822 : // description entry in the section, for use in error messages.
823 : // VERSION is the version number of the CFI format. AUGMENTATION is
824 : // a string describing any producer-specific extensions present in
825 : // the data. RETURN_ADDRESS is the number of the register that holds
826 : // the address to which the function should return.
827 : //
828 : // Entry should return true to process this CFI, or false to skip to
829 : // the next entry.
830 : //
831 : // The parser invokes Entry for each Frame Description Entry (FDE)
832 : // it finds. The parser doesn't report Common Information Entries
833 : // to the handler explicitly; instead, if the handler elects to
834 : // process a given FDE, the parser reiterates the appropriate CIE's
835 : // contents at the beginning of the FDE's rules.
836 : virtual bool Entry(size_t offset, uint64 address, uint64 length,
837 : uint8 version, const string &augmentation,
838 : unsigned return_address) = 0;
839 :
840 : // When the Entry function returns true, the parser calls these
841 : // handler functions repeatedly to describe the rules for recovering
842 : // registers at each instruction in the given range of machine code.
843 : // Immediately after a call to Entry, the handler should assume that
844 : // the rule for each callee-saves register is "unchanged" --- that
845 : // is, that the register still has the value it had in the caller.
846 : //
847 : // If a *Rule function returns true, we continue processing this entry's
848 : // instructions. If a *Rule function returns false, we stop evaluating
849 : // instructions, and skip to the next entry. Either way, we call End
850 : // before going on to the next entry.
851 : //
852 : // In all of these functions, if the REG parameter is kCFARegister, then
853 : // the rule describes how to find the canonical frame address.
854 : // kCFARegister may be passed as a BASE_REGISTER argument, meaning that
855 : // the canonical frame address should be used as the base address for the
856 : // computation. All other REG values will be positive.
857 :
858 : // At ADDRESS, register REG's value is not recoverable.
859 : virtual bool UndefinedRule(uint64 address, int reg) = 0;
860 :
861 : // At ADDRESS, register REG's value is the same as that it had in
862 : // the caller.
863 : virtual bool SameValueRule(uint64 address, int reg) = 0;
864 :
865 : // At ADDRESS, register REG has been saved at offset OFFSET from
866 : // BASE_REGISTER.
867 : virtual bool OffsetRule(uint64 address, int reg,
868 : int base_register, long offset) = 0;
869 :
870 : // At ADDRESS, the caller's value of register REG is the current
871 : // value of BASE_REGISTER plus OFFSET. (This rule doesn't provide an
872 : // address at which the register's value is saved.)
873 : virtual bool ValOffsetRule(uint64 address, int reg,
874 : int base_register, long offset) = 0;
875 :
876 : // At ADDRESS, register REG has been saved in BASE_REGISTER. This differs
877 : // from ValOffsetRule(ADDRESS, REG, BASE_REGISTER, 0), in that
878 : // BASE_REGISTER is the "home" for REG's saved value: if you want to
879 : // assign to a variable whose home is REG in the calling frame, you
880 : // should put the value in BASE_REGISTER.
881 : virtual bool RegisterRule(uint64 address, int reg, int base_register) = 0;
882 :
883 : // At ADDRESS, the DWARF expression EXPRESSION yields the address at
884 : // which REG was saved.
885 : virtual bool ExpressionRule(uint64 address, int reg,
886 : const string &expression) = 0;
887 :
888 : // At ADDRESS, the DWARF expression EXPRESSION yields the caller's
889 : // value for REG. (This rule doesn't provide an address at which the
890 : // register's value is saved.)
891 : virtual bool ValExpressionRule(uint64 address, int reg,
892 : const string &expression) = 0;
893 :
894 : // Indicate that the rules for the address range reported by the
895 : // last call to Entry are complete. End should return true if
896 : // everything is okay, or false if an error has occurred and parsing
897 : // should stop.
898 : virtual bool End() = 0;
899 :
900 : // Handler functions for Linux C++ exception handling data. These are
901 : // only called if the data includes 'z' augmentation strings.
902 :
903 : // The Linux C++ ABI uses an extension of the DWARF CFI format to
904 : // walk the stack to propagate exceptions from the throw to the
905 : // appropriate catch, and do the appropriate cleanups along the way.
906 : // CFI entries used for exception handling have two additional data
907 : // associated with them:
908 : //
909 : // - The "language-specific data area" describes which exception
910 : // types the function has 'catch' clauses for, and indicates how
911 : // to go about re-entering the function at the appropriate catch
912 : // clause. If the exception is not caught, it describes the
913 : // destructors that must run before the frame is popped.
914 : //
915 : // - The "personality routine" is responsible for interpreting the
916 : // language-specific data area's contents, and deciding whether
917 : // the exception should continue to propagate down the stack,
918 : // perhaps after doing some cleanup for this frame, or whether the
919 : // exception will be caught here.
920 : //
921 : // In principle, the language-specific data area is opaque to
922 : // everybody but the personality routine. In practice, these values
923 : // may be useful or interesting to readers with extra context, and
924 : // we have to at least skip them anyway, so we might as well report
925 : // them to the handler.
926 :
927 : // This entry's exception handling personality routine's address is
928 : // ADDRESS. If INDIRECT is true, then ADDRESS is the address at
929 : // which the routine's address is stored. The default definition for
930 : // this handler function simply returns true, allowing parsing of
931 : // the entry to continue.
932 39418 : virtual bool PersonalityRoutine(uint64 address, bool indirect) {
933 39418 : return true;
934 : }
935 :
936 : // This entry's language-specific data area (LSDA) is located at
937 : // ADDRESS. If INDIRECT is true, then ADDRESS is the address at
938 : // which the area's address is stored. The default definition for
939 : // this handler function simply returns true, allowing parsing of
940 : // the entry to continue.
941 39418 : virtual bool LanguageSpecificDataArea(uint64 address, bool indirect) {
942 39418 : return true;
943 : }
944 :
945 : // This entry describes a signal trampoline --- this frame is the
946 : // caller of a signal handler. The default definition for this
947 : // handler function simply returns true, allowing parsing of the
948 : // entry to continue.
949 : //
950 : // The best description of the rationale for and meaning of signal
951 : // trampoline CFI entries seems to be in the GCC bug database:
952 : // http://gcc.gnu.org/bugzilla/show_bug.cgi?id=26208
953 0 : virtual bool SignalHandler() { return true; }
954 : };
955 :
956 : // The CallFrameInfo class makes calls on an instance of this class to
957 : // report errors or warn about problems in the data it is parsing. The
958 : // default definitions of these methods print a message to stderr, but
959 : // you can make a derived class that overrides them.
960 : class CallFrameInfo::Reporter {
961 : public:
962 : // Create an error reporter which attributes troubles to the section
963 : // named SECTION in FILENAME.
964 : //
965 : // Normally SECTION would be .debug_frame, but the Mac puts CFI data
966 : // in a Mach-O section named __debug_frame. If we support
967 : // Linux-style exception handling data, we could be reading an
968 : // .eh_frame section.
969 248 : Reporter(const string &filename,
970 : const string §ion = ".debug_frame")
971 248 : : filename_(filename), section_(section) { }
972 248 : virtual ~Reporter() { }
973 :
974 : // The CFI entry at OFFSET ends too early to be well-formed. KIND
975 : // indicates what kind of entry it is; KIND can be kUnknown if we
976 : // haven't parsed enough of the entry to tell yet.
977 : virtual void Incomplete(uint64 offset, CallFrameInfo::EntryKind kind);
978 :
979 : // The .eh_frame data has a four-byte zero at OFFSET where the next
980 : // entry's length would be; this is a terminator. However, the buffer
981 : // length as given to the CallFrameInfo constructor says there should be
982 : // more data.
983 : virtual void EarlyEHTerminator(uint64 offset);
984 :
985 : // The FDE at OFFSET refers to the CIE at CIE_OFFSET, but the
986 : // section is not that large.
987 : virtual void CIEPointerOutOfRange(uint64 offset, uint64 cie_offset);
988 :
989 : // The FDE at OFFSET refers to the CIE at CIE_OFFSET, but the entry
990 : // there is not a CIE.
991 : virtual void BadCIEId(uint64 offset, uint64 cie_offset);
992 :
993 : // The FDE at OFFSET refers to a CIE with version number VERSION,
994 : // which we don't recognize. We cannot parse DWARF CFI if it uses
995 : // a version number we don't recognize.
996 : virtual void UnrecognizedVersion(uint64 offset, int version);
997 :
998 : // The FDE at OFFSET refers to a CIE with augmentation AUGMENTATION,
999 : // which we don't recognize. We cannot parse DWARF CFI if it uses
1000 : // augmentations we don't recognize.
1001 : virtual void UnrecognizedAugmentation(uint64 offset,
1002 : const string &augmentation);
1003 :
1004 : // The pointer encoding ENCODING, specified by the CIE at OFFSET, is not
1005 : // a valid encoding.
1006 : virtual void InvalidPointerEncoding(uint64 offset, uint8 encoding);
1007 :
1008 : // The pointer encoding ENCODING, specified by the CIE at OFFSET, depends
1009 : // on a base address which has not been supplied.
1010 : virtual void UnusablePointerEncoding(uint64 offset, uint8 encoding);
1011 :
1012 : // The CIE at OFFSET contains a DW_CFA_restore instruction at
1013 : // INSN_OFFSET, which may not appear in a CIE.
1014 : virtual void RestoreInCIE(uint64 offset, uint64 insn_offset);
1015 :
1016 : // The entry at OFFSET, of kind KIND, has an unrecognized
1017 : // instruction at INSN_OFFSET.
1018 : virtual void BadInstruction(uint64 offset, CallFrameInfo::EntryKind kind,
1019 : uint64 insn_offset);
1020 :
1021 : // The instruction at INSN_OFFSET in the entry at OFFSET, of kind
1022 : // KIND, establishes a rule that cites the CFA, but we have not
1023 : // established a CFA rule yet.
1024 : virtual void NoCFARule(uint64 offset, CallFrameInfo::EntryKind kind,
1025 : uint64 insn_offset);
1026 :
1027 : // The instruction at INSN_OFFSET in the entry at OFFSET, of kind
1028 : // KIND, is a DW_CFA_restore_state instruction, but the stack of
1029 : // saved states is empty.
1030 : virtual void EmptyStateStack(uint64 offset, CallFrameInfo::EntryKind kind,
1031 : uint64 insn_offset);
1032 :
1033 : // The DW_CFA_remember_state instruction at INSN_OFFSET in the entry
1034 : // at OFFSET, of kind KIND, would restore a state that has no CFA
1035 : // rule, whereas the current state does have a CFA rule. This is
1036 : // bogus input, which the CallFrameInfo::Handler interface doesn't
1037 : // (and shouldn't) have any way to report.
1038 : virtual void ClearingCFARule(uint64 offset, CallFrameInfo::EntryKind kind,
1039 : uint64 insn_offset);
1040 :
1041 : protected:
1042 : // The name of the file whose CFI we're reading.
1043 : string filename_;
1044 :
1045 : // The name of the CFI section in that file.
1046 : string section_;
1047 : };
1048 :
1049 : } // namespace dwarf2reader
1050 :
1051 : #endif // UTIL_DEBUGINFO_DWARF2READER_H__
|