1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 
4 // Copyright 2006, 2010 Google Inc. All Rights Reserved.
5 //
6 // Redistribution and use in source and binary forms, with or without
7 // modification, are permitted provided that the following conditions are
8 // met:
9 //
10 //     * Redistributions of source code must retain the above copyright
11 // notice, this list of conditions and the following disclaimer.
12 //     * Redistributions in binary form must reproduce the above
13 // copyright notice, this list of conditions and the following disclaimer
14 // in the documentation and/or other materials provided with the
15 // distribution.
16 //     * Neither the name of Google Inc. nor the names of its
17 // contributors may be used to endorse or promote products derived from
18 // this software without specific prior written permission.
19 //
20 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 
32 // Original author: Jim Blandy <jimb@mozilla.com> <jimb@red-bean.com>
33 
34 // This file is derived from the following files in
35 // toolkit/crashreporter/google-breakpad:
36 //   src/common/dwarf/types.h
37 //   src/common/dwarf/dwarf2enums.h
38 //   src/common/dwarf/bytereader.h
39 //   src/common/dwarf_cfi_to_module.h
40 //   src/common/dwarf/dwarf2reader.h
41 
42 #ifndef LulDwarfExt_h
43 #define LulDwarfExt_h
44 
45 #include "LulDwarfSummariser.h"
46 
47 #include "mozilla/Assertions.h"
48 
49 #include <stdint.h>
50 #include <string>
51 
52 typedef signed char int8;
53 typedef short int16;
54 typedef int int32;
55 typedef long long int64;
56 
57 typedef unsigned char uint8;
58 typedef unsigned short uint16;
59 typedef unsigned int uint32;
60 typedef unsigned long long uint64;
61 
62 #ifdef __PTRDIFF_TYPE__
63 typedef __PTRDIFF_TYPE__ intptr;
64 typedef unsigned __PTRDIFF_TYPE__ uintptr;
65 #else
66 #  error "Can't find pointer-sized integral types."
67 #endif
68 
69 namespace lul {
70 
71 class UniqueString;
72 
73 // Exception handling frame description pointer formats, as described
74 // by the Linux Standard Base Core Specification 4.0, section 11.5,
75 // DWARF Extensions.
76 enum DwarfPointerEncoding {
77   DW_EH_PE_absptr = 0x00,
78   DW_EH_PE_omit = 0xff,
79   DW_EH_PE_uleb128 = 0x01,
80   DW_EH_PE_udata2 = 0x02,
81   DW_EH_PE_udata4 = 0x03,
82   DW_EH_PE_udata8 = 0x04,
83   DW_EH_PE_sleb128 = 0x09,
84   DW_EH_PE_sdata2 = 0x0A,
85   DW_EH_PE_sdata4 = 0x0B,
86   DW_EH_PE_sdata8 = 0x0C,
87   DW_EH_PE_pcrel = 0x10,
88   DW_EH_PE_textrel = 0x20,
89   DW_EH_PE_datarel = 0x30,
90   DW_EH_PE_funcrel = 0x40,
91   DW_EH_PE_aligned = 0x50,
92 
93   // The GNU toolchain sources define this enum value as well,
94   // simply to help classify the lower nybble values into signed and
95   // unsigned groups.
96   DW_EH_PE_signed = 0x08,
97 
98   // This is not documented in LSB 4.0, but it is used in both the
99   // Linux and OS X toolchains. It can be added to any other
100   // encoding (except DW_EH_PE_aligned), and indicates that the
101   // encoded value represents the address at which the true address
102   // is stored, not the true address itself.
103   DW_EH_PE_indirect = 0x80
104 };
105 
106 // We can't use the obvious name of LITTLE_ENDIAN and BIG_ENDIAN
107 // because it conflicts with a macro
108 enum Endianness { ENDIANNESS_BIG, ENDIANNESS_LITTLE };
109 
110 // A ByteReader knows how to read single- and multi-byte values of
111 // various endiannesses, sizes, and encodings, as used in DWARF
112 // debugging information and Linux C++ exception handling data.
113 class ByteReader {
114  public:
115   // Construct a ByteReader capable of reading one-, two-, four-, and
116   // eight-byte values according to ENDIANNESS, absolute machine-sized
117   // addresses, DWARF-style "initial length" values, signed and
118   // unsigned LEB128 numbers, and Linux C++ exception handling data's
119   // encoded pointers.
120   explicit ByteReader(enum Endianness endianness);
121   virtual ~ByteReader();
122 
123   // Read a single byte from BUFFER and return it as an unsigned 8 bit
124   // number.
125   uint8 ReadOneByte(const char* buffer) const;
126 
127   // Read two bytes from BUFFER and return them as an unsigned 16 bit
128   // number, using this ByteReader's endianness.
129   uint16 ReadTwoBytes(const char* buffer) const;
130 
131   // Read four bytes from BUFFER and return them as an unsigned 32 bit
132   // number, using this ByteReader's endianness. This function returns
133   // a uint64 so that it is compatible with ReadAddress and
134   // ReadOffset. The number it returns will never be outside the range
135   // of an unsigned 32 bit integer.
136   uint64 ReadFourBytes(const char* buffer) const;
137 
138   // Read eight bytes from BUFFER and return them as an unsigned 64
139   // bit number, using this ByteReader's endianness.
140   uint64 ReadEightBytes(const char* buffer) const;
141 
142   // Read an unsigned LEB128 (Little Endian Base 128) number from
143   // BUFFER and return it as an unsigned 64 bit integer. Set LEN to
144   // the number of bytes read.
145   //
146   // The unsigned LEB128 representation of an integer N is a variable
147   // number of bytes:
148   //
149   // - If N is between 0 and 0x7f, then its unsigned LEB128
150   //   representation is a single byte whose value is N.
151   //
152   // - Otherwise, its unsigned LEB128 representation is (N & 0x7f) |
153   //   0x80, followed by the unsigned LEB128 representation of N /
154   //   128, rounded towards negative infinity.
155   //
156   // In other words, we break VALUE into groups of seven bits, put
157   // them in little-endian order, and then write them as eight-bit
158   // bytes with the high bit on all but the last.
159   uint64 ReadUnsignedLEB128(const char* buffer, size_t* len) const;
160 
161   // Read a signed LEB128 number from BUFFER and return it as an
162   // signed 64 bit integer. Set LEN to the number of bytes read.
163   //
164   // The signed LEB128 representation of an integer N is a variable
165   // number of bytes:
166   //
167   // - If N is between -0x40 and 0x3f, then its signed LEB128
168   //   representation is a single byte whose value is N in two's
169   //   complement.
170   //
171   // - Otherwise, its signed LEB128 representation is (N & 0x7f) |
172   //   0x80, followed by the signed LEB128 representation of N / 128,
173   //   rounded towards negative infinity.
174   //
175   // In other words, we break VALUE into groups of seven bits, put
176   // them in little-endian order, and then write them as eight-bit
177   // bytes with the high bit on all but the last.
178   int64 ReadSignedLEB128(const char* buffer, size_t* len) const;
179 
180   // Indicate that addresses on this architecture are SIZE bytes long. SIZE
181   // must be either 4 or 8. (DWARF allows addresses to be any number of
182   // bytes in length from 1 to 255, but we only support 32- and 64-bit
183   // addresses at the moment.) You must call this before using the
184   // ReadAddress member function.
185   //
186   // For data in a .debug_info section, or something that .debug_info
187   // refers to like line number or macro data, the compilation unit
188   // header's address_size field indicates the address size to use. Call
189   // frame information doesn't indicate its address size (a shortcoming of
190   // the spec); you must supply the appropriate size based on the
191   // architecture of the target machine.
192   void SetAddressSize(uint8 size);
193 
194   // Return the current address size, in bytes. This is either 4,
195   // indicating 32-bit addresses, or 8, indicating 64-bit addresses.
AddressSize()196   uint8 AddressSize() const { return address_size_; }
197 
198   // Read an address from BUFFER and return it as an unsigned 64 bit
199   // integer, respecting this ByteReader's endianness and address size. You
200   // must call SetAddressSize before calling this function.
201   uint64 ReadAddress(const char* buffer) const;
202 
203   // DWARF actually defines two slightly different formats: 32-bit DWARF
204   // and 64-bit DWARF. This is *not* related to the size of registers or
205   // addresses on the target machine; it refers only to the size of section
206   // offsets and data lengths appearing in the DWARF data. One only needs
207   // 64-bit DWARF when the debugging data itself is larger than 4GiB.
208   // 32-bit DWARF can handle x86_64 or PPC64 code just fine, unless the
209   // debugging data itself is very large.
210   //
211   // DWARF information identifies itself as 32-bit or 64-bit DWARF: each
212   // compilation unit and call frame information entry begins with an
213   // "initial length" field, which, in addition to giving the length of the
214   // data, also indicates the size of section offsets and lengths appearing
215   // in that data. The ReadInitialLength member function, below, reads an
216   // initial length and sets the ByteReader's offset size as a side effect.
217   // Thus, in the normal process of reading DWARF data, the appropriate
218   // offset size is set automatically. So, you should only need to call
219   // SetOffsetSize if you are using the same ByteReader to jump from the
220   // midst of one block of DWARF data into another.
221 
222   // Read a DWARF "initial length" field from START, and return it as
223   // an unsigned 64 bit integer, respecting this ByteReader's
224   // endianness. Set *LEN to the length of the initial length in
225   // bytes, either four or twelve. As a side effect, set this
226   // ByteReader's offset size to either 4 (if we see a 32-bit DWARF
227   // initial length) or 8 (if we see a 64-bit DWARF initial length).
228   //
229   // A DWARF initial length is either:
230   //
231   // - a byte count stored as an unsigned 32-bit value less than
232   //   0xffffff00, indicating that the data whose length is being
233   //   measured uses the 32-bit DWARF format, or
234   //
235   // - The 32-bit value 0xffffffff, followed by a 64-bit byte count,
236   //   indicating that the data whose length is being measured uses
237   //   the 64-bit DWARF format.
238   uint64 ReadInitialLength(const char* start, size_t* len);
239 
240   // Read an offset from BUFFER and return it as an unsigned 64 bit
241   // integer, respecting the ByteReader's endianness. In 32-bit DWARF, the
242   // offset is 4 bytes long; in 64-bit DWARF, the offset is eight bytes
243   // long. You must call ReadInitialLength or SetOffsetSize before calling
244   // this function; see the comments above for details.
245   uint64 ReadOffset(const char* buffer) const;
246 
247   // Return the current offset size, in bytes.
248   // A return value of 4 indicates that we are reading 32-bit DWARF.
249   // A return value of 8 indicates that we are reading 64-bit DWARF.
OffsetSize()250   uint8 OffsetSize() const { return offset_size_; }
251 
252   // Indicate that section offsets and lengths are SIZE bytes long. SIZE
253   // must be either 4 (meaning 32-bit DWARF) or 8 (meaning 64-bit DWARF).
254   // Usually, you should not call this function yourself; instead, let a
255   // call to ReadInitialLength establish the data's offset size
256   // automatically.
257   void SetOffsetSize(uint8 size);
258 
259   // The Linux C++ ABI uses a variant of DWARF call frame information
260   // for exception handling. This data is included in the program's
261   // address space as the ".eh_frame" section, and intepreted at
262   // runtime to walk the stack, find exception handlers, and run
263   // cleanup code. The format is mostly the same as DWARF CFI, with
264   // some adjustments made to provide the additional
265   // exception-handling data, and to make the data easier to work with
266   // in memory --- for example, to allow it to be placed in read-only
267   // memory even when describing position-independent code.
268   //
269   // In particular, exception handling data can select a number of
270   // different encodings for pointers that appear in the data, as
271   // described by the DwarfPointerEncoding enum. There are actually
272   // four axes(!) to the encoding:
273   //
274   // - The pointer size: pointers can be 2, 4, or 8 bytes long, or use
275   //   the DWARF LEB128 encoding.
276   //
277   // - The pointer's signedness: pointers can be signed or unsigned.
278   //
279   // - The pointer's base address: the data stored in the exception
280   //   handling data can be the actual address (that is, an absolute
281   //   pointer), or relative to one of a number of different base
282   //   addreses --- including that of the encoded pointer itself, for
283   //   a form of "pc-relative" addressing.
284   //
285   // - The pointer may be indirect: it may be the address where the
286   //   true pointer is stored. (This is used to refer to things via
287   //   global offset table entries, program linkage table entries, or
288   //   other tricks used in position-independent code.)
289   //
290   // There are also two options that fall outside that matrix
291   // altogether: the pointer may be omitted, or it may have padding to
292   // align it on an appropriate address boundary. (That last option
293   // may seem like it should be just another axis, but it is not.)
294 
295   // Indicate that the exception handling data is loaded starting at
296   // SECTION_BASE, and that the start of its buffer in our own memory
297   // is BUFFER_BASE. This allows us to find the address that a given
298   // byte in our buffer would have when loaded into the program the
299   // data describes. We need this to resolve DW_EH_PE_pcrel pointers.
300   void SetCFIDataBase(uint64 section_base, const char* buffer_base);
301 
302   // Indicate that the base address of the program's ".text" section
303   // is TEXT_BASE. We need this to resolve DW_EH_PE_textrel pointers.
304   void SetTextBase(uint64 text_base);
305 
306   // Indicate that the base address for DW_EH_PE_datarel pointers is
307   // DATA_BASE. The proper value depends on the ABI; it is usually the
308   // address of the global offset table, held in a designated register in
309   // position-independent code. You will need to look at the startup code
310   // for the target system to be sure. I tried; my eyes bled.
311   void SetDataBase(uint64 data_base);
312 
313   // Indicate that the base address for the FDE we are processing is
314   // FUNCTION_BASE. This is the start address of DW_EH_PE_funcrel
315   // pointers. (This encoding does not seem to be used by the GNU
316   // toolchain.)
317   void SetFunctionBase(uint64 function_base);
318 
319   // Indicate that we are no longer processing any FDE, so any use of
320   // a DW_EH_PE_funcrel encoding is an error.
321   void ClearFunctionBase();
322 
323   // Return true if ENCODING is a valid pointer encoding.
324   bool ValidEncoding(DwarfPointerEncoding encoding) const;
325 
326   // Return true if we have all the information we need to read a
327   // pointer that uses ENCODING. This checks that the appropriate
328   // SetFooBase function for ENCODING has been called.
329   bool UsableEncoding(DwarfPointerEncoding encoding) const;
330 
331   // Read an encoded pointer from BUFFER using ENCODING; return the
332   // absolute address it represents, and set *LEN to the pointer's
333   // length in bytes, including any padding for aligned pointers.
334   //
335   // This function calls 'abort' if ENCODING is invalid or refers to a
336   // base address this reader hasn't been given, so you should check
337   // with ValidEncoding and UsableEncoding first if you would rather
338   // die in a more helpful way.
339   uint64 ReadEncodedPointer(const char* buffer, DwarfPointerEncoding encoding,
340                             size_t* len) const;
341 
342  private:
343   // Function pointer type for our address and offset readers.
344   typedef uint64 (ByteReader::*AddressReader)(const char*) const;
345 
346   // Read an offset from BUFFER and return it as an unsigned 64 bit
347   // integer.  DWARF2/3 define offsets as either 4 or 8 bytes,
348   // generally depending on the amount of DWARF2/3 info present.
349   // This function pointer gets set by SetOffsetSize.
350   AddressReader offset_reader_;
351 
352   // Read an address from BUFFER and return it as an unsigned 64 bit
353   // integer.  DWARF2/3 allow addresses to be any size from 0-255
354   // bytes currently.  Internally we support 4 and 8 byte addresses,
355   // and will CHECK on anything else.
356   // This function pointer gets set by SetAddressSize.
357   AddressReader address_reader_;
358 
359   Endianness endian_;
360   uint8 address_size_;
361   uint8 offset_size_;
362 
363   // Base addresses for Linux C++ exception handling data's encoded pointers.
364   bool have_section_base_, have_text_base_, have_data_base_;
365   bool have_function_base_;
366   uint64 section_base_;
367   uint64 text_base_, data_base_, function_base_;
368   const char* buffer_base_;
369 };
370 
ReadOneByte(const char * buffer)371 inline uint8 ByteReader::ReadOneByte(const char* buffer) const {
372   return buffer[0];
373 }
374 
ReadTwoBytes(const char * signed_buffer)375 inline uint16 ByteReader::ReadTwoBytes(const char* signed_buffer) const {
376   const unsigned char* buffer =
377       reinterpret_cast<const unsigned char*>(signed_buffer);
378   const uint16 buffer0 = buffer[0];
379   const uint16 buffer1 = buffer[1];
380   if (endian_ == ENDIANNESS_LITTLE) {
381     return buffer0 | buffer1 << 8;
382   } else {
383     return buffer1 | buffer0 << 8;
384   }
385 }
386 
ReadFourBytes(const char * signed_buffer)387 inline uint64 ByteReader::ReadFourBytes(const char* signed_buffer) const {
388   const unsigned char* buffer =
389       reinterpret_cast<const unsigned char*>(signed_buffer);
390   const uint32 buffer0 = buffer[0];
391   const uint32 buffer1 = buffer[1];
392   const uint32 buffer2 = buffer[2];
393   const uint32 buffer3 = buffer[3];
394   if (endian_ == ENDIANNESS_LITTLE) {
395     return buffer0 | buffer1 << 8 | buffer2 << 16 | buffer3 << 24;
396   } else {
397     return buffer3 | buffer2 << 8 | buffer1 << 16 | buffer0 << 24;
398   }
399 }
400 
ReadEightBytes(const char * signed_buffer)401 inline uint64 ByteReader::ReadEightBytes(const char* signed_buffer) const {
402   const unsigned char* buffer =
403       reinterpret_cast<const unsigned char*>(signed_buffer);
404   const uint64 buffer0 = buffer[0];
405   const uint64 buffer1 = buffer[1];
406   const uint64 buffer2 = buffer[2];
407   const uint64 buffer3 = buffer[3];
408   const uint64 buffer4 = buffer[4];
409   const uint64 buffer5 = buffer[5];
410   const uint64 buffer6 = buffer[6];
411   const uint64 buffer7 = buffer[7];
412   if (endian_ == ENDIANNESS_LITTLE) {
413     return buffer0 | buffer1 << 8 | buffer2 << 16 | buffer3 << 24 |
414            buffer4 << 32 | buffer5 << 40 | buffer6 << 48 | buffer7 << 56;
415   } else {
416     return buffer7 | buffer6 << 8 | buffer5 << 16 | buffer4 << 24 |
417            buffer3 << 32 | buffer2 << 40 | buffer1 << 48 | buffer0 << 56;
418   }
419 }
420 
421 // Read an unsigned LEB128 number.  Each byte contains 7 bits of
422 // information, plus one bit saying whether the number continues or
423 // not.
424 
ReadUnsignedLEB128(const char * buffer,size_t * len)425 inline uint64 ByteReader::ReadUnsignedLEB128(const char* buffer,
426                                              size_t* len) const {
427   uint64 result = 0;
428   size_t num_read = 0;
429   unsigned int shift = 0;
430   unsigned char byte;
431 
432   do {
433     byte = *buffer++;
434     num_read++;
435 
436     result |= (static_cast<uint64>(byte & 0x7f)) << shift;
437 
438     shift += 7;
439 
440   } while (byte & 0x80);
441 
442   *len = num_read;
443 
444   return result;
445 }
446 
447 // Read a signed LEB128 number.  These are like regular LEB128
448 // numbers, except the last byte may have a sign bit set.
449 
ReadSignedLEB128(const char * buffer,size_t * len)450 inline int64 ByteReader::ReadSignedLEB128(const char* buffer,
451                                           size_t* len) const {
452   int64 result = 0;
453   unsigned int shift = 0;
454   size_t num_read = 0;
455   unsigned char byte;
456 
457   do {
458     byte = *buffer++;
459     num_read++;
460     result |= (static_cast<uint64>(byte & 0x7f) << shift);
461     shift += 7;
462   } while (byte & 0x80);
463 
464   if ((shift < 8 * sizeof(result)) && (byte & 0x40))
465     result |= -((static_cast<int64>(1)) << shift);
466   *len = num_read;
467   return result;
468 }
469 
ReadOffset(const char * buffer)470 inline uint64 ByteReader::ReadOffset(const char* buffer) const {
471   MOZ_ASSERT(this->offset_reader_);
472   return (this->*offset_reader_)(buffer);
473 }
474 
ReadAddress(const char * buffer)475 inline uint64 ByteReader::ReadAddress(const char* buffer) const {
476   MOZ_ASSERT(this->address_reader_);
477   return (this->*address_reader_)(buffer);
478 }
479 
SetCFIDataBase(uint64 section_base,const char * buffer_base)480 inline void ByteReader::SetCFIDataBase(uint64 section_base,
481                                        const char* buffer_base) {
482   section_base_ = section_base;
483   buffer_base_ = buffer_base;
484   have_section_base_ = true;
485 }
486 
SetTextBase(uint64 text_base)487 inline void ByteReader::SetTextBase(uint64 text_base) {
488   text_base_ = text_base;
489   have_text_base_ = true;
490 }
491 
SetDataBase(uint64 data_base)492 inline void ByteReader::SetDataBase(uint64 data_base) {
493   data_base_ = data_base;
494   have_data_base_ = true;
495 }
496 
SetFunctionBase(uint64 function_base)497 inline void ByteReader::SetFunctionBase(uint64 function_base) {
498   function_base_ = function_base;
499   have_function_base_ = true;
500 }
501 
ClearFunctionBase()502 inline void ByteReader::ClearFunctionBase() { have_function_base_ = false; }
503 
504 // (derived from)
505 // dwarf_cfi_to_module.h: Define the DwarfCFIToModule class, which
506 // accepts parsed DWARF call frame info and adds it to a Summariser object.
507 
508 // This class is a reader for DWARF's Call Frame Information.  CFI
509 // describes how to unwind stack frames --- even for functions that do
510 // not follow fixed conventions for saving registers, whose frame size
511 // varies as they execute, etc.
512 //
513 // CFI describes, at each machine instruction, how to compute the
514 // stack frame's base address, how to find the return address, and
515 // where to find the saved values of the caller's registers (if the
516 // callee has stashed them somewhere to free up the registers for its
517 // own use).
518 //
519 // For example, suppose we have a function whose machine code looks
520 // like this (imagine an assembly language that looks like C, for a
521 // machine with 32-bit registers, and a stack that grows towards lower
522 // addresses):
523 //
524 // func:                                ; entry point; return address at sp
525 // func+0:      sp = sp - 16            ; allocate space for stack frame
526 // func+1:      sp[12] = r0             ; save r0 at sp+12
527 // ...                                  ; other code, not frame-related
528 // func+10:     sp -= 4; *sp = x        ; push some x on the stack
529 // ...                                  ; other code, not frame-related
530 // func+20:     r0 = sp[16]             ; restore saved r0
531 // func+21:     sp += 20                ; pop whole stack frame
532 // func+22:     pc = *sp; sp += 4       ; pop return address and jump to it
533 //
534 // DWARF CFI is (a very compressed representation of) a table with a
535 // row for each machine instruction address and a column for each
536 // register showing how to restore it, if possible.
537 //
538 // A special column named "CFA", for "Canonical Frame Address", tells how
539 // to compute the base address of the frame; registers' entries may
540 // refer to the CFA in describing where the registers are saved.
541 //
542 // Another special column, named "RA", represents the return address.
543 //
544 // For example, here is a complete (uncompressed) table describing the
545 // function above:
546 //
547 //     insn      cfa    r0      r1 ...  ra
548 //     =======================================
549 //     func+0:   sp                     cfa[0]
550 //     func+1:   sp+16                  cfa[0]
551 //     func+2:   sp+16  cfa[-4]         cfa[0]
552 //     func+11:  sp+20  cfa[-4]         cfa[0]
553 //     func+21:  sp+20                  cfa[0]
554 //     func+22:  sp                     cfa[0]
555 //
556 // Some things to note here:
557 //
558 // - Each row describes the state of affairs *before* executing the
559 //   instruction at the given address.  Thus, the row for func+0
560 //   describes the state before we allocate the stack frame.  In the
561 //   next row, the formula for computing the CFA has changed,
562 //   reflecting that allocation.
563 //
564 // - The other entries are written in terms of the CFA; this allows
565 //   them to remain unchanged as the stack pointer gets bumped around.
566 //   For example, the rule for recovering the return address (the "ra"
567 //   column) remains unchanged throughout the function, even as the
568 //   stack pointer takes on three different offsets from the return
569 //   address.
570 //
571 // - Although we haven't shown it, most calling conventions designate
572 //   "callee-saves" and "caller-saves" registers. The callee must
573 //   preserve the values of callee-saves registers; if it uses them,
574 //   it must save their original values somewhere, and restore them
575 //   before it returns. In contrast, the callee is free to trash
576 //   caller-saves registers; if the callee uses these, it will
577 //   probably not bother to save them anywhere, and the CFI will
578 //   probably mark their values as "unrecoverable".
579 //
580 //   (However, since the caller cannot assume the callee was going to
581 //   save them, caller-saves registers are probably dead in the caller
582 //   anyway, so compilers usually don't generate CFA for caller-saves
583 //   registers.)
584 //
585 // - Exactly where the CFA points is a matter of convention that
586 //   depends on the architecture and ABI in use. In the example, the
587 //   CFA is the value the stack pointer had upon entry to the
588 //   function, pointing at the saved return address. But on the x86,
589 //   the call frame information generated by GCC follows the
590 //   convention that the CFA is the address *after* the saved return
591 //   address.
592 //
593 //   But by definition, the CFA remains constant throughout the
594 //   lifetime of the frame. This makes it a useful value for other
595 //   columns to refer to. It is also gives debuggers a useful handle
596 //   for identifying a frame.
597 //
598 // If you look at the table above, you'll notice that a given entry is
599 // often the same as the one immediately above it: most instructions
600 // change only one or two aspects of the stack frame, if they affect
601 // it at all. The DWARF format takes advantage of this fact, and
602 // reduces the size of the data by mentioning only the addresses and
603 // columns at which changes take place. So for the above, DWARF CFI
604 // data would only actually mention the following:
605 //
606 //     insn      cfa    r0      r1 ...  ra
607 //     =======================================
608 //     func+0:   sp                     cfa[0]
609 //     func+1:   sp+16
610 //     func+2:          cfa[-4]
611 //     func+11:  sp+20
612 //     func+21:         r0
613 //     func+22:  sp
614 //
615 // In fact, this is the way the parser reports CFI to the consumer: as
616 // a series of statements of the form, "At address X, column Y changed
617 // to Z," and related conventions for describing the initial state.
618 //
619 // Naturally, it would be impractical to have to scan the entire
620 // program's CFI, noting changes as we go, just to recover the
621 // unwinding rules in effect at one particular instruction. To avoid
622 // this, CFI data is grouped into "entries", each of which covers a
623 // specified range of addresses and begins with a complete statement
624 // of the rules for all recoverable registers at that starting
625 // address. Each entry typically covers a single function.
626 //
627 // Thus, to compute the contents of a given row of the table --- that
628 // is, rules for recovering the CFA, RA, and registers at a given
629 // instruction --- the consumer should find the entry that covers that
630 // instruction's address, start with the initial state supplied at the
631 // beginning of the entry, and work forward until it has processed all
632 // the changes up to and including those for the present instruction.
633 //
634 // There are seven kinds of rules that can appear in an entry of the
635 // table:
636 //
637 // - "undefined": The given register is not preserved by the callee;
638 //   its value cannot be recovered.
639 //
640 // - "same value": This register has the same value it did in the callee.
641 //
642 // - offset(N): The register is saved at offset N from the CFA.
643 //
644 // - val_offset(N): The value the register had in the caller is the
645 //   CFA plus offset N. (This is usually only useful for describing
646 //   the stack pointer.)
647 //
648 // - register(R): The register's value was saved in another register R.
649 //
650 // - expression(E): Evaluating the DWARF expression E using the
651 //   current frame's registers' values yields the address at which the
652 //   register was saved.
653 //
654 // - val_expression(E): Evaluating the DWARF expression E using the
655 //   current frame's registers' values yields the value the register
656 //   had in the caller.
657 
658 class CallFrameInfo {
659  public:
660   // The different kinds of entries one finds in CFI. Used internally,
661   // and for error reporting.
662   enum EntryKind { kUnknown, kCIE, kFDE, kTerminator };
663 
664   // The handler class to which the parser hands the parsed call frame
665   // information.  Defined below.
666   class Handler;
667 
668   // A reporter class, which CallFrameInfo uses to report errors
669   // encountered while parsing call frame information.  Defined below.
670   class Reporter;
671 
672   // Create a DWARF CFI parser. BUFFER points to the contents of the
673   // .debug_frame section to parse; BUFFER_LENGTH is its length in bytes.
674   // REPORTER is an error reporter the parser should use to report
675   // problems. READER is a ByteReader instance that has the endianness and
676   // address size set properly. Report the data we find to HANDLER.
677   //
678   // This class can also parse Linux C++ exception handling data, as found
679   // in '.eh_frame' sections. This data is a variant of DWARF CFI that is
680   // placed in loadable segments so that it is present in the program's
681   // address space, and is interpreted by the C++ runtime to search the
682   // call stack for a handler interested in the exception being thrown,
683   // actually pop the frames, and find cleanup code to run.
684   //
685   // There are two differences between the call frame information described
686   // in the DWARF standard and the exception handling data Linux places in
687   // the .eh_frame section:
688   //
689   // - Exception handling data uses uses a different format for call frame
690   //   information entry headers. The distinguished CIE id, the way FDEs
691   //   refer to their CIEs, and the way the end of the series of entries is
692   //   determined are all slightly different.
693   //
694   //   If the constructor's EH_FRAME argument is true, then the
695   //   CallFrameInfo parses the entry headers as Linux C++ exception
696   //   handling data. If EH_FRAME is false or omitted, the CallFrameInfo
697   //   parses standard DWARF call frame information.
698   //
699   // - Linux C++ exception handling data uses CIE augmentation strings
700   //   beginning with 'z' to specify the presence of additional data after
701   //   the CIE and FDE headers and special encodings used for addresses in
702   //   frame description entries.
703   //
704   //   CallFrameInfo can handle 'z' augmentations in either DWARF CFI or
705   //   exception handling data if you have supplied READER with the base
706   //   addresses needed to interpret the pointer encodings that 'z'
707   //   augmentations can specify. See the ByteReader interface for details
708   //   about the base addresses. See the CallFrameInfo::Handler interface
709   //   for details about the additional information one might find in
710   //   'z'-augmented data.
711   //
712   // Thus:
713   //
714   // - If you are parsing standard DWARF CFI, as found in a .debug_frame
715   //   section, you should pass false for the EH_FRAME argument, or omit
716   //   it, and you need not worry about providing READER with the
717   //   additional base addresses.
718   //
719   // - If you want to parse Linux C++ exception handling data from a
720   //   .eh_frame section, you should pass EH_FRAME as true, and call
721   //   READER's Set*Base member functions before calling our Start method.
722   //
723   // - If you want to parse DWARF CFI that uses the 'z' augmentations
724   //   (although I don't think any toolchain ever emits such data), you
725   //   could pass false for EH_FRAME, but call READER's Set*Base members.
726   //
727   // The extensions the Linux C++ ABI makes to DWARF for exception
728   // handling are described here, rather poorly:
729   // http://refspecs.linux-foundation.org/LSB_4.0.0/LSB-Core-generic/LSB-Core-generic/dwarfext.html
730   // http://refspecs.linux-foundation.org/LSB_4.0.0/LSB-Core-generic/LSB-Core-generic/ehframechpt.html
731   //
732   // The mechanics of C++ exception handling, personality routines,
733   // and language-specific data areas are described here, rather nicely:
734   // http://www.codesourcery.com/public/cxx-abi/abi-eh.html
735 
736   CallFrameInfo(const char* buffer, size_t buffer_length, ByteReader* reader,
737                 Handler* handler, Reporter* reporter, bool eh_frame = false)
buffer_(buffer)738       : buffer_(buffer),
739         buffer_length_(buffer_length),
740         reader_(reader),
741         handler_(handler),
742         reporter_(reporter),
743         eh_frame_(eh_frame) {}
744 
~CallFrameInfo()745   ~CallFrameInfo() {}
746 
747   // Parse the entries in BUFFER, reporting what we find to HANDLER.
748   // Return true if we reach the end of the section successfully, or
749   // false if we encounter an error.
750   bool Start();
751 
752   // Return the textual name of KIND. For error reporting.
753   static const char* KindName(EntryKind kind);
754 
755  private:
756   struct CIE;
757 
758   // A CFI entry, either an FDE or a CIE.
759   struct Entry {
760     // The starting offset of the entry in the section, for error
761     // reporting.
762     size_t offset;
763 
764     // The start of this entry in the buffer.
765     const char* start;
766 
767     // Which kind of entry this is.
768     //
769     // We want to be able to use this for error reporting even while we're
770     // in the midst of parsing. Error reporting code may assume that kind,
771     // offset, and start fields are valid, although kind may be kUnknown.
772     EntryKind kind;
773 
774     // The end of this entry's common prologue (initial length and id), and
775     // the start of this entry's kind-specific fields.
776     const char* fields;
777 
778     // The start of this entry's instructions.
779     const char* instructions;
780 
781     // The address past the entry's last byte in the buffer. (Note that
782     // since offset points to the entry's initial length field, and the
783     // length field is the number of bytes after that field, this is not
784     // simply buffer_ + offset + length.)
785     const char* end;
786 
787     // For both DWARF CFI and .eh_frame sections, this is the CIE id in a
788     // CIE, and the offset of the associated CIE in an FDE.
789     uint64 id;
790 
791     // The CIE that applies to this entry, if we've parsed it. If this is a
792     // CIE, then this field points to this structure.
793     CIE* cie;
794   };
795 
796   // A common information entry (CIE).
797   struct CIE : public Entry {
798     uint8 version;                     // CFI data version number
799     std::string augmentation;          // vendor format extension markers
800     uint64 code_alignment_factor;      // scale for code address adjustments
801     int data_alignment_factor;         // scale for stack pointer adjustments
802     unsigned return_address_register;  // which register holds the return addr
803 
804     // True if this CIE includes Linux C++ ABI 'z' augmentation data.
805     bool has_z_augmentation;
806 
807     // Parsed 'z' augmentation data. These are meaningful only if
808     // has_z_augmentation is true.
809     bool has_z_lsda;          // The 'z' augmentation included 'L'.
810     bool has_z_personality;   // The 'z' augmentation included 'P'.
811     bool has_z_signal_frame;  // The 'z' augmentation included 'S'.
812 
813     // If has_z_lsda is true, this is the encoding to be used for language-
814     // specific data area pointers in FDEs.
815     DwarfPointerEncoding lsda_encoding;
816 
817     // If has_z_personality is true, this is the encoding used for the
818     // personality routine pointer in the augmentation data.
819     DwarfPointerEncoding personality_encoding;
820 
821     // If has_z_personality is true, this is the address of the personality
822     // routine --- or, if personality_encoding & DW_EH_PE_indirect, the
823     // address where the personality routine's address is stored.
824     uint64 personality_address;
825 
826     // This is the encoding used for addresses in the FDE header and
827     // in DW_CFA_set_loc instructions. This is always valid, whether
828     // or not we saw a 'z' augmentation string; its default value is
829     // DW_EH_PE_absptr, which is what normal DWARF CFI uses.
830     DwarfPointerEncoding pointer_encoding;
831   };
832 
833   // A frame description entry (FDE).
834   struct FDE : public Entry {
835     uint64 address;  // start address of described code
836     uint64 size;     // size of described code, in bytes
837 
838     // If cie->has_z_lsda is true, then this is the language-specific data
839     // area's address --- or its address's address, if cie->lsda_encoding
840     // has the DW_EH_PE_indirect bit set.
841     uint64 lsda_address;
842   };
843 
844   // Internal use.
845   class Rule;
846   class UndefinedRule;
847   class SameValueRule;
848   class OffsetRule;
849   class ValOffsetRule;
850   class RegisterRule;
851   class ExpressionRule;
852   class ValExpressionRule;
853   class RuleMap;
854   class State;
855 
856   // Parse the initial length and id of a CFI entry, either a CIE, an FDE,
857   // or a .eh_frame end-of-data mark. CURSOR points to the beginning of the
858   // data to parse. On success, populate ENTRY as appropriate, and return
859   // true. On failure, report the problem, and return false. Even if we
860   // return false, set ENTRY->end to the first byte after the entry if we
861   // were able to figure that out, or NULL if we weren't.
862   bool ReadEntryPrologue(const char* cursor, Entry* entry);
863 
864   // Parse the fields of a CIE after the entry prologue, including any 'z'
865   // augmentation data. Assume that the 'Entry' fields of CIE are
866   // populated; use CIE->fields and CIE->end as the start and limit for
867   // parsing. On success, populate the rest of *CIE, and return true; on
868   // failure, report the problem and return false.
869   bool ReadCIEFields(CIE* cie);
870 
871   // Parse the fields of an FDE after the entry prologue, including any 'z'
872   // augmentation data. Assume that the 'Entry' fields of *FDE are
873   // initialized; use FDE->fields and FDE->end as the start and limit for
874   // parsing. Assume that FDE->cie is fully initialized. On success,
875   // populate the rest of *FDE, and return true; on failure, report the
876   // problem and return false.
877   bool ReadFDEFields(FDE* fde);
878 
879   // Report that ENTRY is incomplete, and return false. This is just a
880   // trivial wrapper for invoking reporter_->Incomplete; it provides a
881   // little brevity.
882   bool ReportIncomplete(Entry* entry);
883 
884   // Return true if ENCODING has the DW_EH_PE_indirect bit set.
IsIndirectEncoding(DwarfPointerEncoding encoding)885   static bool IsIndirectEncoding(DwarfPointerEncoding encoding) {
886     return encoding & DW_EH_PE_indirect;
887   }
888 
889   // The contents of the DWARF .debug_info section we're parsing.
890   const char* buffer_;
891   size_t buffer_length_;
892 
893   // For reading multi-byte values with the appropriate endianness.
894   ByteReader* reader_;
895 
896   // The handler to which we should report the data we find.
897   Handler* handler_;
898 
899   // For reporting problems in the info we're parsing.
900   Reporter* reporter_;
901 
902   // True if we are processing .eh_frame-format data.
903   bool eh_frame_;
904 };
905 
906 // The handler class for CallFrameInfo.  The a CFI parser calls the
907 // member functions of a handler object to report the data it finds.
908 class CallFrameInfo::Handler {
909  public:
910   // The pseudo-register number for the canonical frame address.
911   enum { kCFARegister = DW_REG_CFA };
912 
Handler()913   Handler() {}
~Handler()914   virtual ~Handler() {}
915 
916   // The parser has found CFI for the machine code at ADDRESS,
917   // extending for LENGTH bytes. OFFSET is the offset of the frame
918   // description entry in the section, for use in error messages.
919   // VERSION is the version number of the CFI format. AUGMENTATION is
920   // a string describing any producer-specific extensions present in
921   // the data. RETURN_ADDRESS is the number of the register that holds
922   // the address to which the function should return.
923   //
924   // Entry should return true to process this CFI, or false to skip to
925   // the next entry.
926   //
927   // The parser invokes Entry for each Frame Description Entry (FDE)
928   // it finds.  The parser doesn't report Common Information Entries
929   // to the handler explicitly; instead, if the handler elects to
930   // process a given FDE, the parser reiterates the appropriate CIE's
931   // contents at the beginning of the FDE's rules.
932   virtual bool Entry(size_t offset, uint64 address, uint64 length,
933                      uint8 version, const std::string& augmentation,
934                      unsigned return_address) = 0;
935 
936   // When the Entry function returns true, the parser calls these
937   // handler functions repeatedly to describe the rules for recovering
938   // registers at each instruction in the given range of machine code.
939   // Immediately after a call to Entry, the handler should assume that
940   // the rule for each callee-saves register is "unchanged" --- that
941   // is, that the register still has the value it had in the caller.
942   //
943   // If a *Rule function returns true, we continue processing this entry's
944   // instructions. If a *Rule function returns false, we stop evaluating
945   // instructions, and skip to the next entry. Either way, we call End
946   // before going on to the next entry.
947   //
948   // In all of these functions, if the REG parameter is kCFARegister, then
949   // the rule describes how to find the canonical frame address.
950   // kCFARegister may be passed as a BASE_REGISTER argument, meaning that
951   // the canonical frame address should be used as the base address for the
952   // computation. All other REG values will be positive.
953 
954   // At ADDRESS, register REG's value is not recoverable.
955   virtual bool UndefinedRule(uint64 address, int reg) = 0;
956 
957   // At ADDRESS, register REG's value is the same as that it had in
958   // the caller.
959   virtual bool SameValueRule(uint64 address, int reg) = 0;
960 
961   // At ADDRESS, register REG has been saved at offset OFFSET from
962   // BASE_REGISTER.
963   virtual bool OffsetRule(uint64 address, int reg, int base_register,
964                           long offset) = 0;
965 
966   // At ADDRESS, the caller's value of register REG is the current
967   // value of BASE_REGISTER plus OFFSET. (This rule doesn't provide an
968   // address at which the register's value is saved.)
969   virtual bool ValOffsetRule(uint64 address, int reg, int base_register,
970                              long offset) = 0;
971 
972   // At ADDRESS, register REG has been saved in BASE_REGISTER. This differs
973   // from ValOffsetRule(ADDRESS, REG, BASE_REGISTER, 0), in that
974   // BASE_REGISTER is the "home" for REG's saved value: if you want to
975   // assign to a variable whose home is REG in the calling frame, you
976   // should put the value in BASE_REGISTER.
977   virtual bool RegisterRule(uint64 address, int reg, int base_register) = 0;
978 
979   // At ADDRESS, the DWARF expression EXPRESSION yields the address at
980   // which REG was saved.
981   virtual bool ExpressionRule(uint64 address, int reg,
982                               const std::string& expression) = 0;
983 
984   // At ADDRESS, the DWARF expression EXPRESSION yields the caller's
985   // value for REG. (This rule doesn't provide an address at which the
986   // register's value is saved.)
987   virtual bool ValExpressionRule(uint64 address, int reg,
988                                  const std::string& expression) = 0;
989 
990   // Indicate that the rules for the address range reported by the
991   // last call to Entry are complete.  End should return true if
992   // everything is okay, or false if an error has occurred and parsing
993   // should stop.
994   virtual bool End() = 0;
995 
996   // Handler functions for Linux C++ exception handling data. These are
997   // only called if the data includes 'z' augmentation strings.
998 
999   // The Linux C++ ABI uses an extension of the DWARF CFI format to
1000   // walk the stack to propagate exceptions from the throw to the
1001   // appropriate catch, and do the appropriate cleanups along the way.
1002   // CFI entries used for exception handling have two additional data
1003   // associated with them:
1004   //
1005   // - The "language-specific data area" describes which exception
1006   //   types the function has 'catch' clauses for, and indicates how
1007   //   to go about re-entering the function at the appropriate catch
1008   //   clause. If the exception is not caught, it describes the
1009   //   destructors that must run before the frame is popped.
1010   //
1011   // - The "personality routine" is responsible for interpreting the
1012   //   language-specific data area's contents, and deciding whether
1013   //   the exception should continue to propagate down the stack,
1014   //   perhaps after doing some cleanup for this frame, or whether the
1015   //   exception will be caught here.
1016   //
1017   // In principle, the language-specific data area is opaque to
1018   // everybody but the personality routine. In practice, these values
1019   // may be useful or interesting to readers with extra context, and
1020   // we have to at least skip them anyway, so we might as well report
1021   // them to the handler.
1022 
1023   // This entry's exception handling personality routine's address is
1024   // ADDRESS. If INDIRECT is true, then ADDRESS is the address at
1025   // which the routine's address is stored. The default definition for
1026   // this handler function simply returns true, allowing parsing of
1027   // the entry to continue.
PersonalityRoutine(uint64 address,bool indirect)1028   virtual bool PersonalityRoutine(uint64 address, bool indirect) {
1029     return true;
1030   }
1031 
1032   // This entry's language-specific data area (LSDA) is located at
1033   // ADDRESS. If INDIRECT is true, then ADDRESS is the address at
1034   // which the area's address is stored. The default definition for
1035   // this handler function simply returns true, allowing parsing of
1036   // the entry to continue.
LanguageSpecificDataArea(uint64 address,bool indirect)1037   virtual bool LanguageSpecificDataArea(uint64 address, bool indirect) {
1038     return true;
1039   }
1040 
1041   // This entry describes a signal trampoline --- this frame is the
1042   // caller of a signal handler. The default definition for this
1043   // handler function simply returns true, allowing parsing of the
1044   // entry to continue.
1045   //
1046   // The best description of the rationale for and meaning of signal
1047   // trampoline CFI entries seems to be in the GCC bug database:
1048   // http://gcc.gnu.org/bugzilla/show_bug.cgi?id=26208
SignalHandler()1049   virtual bool SignalHandler() { return true; }
1050 };
1051 
1052 // The CallFrameInfo class makes calls on an instance of this class to
1053 // report errors or warn about problems in the data it is parsing.
1054 // These messages are sent to the message sink |aLog| provided to the
1055 // constructor.
1056 class CallFrameInfo::Reporter {
1057  public:
1058   // Create an error reporter which attributes troubles to the section
1059   // named SECTION in FILENAME.
1060   //
1061   // Normally SECTION would be .debug_frame, but the Mac puts CFI data
1062   // in a Mach-O section named __debug_frame. If we support
1063   // Linux-style exception handling data, we could be reading an
1064   // .eh_frame section.
1065   Reporter(void (*aLog)(const char*), const std::string& filename,
1066            const std::string& section = ".debug_frame")
log_(aLog)1067       : log_(aLog), filename_(filename), section_(section) {}
~Reporter()1068   virtual ~Reporter() {}
1069 
1070   // The CFI entry at OFFSET ends too early to be well-formed. KIND
1071   // indicates what kind of entry it is; KIND can be kUnknown if we
1072   // haven't parsed enough of the entry to tell yet.
1073   virtual void Incomplete(uint64 offset, CallFrameInfo::EntryKind kind);
1074 
1075   // The .eh_frame data has a four-byte zero at OFFSET where the next
1076   // entry's length would be; this is a terminator. However, the buffer
1077   // length as given to the CallFrameInfo constructor says there should be
1078   // more data.
1079   virtual void EarlyEHTerminator(uint64 offset);
1080 
1081   // The FDE at OFFSET refers to the CIE at CIE_OFFSET, but the
1082   // section is not that large.
1083   virtual void CIEPointerOutOfRange(uint64 offset, uint64 cie_offset);
1084 
1085   // The FDE at OFFSET refers to the CIE at CIE_OFFSET, but the entry
1086   // there is not a CIE.
1087   virtual void BadCIEId(uint64 offset, uint64 cie_offset);
1088 
1089   // The FDE at OFFSET refers to a CIE with version number VERSION,
1090   // which we don't recognize. We cannot parse DWARF CFI if it uses
1091   // a version number we don't recognize.
1092   virtual void UnrecognizedVersion(uint64 offset, int version);
1093 
1094   // The FDE at OFFSET refers to a CIE with augmentation AUGMENTATION,
1095   // which we don't recognize. We cannot parse DWARF CFI if it uses
1096   // augmentations we don't recognize.
1097   virtual void UnrecognizedAugmentation(uint64 offset,
1098                                         const std::string& augmentation);
1099 
1100   // The FDE at OFFSET contains an invalid or otherwise unusable Dwarf4
1101   // specific field (currently, only "address_size" or "segment_size").
1102   // Parsing DWARF CFI with unexpected values here seems dubious at best,
1103   // so we stop.  WHAT gives a little more information about what is wrong.
1104   virtual void InvalidDwarf4Artefact(uint64 offset, const char* what);
1105 
1106   // The pointer encoding ENCODING, specified by the CIE at OFFSET, is not
1107   // a valid encoding.
1108   virtual void InvalidPointerEncoding(uint64 offset, uint8 encoding);
1109 
1110   // The pointer encoding ENCODING, specified by the CIE at OFFSET, depends
1111   // on a base address which has not been supplied.
1112   virtual void UnusablePointerEncoding(uint64 offset, uint8 encoding);
1113 
1114   // The CIE at OFFSET contains a DW_CFA_restore instruction at
1115   // INSN_OFFSET, which may not appear in a CIE.
1116   virtual void RestoreInCIE(uint64 offset, uint64 insn_offset);
1117 
1118   // The entry at OFFSET, of kind KIND, has an unrecognized
1119   // instruction at INSN_OFFSET.
1120   virtual void BadInstruction(uint64 offset, CallFrameInfo::EntryKind kind,
1121                               uint64 insn_offset);
1122 
1123   // The instruction at INSN_OFFSET in the entry at OFFSET, of kind
1124   // KIND, establishes a rule that cites the CFA, but we have not
1125   // established a CFA rule yet.
1126   virtual void NoCFARule(uint64 offset, CallFrameInfo::EntryKind kind,
1127                          uint64 insn_offset);
1128 
1129   // The instruction at INSN_OFFSET in the entry at OFFSET, of kind
1130   // KIND, is a DW_CFA_restore_state instruction, but the stack of
1131   // saved states is empty.
1132   virtual void EmptyStateStack(uint64 offset, CallFrameInfo::EntryKind kind,
1133                                uint64 insn_offset);
1134 
1135   // The DW_CFA_remember_state instruction at INSN_OFFSET in the entry
1136   // at OFFSET, of kind KIND, would restore a state that has no CFA
1137   // rule, whereas the current state does have a CFA rule. This is
1138   // bogus input, which the CallFrameInfo::Handler interface doesn't
1139   // (and shouldn't) have any way to report.
1140   virtual void ClearingCFARule(uint64 offset, CallFrameInfo::EntryKind kind,
1141                                uint64 insn_offset);
1142 
1143  private:
1144   // A logging sink function, as supplied by LUL's user.
1145   void (*log_)(const char*);
1146 
1147  protected:
1148   // The name of the file whose CFI we're reading.
1149   std::string filename_;
1150 
1151   // The name of the CFI section in that file.
1152   std::string section_;
1153 };
1154 
1155 using lul::CallFrameInfo;
1156 using lul::Summariser;
1157 
1158 // A class that accepts parsed call frame information from the DWARF
1159 // CFI parser and populates a google_breakpad::Module object with the
1160 // contents.
1161 class DwarfCFIToModule : public CallFrameInfo::Handler {
1162  public:
1163   // DwarfCFIToModule uses an instance of this class to report errors
1164   // detected while converting DWARF CFI to Breakpad STACK CFI records.
1165   class Reporter {
1166    public:
1167     // Create a reporter that writes messages to the message sink
1168     // |aLog|. FILE is the name of the file we're processing, and
1169     // SECTION is the name of the section within that file that we're
1170     // looking at (.debug_frame, .eh_frame, etc.).
Reporter(void (* aLog)(const char *),const std::string & file,const std::string & section)1171     Reporter(void (*aLog)(const char*), const std::string& file,
1172              const std::string& section)
1173         : log_(aLog), file_(file), section_(section) {}
~Reporter()1174     virtual ~Reporter() {}
1175 
1176     // The DWARF CFI entry at OFFSET says that REG is undefined, but the
1177     // Breakpad symbol file format cannot express this.
1178     virtual void UndefinedNotSupported(size_t offset, const UniqueString* reg);
1179 
1180     // The DWARF CFI entry at OFFSET says that REG uses a DWARF
1181     // expression to find its value, but parseDwarfExpr could not
1182     // convert it to a sequence of PfxInstrs.
1183     virtual void ExpressionCouldNotBeSummarised(size_t offset,
1184                                                 const UniqueString* reg);
1185 
1186    private:
1187     // A logging sink function, as supplied by LUL's user.
1188     void (*log_)(const char*);
1189 
1190    protected:
1191     std::string file_, section_;
1192   };
1193 
1194   // Register name tables. If TABLE is a vector returned by one of these
1195   // functions, then TABLE[R] is the name of the register numbered R in
1196   // DWARF call frame information.
1197   class RegisterNames {
1198    public:
1199     // Intel's "x86" or IA-32.
1200     static unsigned int I386();
1201 
1202     // AMD x86_64, AMD64, Intel EM64T, or Intel 64
1203     static unsigned int X86_64();
1204 
1205     // ARM.
1206     static unsigned int ARM();
1207 
1208     // AARCH64.
1209     static unsigned int ARM64();
1210 
1211     // MIPS.
1212     static unsigned int MIPS();
1213   };
1214 
1215   // Create a handler for the dwarf2reader::CallFrameInfo parser that
1216   // records the stack unwinding information it receives in SUMM.
1217   //
1218   // Use REGISTER_NAMES[I] as the name of register number I; *this
1219   // keeps a reference to the vector, so the vector should remain
1220   // alive for as long as the DwarfCFIToModule does.
1221   //
1222   // Use REPORTER for reporting problems encountered in the conversion
1223   // process.
DwarfCFIToModule(const unsigned int num_dw_regs,Reporter * reporter,ByteReader * reader,UniqueStringUniverse * usu,Summariser * summ)1224   DwarfCFIToModule(const unsigned int num_dw_regs, Reporter* reporter,
1225                    ByteReader* reader,
1226                    /*MOD*/ UniqueStringUniverse* usu,
1227                    /*OUT*/ Summariser* summ)
1228       : summ_(summ),
1229         usu_(usu),
1230         num_dw_regs_(num_dw_regs),
1231         reporter_(reporter),
1232         reader_(reader),
1233         return_address_(-1) {}
~DwarfCFIToModule()1234   virtual ~DwarfCFIToModule() {}
1235 
1236   virtual bool Entry(size_t offset, uint64 address, uint64 length,
1237                      uint8 version, const std::string& augmentation,
1238                      unsigned return_address) override;
1239   virtual bool UndefinedRule(uint64 address, int reg) override;
1240   virtual bool SameValueRule(uint64 address, int reg) override;
1241   virtual bool OffsetRule(uint64 address, int reg, int base_register,
1242                           long offset) override;
1243   virtual bool ValOffsetRule(uint64 address, int reg, int base_register,
1244                              long offset) override;
1245   virtual bool RegisterRule(uint64 address, int reg,
1246                             int base_register) override;
1247   virtual bool ExpressionRule(uint64 address, int reg,
1248                               const std::string& expression) override;
1249   virtual bool ValExpressionRule(uint64 address, int reg,
1250                                  const std::string& expression) override;
1251   virtual bool End() override;
1252 
1253  private:
1254   // Return the name to use for register I.
1255   const UniqueString* RegisterName(int i);
1256 
1257   // The Summariser to which we should give entries
1258   Summariser* summ_;
1259 
1260   // Universe for creating UniqueStrings in, should that be necessary.
1261   UniqueStringUniverse* usu_;
1262 
1263   // The number of Dwarf-defined register names for this architecture.
1264   const unsigned int num_dw_regs_;
1265 
1266   // The reporter to use to report problems.
1267   Reporter* reporter_;
1268 
1269   // The ByteReader to use for parsing Dwarf expressions.
1270   ByteReader* reader_;
1271 
1272   // The section offset of the current frame description entry, for
1273   // use in error messages.
1274   size_t entry_offset_;
1275 
1276   // The return address column for that entry.
1277   unsigned return_address_;
1278 };
1279 
1280 // Convert the Dwarf expression in |expr| into PfxInstrs stored in the
1281 // SecMap referred to by |summ|, and return the index of the starting
1282 // PfxInstr added, which must be >= 0.  In case of failure return -1.
1283 int32_t parseDwarfExpr(Summariser* summ, const ByteReader* reader,
1284                        std::string expr, bool debug, bool pushCfaAtStart,
1285                        bool derefAtEnd);
1286 
1287 }  // namespace lul
1288 
1289 #endif  // LulDwarfExt_h
1290