readdwarf.c revision 4c3b2379fb2cb97f762617df7770b042b1f8a59c
1
2/*--------------------------------------------------------------------*/
3/*--- Read DWARF1/2/3/4 debug info.                    readdwarf.c ---*/
4/*--------------------------------------------------------------------*/
5
6/*
7   This file is part of Valgrind, a dynamic binary instrumentation
8   framework.
9
10   Copyright (C) 2000-2012 Julian Seward
11      jseward@acm.org
12
13   This program is free software; you can redistribute it and/or
14   modify it under the terms of the GNU General Public License as
15   published by the Free Software Foundation; either version 2 of the
16   License, or (at your option) any later version.
17
18   This program is distributed in the hope that it will be useful, but
19   WITHOUT ANY WARRANTY; without even the implied warranty of
20   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
21   General Public License for more details.
22
23   You should have received a copy of the GNU General Public License
24   along with this program; if not, write to the Free Software
25   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
26   02111-1307, USA.
27
28   The GNU General Public License is contained in the file COPYING.
29*/
30
31#if defined(VGO_linux) || defined(VGO_darwin)
32
33#include "pub_core_basics.h"
34#include "pub_core_debuginfo.h"
35#include "pub_core_libcbase.h"
36#include "pub_core_libcassert.h"
37#include "pub_core_libcprint.h"
38#include "pub_core_options.h"
39#include "pub_core_xarray.h"
40#include "pub_core_tooliface.h"    /* VG_(needs) */
41#include "priv_misc.h"             /* dinfo_zalloc/free/strdup */
42#include "priv_d3basics.h"
43#include "priv_tytypes.h"
44#include "priv_storage.h"
45#include "priv_readdwarf.h"        /* self */
46
47
48/*------------------------------------------------------------*/
49/*---                                                      ---*/
50/*--- Read line number and CFI info from DWARF1, DWARF2    ---*/
51/*--- and to some extent DWARF3 sections.                  ---*/
52/*---                                                      ---*/
53/*------------------------------------------------------------*/
54
55/*------------------------------------------------------------*/
56/*--- Expanding arrays of words, for holding file name and ---*/
57/*--- directory name arrays.                               ---*/
58/*------------------------------------------------------------*/
59
60typedef
61   struct {
62      Word* tab;
63      UInt  tab_size;
64      UInt  tab_used;
65   }
66   WordArray;
67
68static void init_WordArray ( WordArray* wa )
69{
70   wa->tab      = NULL;
71   wa->tab_size = 0;
72   wa->tab_used = 0;
73}
74
75static void free_WordArray ( WordArray* wa )
76{
77   if (wa->tab) {
78      vg_assert(wa->tab_size > 0);
79      ML_(dinfo_free)(wa->tab);
80   }
81   init_WordArray(wa);
82}
83
84static void addto_WordArray ( WordArray* wa, Word w )
85{
86   UInt  new_size, i;
87   Word* new_tab;
88
89   if (0) VG_(printf)("<<ADD %p (new sz = %d) >>\n",
90                      (HChar*)w, wa->tab_used+1);
91
92   if (wa->tab_used < wa->tab_size) {
93      /* fine */
94   } else {
95      /* expand array */
96      if (0) VG_(printf)("EXPAND ARRAY from %d\n", wa->tab_size);
97      vg_assert(wa->tab_used == wa->tab_size);
98      vg_assert( (wa->tab_size == 0 && wa->tab == NULL)
99                 || (wa->tab_size != 0 && wa->tab != NULL) );
100      new_size = wa->tab_size == 0 ? 8 : 2 * wa->tab_size;
101      new_tab  = ML_(dinfo_zalloc)("di.aWA.1", new_size * sizeof(Word));
102      vg_assert(new_tab != NULL);
103      for (i = 0; i < wa->tab_used; i++)
104         new_tab[i] = wa->tab[i];
105      wa->tab_size = new_size;
106      if (wa->tab)
107         ML_(dinfo_free)(wa->tab);
108      wa->tab = new_tab;
109   }
110
111   vg_assert(wa->tab_used < wa->tab_size);
112   vg_assert(wa->tab_size > 0);
113   wa->tab[wa->tab_used] = w;
114   wa->tab_used++;
115}
116
117static Word index_WordArray ( /*OUT*/Bool* inRange, WordArray* wa, Int i )
118{
119   vg_assert(inRange);
120   if (i >= 0 && i < wa->tab_used) {
121      *inRange = True;
122      return wa->tab[i];
123   } else {
124      *inRange = False;
125      return 0;
126   }
127}
128
129
130/*------------------------------------------------------------*/
131/*--- Read DWARF2 format line number info.                 ---*/
132/*------------------------------------------------------------*/
133
134/* Structure holding info extracted from the a .debug_line
135   section.  */
136typedef struct
137{
138  ULong  li_length;
139  UShort li_version;
140  ULong  li_header_length;
141  UChar  li_min_insn_length;
142  UChar  li_max_ops_per_insn;
143  UChar  li_default_is_stmt;
144  Int    li_line_base;
145  UChar  li_line_range;
146  UChar  li_opcode_base;
147}
148DebugLineInfo;
149
150/* Structure holding additional infos found from a .debug_info
151 * compilation unit block */
152typedef struct
153{
154  /* Feel free to add more members here if you need ! */
155  HChar* compdir;  /* Compilation directory - points to .debug_info */
156  HChar* name;     /* Main file name - points to .debug_info */
157  ULong stmt_list; /* Offset in .debug_line */
158  Bool  dw64;      /* 64-bit Dwarf? */
159}
160UnitInfo;
161
162/* Line number opcodes.  */
163enum dwarf_line_number_ops
164  {
165    DW_LNS_extended_op = 0,
166    DW_LNS_copy = 1,
167    DW_LNS_advance_pc = 2,
168    DW_LNS_advance_line = 3,
169    DW_LNS_set_file = 4,
170    DW_LNS_set_column = 5,
171    DW_LNS_negate_stmt = 6,
172    DW_LNS_set_basic_block = 7,
173    DW_LNS_const_add_pc = 8,
174    DW_LNS_fixed_advance_pc = 9,
175    /* DWARF 3.  */
176    DW_LNS_set_prologue_end = 10,
177    DW_LNS_set_epilogue_begin = 11,
178    DW_LNS_set_isa = 12
179  };
180
181/* Line number extended opcodes.  */
182enum dwarf_line_number_x_ops
183  {
184    DW_LNE_end_sequence = 1,
185    DW_LNE_set_address = 2,
186    DW_LNE_define_file = 3,
187    DW_LNE_set_discriminator = 4
188  };
189
190typedef struct
191{
192  /* Information for the last statement boundary.
193   * Needed to calculate statement lengths. */
194  Addr  last_address;
195  UInt  last_file;
196  UInt  last_line;
197
198  Addr  address;
199  UInt  file;
200  UInt  line;
201  UInt  column;
202  Int   is_stmt;
203  Int   basic_block;
204  UChar end_sequence;
205} LineSMR;
206
207
208/* FIXME: duplicated in readdwarf3.c */
209static
210ULong read_leb128 ( UChar* data, Int* length_return, Int sign )
211{
212  ULong  result = 0;
213  UInt   num_read = 0;
214  Int    shift = 0;
215  UChar  byte;
216
217  vg_assert(sign == 0 || sign == 1);
218
219  do
220    {
221      byte = * data ++;
222      num_read ++;
223
224      result |= ((ULong)(byte & 0x7f)) << shift;
225
226      shift += 7;
227
228    }
229  while (byte & 0x80);
230
231  if (length_return != NULL)
232    * length_return = num_read;
233
234  if (sign && (shift < 64) && (byte & 0x40))
235    result |= -(1ULL << shift);
236
237  return result;
238}
239
240/* Small helper functions easier to use
241 * value is returned and the given pointer is
242 * moved past end of leb128 data */
243/* FIXME: duplicated in readdwarf3.c */
244static ULong read_leb128U( UChar **data )
245{
246  Int len;
247  ULong val = read_leb128( *data, &len, 0 );
248  *data += len;
249  return val;
250}
251
252/* Same for signed data */
253/* FIXME: duplicated in readdwarf3.c */
254static Long read_leb128S( UChar **data )
255{
256   Int len;
257   ULong val = read_leb128( *data, &len, 1 );
258   *data += len;
259   return (Long)val;
260}
261
262/* Read what the DWARF3 spec calls an "initial length field".  This
263   uses up either 4 or 12 bytes of the input and produces a 32-bit or
264   64-bit number respectively.
265
266   Read 32-bit value from p.  If it is 0xFFFFFFFF, instead read a
267   64-bit bit value from p+4.  This is used in 64-bit dwarf to encode
268   some table lengths.
269
270   XXX this is a hack: the endianness of the initial length field is
271   specified by the DWARF we're reading.  This happens to work only
272   because we don't do cross-arch jitting, hence this code runs on a
273   platform of the same endianness as the DWARF it is reading.  Same
274   applies for initial lengths for CIE/FDEs and probably in zillions
275   of other places -- to be precise, exactly the places where
276   binutils/dwarf.c calls byte_get().
277*/
278static ULong read_initial_length_field ( UChar* p_img, /*OUT*/Bool* is64 )
279{
280   UInt w32 = ML_(read_UInt)(p_img);
281   if (w32 == 0xFFFFFFFF) {
282      *is64 = True;
283      return ML_(read_ULong)(p_img+4);
284   } else {
285      *is64 = False;
286      return (ULong)w32;
287   }
288}
289
290
291static LineSMR state_machine_regs;
292
293static
294void reset_state_machine ( Int is_stmt )
295{
296   if (0) VG_(printf)("smr.a := %p (reset)\n", NULL );
297   state_machine_regs.last_address = 0;
298   state_machine_regs.last_file = 1;
299   state_machine_regs.last_line = 1;
300   state_machine_regs.address = 0;
301   state_machine_regs.file = 1;
302   state_machine_regs.line = 1;
303   state_machine_regs.column = 0;
304   state_machine_regs.is_stmt = is_stmt;
305   state_machine_regs.basic_block = 0;
306   state_machine_regs.end_sequence = 0;
307}
308
309/* Look up a directory name, or return NULL if unknown. */
310static
311HChar* lookupDir ( Int filename_index,
312                   WordArray* fnidx2dir,
313                   WordArray* dirnames )
314{
315   Bool inRange;
316   Word diridx, dirname;
317
318   diridx = index_WordArray( &inRange, fnidx2dir, filename_index );
319   if (!inRange) goto bad;
320
321   dirname = index_WordArray( &inRange, dirnames, (Int)diridx );
322   if (!inRange) goto bad;
323
324   return (HChar*)dirname;
325  bad:
326   return NULL;
327}
328
329////////////////////////////////////////////////////////////////////
330////////////////////////////////////////////////////////////////////
331
332/* Handled an extended line op starting at 'data'.  Returns the number
333   of bytes that 'data' should be advanced by. */
334static
335Word process_extended_line_op( struct _DebugInfo* di,
336                               WordArray* filenames,
337                               WordArray* dirnames,
338                               WordArray* fnidx2dir,
339                               UChar* data, Int is_stmt)
340{
341   UChar  op_code;
342   Int    bytes_read;
343   UInt   len;
344   HChar* name;
345   Addr   adr;
346
347   len = read_leb128 (data, & bytes_read, 0);
348   data += bytes_read;
349
350   if (len == 0) {
351      VG_(message)(Vg_UserMsg,
352                   "Warning: DWARF2 reader: "
353                   "Badly formed extended line op encountered\n");
354      return (Word)bytes_read;
355   }
356
357   len += bytes_read;
358   op_code = * data ++;
359
360   if (0) VG_(printf)("dwarf2: ext OPC: %d\n", op_code);
361
362   switch (op_code) {
363      case DW_LNE_end_sequence:
364         if (0) VG_(printf)("1001: si->o %#lx, smr.a %#lx\n",
365                            di->text_debug_bias, state_machine_regs.address );
366         /* JRS: added for compliance with spec; is pointless due to
367            reset_state_machine below */
368         state_machine_regs.end_sequence = 1;
369
370         if (state_machine_regs.is_stmt) {
371            if (state_machine_regs.last_address) {
372               Bool inRange = False;
373               const HChar* filename
374                  = (HChar*)index_WordArray( &inRange, filenames,
375                                             state_machine_regs.last_file);
376               if (!inRange || !filename)
377                  filename = "???";
378               ML_(addLineInfo) (
379                  di,
380                  filename,
381                  lookupDir( state_machine_regs.last_file,
382                             fnidx2dir, dirnames ),
383                  di->text_debug_bias + state_machine_regs.last_address,
384                  di->text_debug_bias + state_machine_regs.address,
385                  state_machine_regs.last_line, 0
386               );
387            }
388         }
389         reset_state_machine (is_stmt);
390         if (di->ddump_line)
391            VG_(printf)("  Extended opcode %d: End of Sequence\n\n",
392                        (Int)op_code);
393         break;
394
395      case DW_LNE_set_address:
396         adr = ML_(read_Addr)(data);
397         state_machine_regs.address = adr;
398         if (di->ddump_line)
399            VG_(printf)("  Extended opcode %d: set Address to 0x%lx\n",
400                        (Int)op_code, (Addr)adr);
401         break;
402
403      case DW_LNE_define_file:
404         name = (HChar *)data;
405         addto_WordArray( filenames, (Word)ML_(addStr)(di,name,-1) );
406         data += VG_(strlen) ((char *) data) + 1;
407         read_leb128 (data, & bytes_read, 0);
408         data += bytes_read;
409         read_leb128 (data, & bytes_read, 0);
410         data += bytes_read;
411         read_leb128 (data, & bytes_read, 0);
412         if (di->ddump_line)
413            VG_(printf)("  DWARF2-line: set_address\n");
414         break;
415
416      case DW_LNE_set_discriminator:
417         read_leb128 (data, & bytes_read, 0);
418         data += bytes_read;
419         break;
420
421      default:
422         if (di->ddump_line)
423            VG_(printf)("process_extended_line_op:default\n");
424         break;
425   }
426
427   return (Word)len;
428}
429
430////////////////////////////////////////////////////////////////////
431////////////////////////////////////////////////////////////////////
432
433/* read a .debug_line section block for a compilation unit
434 *
435 * Input:   - theBlock must point to the start of the block
436 *            for the given compilation unit
437 *          - ui contains additional info like the compilation dir
438 *            for this unit
439 *
440 * Output: - si debug info structures get updated
441 */
442static
443void read_dwarf2_lineblock ( struct _DebugInfo* di,
444                             UnitInfo* ui,
445                             UChar*    theBlock, /* IMAGE */
446                             Int       noLargerThan )
447{
448   Int            i;
449   DebugLineInfo  info;
450   UChar*         standard_opcodes;
451   UChar*         end_of_sequence;
452   Bool           is64;
453   WordArray      filenames;
454   WordArray      dirnames;
455   WordArray      fnidx2dir;
456
457   UChar*         external = theBlock;
458   UChar*         data = theBlock;
459
460   /* filenames is an array of file names harvested from the DWARF2
461      info.  Entry [0] is NULL and is never referred to by the state
462      machine.
463
464      Similarly, dirnames is an array of directory names.  Entry [0]
465      is also NULL and denotes "we don't know what the path is", since
466      that is different from "the path is the empty string".  Unlike
467      the file name table, the state machine does refer to entry [0],
468      which basically means "." ("the current directory of the
469      compilation", whatever that means, according to the DWARF3
470      spec.)
471
472      fnidx2dir is an array of indexes into the dirnames table.
473      (confused yet?)  filenames[] and fnidx2dir[] are indexed
474      together.  That is, for some index i in the filename table, then
475
476         the filename  is filenames[i]
477         the directory is dirnames[ fnidx2dir[i] ] */
478
479   /* Fails due to gcc padding ...
480   vg_assert(sizeof(DWARF2_External_LineInfo)
481             == sizeof(DWARF2_Internal_LineInfo));
482   */
483
484   init_WordArray(&filenames);
485   init_WordArray(&dirnames);
486   init_WordArray(&fnidx2dir);
487
488   /* DWARF2 starts numbering filename entries at 1, so we need to
489      add a dummy zeroth entry to the table.  The zeroth dirnames
490      entry denotes 'current directory of compilation' so we might
491      as well make the fnidx2dir zeroth entry denote that.
492   */
493   addto_WordArray( &filenames, (Word)NULL );
494
495   if (ui->compdir)
496      addto_WordArray( &dirnames, (Word)ML_(addStr)(di, ui->compdir, -1) );
497   else
498      addto_WordArray( &dirnames, (Word)ML_(addStr)(di, ".", -1) );
499
500   addto_WordArray( &fnidx2dir, (Word)0 );  /* compilation dir */
501
502   info.li_length = read_initial_length_field( external, &is64 );
503   external += is64 ? 12 : 4;
504   if (di->ddump_line)
505      VG_(printf)("  Length:                      %llu\n",
506                  info.li_length);
507
508   /* Check the length of the block.  */
509   if (info.li_length > noLargerThan) {
510      ML_(symerr)(di, True,
511                  "DWARF line info appears to be corrupt "
512                  "- the section is too small");
513      goto out;
514   }
515
516   /* Check its version number.  */
517   info.li_version = ML_(read_UShort)(external);
518   external += 2;
519   if (di->ddump_line)
520      VG_(printf)("  DWARF Version:               %d\n",
521                  (Int)info.li_version);
522
523   if (info.li_version != 2 && info.li_version != 3 && info.li_version != 4) {
524      ML_(symerr)(di, True,
525                  "Only DWARF version 2, 3 and 4 line info "
526                  "is currently supported.");
527      goto out;
528   }
529
530   info.li_header_length = ui->dw64 ? ML_(read_ULong)(external)
531                                    : (ULong)(ML_(read_UInt)(external));
532   external += ui->dw64 ? 8 : 4;
533   if (di->ddump_line)
534      VG_(printf)("  Prologue Length:             %llu\n",
535                  info.li_header_length);
536
537   info.li_min_insn_length = * ((UChar *)external);
538   external += 1;
539   if (di->ddump_line)
540      VG_(printf)("  Minimum Instruction Length:  %d\n",
541                  (Int)info.li_min_insn_length);
542
543   /* We only support machines with one opcode per instruction
544      for now. If we ever want to support VLIW machines there is
545      code to handle multiple opcodes per instruction in the
546      patch attached to BZ#233595.
547   */
548   if (info.li_version >= 4) {
549      info.li_max_ops_per_insn = * ((UChar *)external);
550      if (info.li_max_ops_per_insn != 1) {
551         ML_(symerr)(di, True,
552                     "Invalid Maximum Ops Per Insn in line info.");
553         goto out;
554      }
555      external += 1;
556      if (di->ddump_line)
557         VG_(printf)("  Maximum Ops Per Insn:        %d\n",
558                  (Int)info.li_max_ops_per_insn);
559   } else {
560      info.li_max_ops_per_insn = 1;
561   }
562
563   info.li_default_is_stmt = * ((UChar *)external);
564   external += 1;
565   if (di->ddump_line)
566      VG_(printf)("  Initial value of 'is_stmt':  %d\n",
567                  (Int)info.li_default_is_stmt);
568
569   /* Josef Weidendorfer (20021021) writes:
570
571      It seems to me that the Intel Fortran compiler generates bad
572      DWARF2 line info code: It sets "is_stmt" of the state machine in
573      the the line info reader to be always false. Thus, there is
574      never a statement boundary generated and therefore never a
575      instruction range/line number mapping generated for valgrind.
576
577      Please have a look at the DWARF2 specification, Ch. 6.2
578      (x86.ddj.com/ftp/manuals/tools/dwarf.pdf).  Perhaps I understand
579      this wrong, but I don't think so.
580
581      I just had a look at the GDB DWARF2 reader...  They completely
582      ignore "is_stmt" when recording line info ;-) That's the reason
583      "objdump -S" works on files from the the intel fortran compiler.
584
585      Therefore: */
586   info.li_default_is_stmt = True;
587
588   /* JRS: changed (UInt*) to (UChar*) */
589   info.li_line_base = * ((UChar *)external);
590   info.li_line_base = (Int)(signed char)info.li_line_base;
591   external += 1;
592   if (di->ddump_line)
593      VG_(printf)("  Line Base:                   %d\n",
594                  info.li_line_base);
595
596   info.li_line_range = * ((UChar *)external);
597   external += 1;
598   if (di->ddump_line)
599      VG_(printf)("  Line Range:                  %d\n",
600                  (Int)info.li_line_range);
601
602   info.li_opcode_base = * ((UChar *)external);
603   external += 1;
604   if (di->ddump_line)
605      VG_(printf)("  Opcode Base:                 %d\n\n",
606                  info.li_opcode_base);
607
608   if (0) VG_(printf)("dwarf2: line base: %d, range %d, opc base: %d\n",
609                      (Int)info.li_line_base,
610                      (Int)info.li_line_range,
611                      (Int)info.li_opcode_base);
612
613   end_of_sequence = data + info.li_length
614                          + (is64 ? 12 : 4);
615
616   reset_state_machine (info.li_default_is_stmt);
617
618   /* Read the contents of the Opcodes table.  */
619   standard_opcodes = external;
620   if (di->ddump_line) {
621      VG_(printf)(" Opcodes:\n");
622      for (i = 1; i < (Int)info.li_opcode_base; i++) {
623         VG_(printf)("  Opcode %d has %d args\n",
624                     i, (Int)standard_opcodes[i-1]);
625      }
626      VG_(printf)("\n");
627   }
628
629   /* Read the contents of the Directory table.  */
630   data = standard_opcodes + info.li_opcode_base - 1;
631
632   if (di->ddump_line)
633      VG_(printf)(" The Directory Table%s\n",
634                  *data == 0 ? " is empty." : ":" );
635
636   while (* data != 0) {
637
638#     define NBUF 4096
639      static HChar buf[NBUF];
640
641      if (di->ddump_line)
642         VG_(printf)("  %s\n", data);
643
644      /* If data[0] is '/', then 'data' is an absolute path and we
645         don't mess with it.  Otherwise, if we can, construct the
646         'path ui->compdir' ++ "/" ++ 'data'. */
647
648      if (*data != '/'
649          /* not an absolute path */
650          && ui->compdir != NULL
651          /* actually got something sensible for compdir */
652          && VG_(strlen)(ui->compdir) + VG_(strlen)((HChar *)data) + 5/*paranoia*/ < NBUF
653          /* it's short enough to concatenate */)
654      {
655         buf[0] = 0;
656         VG_(strcat)(buf, ui->compdir);
657         VG_(strcat)(buf, "/");
658         VG_(strcat)(buf, (HChar *)data);
659         vg_assert(VG_(strlen)(buf) < NBUF);
660         addto_WordArray( &dirnames, (Word)ML_(addStr)(di,buf,-1) );
661         if (0) VG_(printf)("rel path  %s\n", buf);
662      } else {
663         /* just use 'data'. */
664        addto_WordArray( &dirnames, (Word)ML_(addStr)(di,(HChar *)data,-1) );
665         if (0) VG_(printf)("abs path  %s\n", data);
666      }
667
668      data += VG_(strlen)((HChar *)data) + 1;
669
670#     undef NBUF
671   }
672
673   if (di->ddump_line)
674      VG_(printf)("\n");
675
676   if (*data != 0) {
677      ML_(symerr)(di, True,
678                  "can't find NUL at end of DWARF2 directory table");
679      goto out;
680   }
681   data ++;
682
683   /* Read the contents of the File Name table.  This produces a bunch
684      of file names, and for each, an index to the corresponding
685      directory name entry. */
686   if (di->ddump_line) {
687      VG_(printf)(" The File Name Table:\n");
688      VG_(printf)("  Entry	Dir	Time	Size	Name\n");
689   }
690
691   i = 1;
692   while (* data != 0) {
693      HChar* name;
694      Int    bytes_read, diridx;
695      Int    uu_time, uu_size; /* unused, and a guess */
696      name = (HChar *)data;
697      data += VG_(strlen) (name) + 1;
698
699      diridx = read_leb128 (data, & bytes_read, 0);
700      data += bytes_read;
701      uu_time = read_leb128 (data, & bytes_read, 0);
702      data += bytes_read;
703      uu_size = read_leb128 (data, & bytes_read, 0);
704      data += bytes_read;
705
706      addto_WordArray( &filenames, (Word)ML_(addStr)(di,name,-1) );
707      addto_WordArray( &fnidx2dir, (Word)diridx );
708      if (0) VG_(printf)("file %s diridx %d\n", name, diridx );
709      if (di->ddump_line)
710         VG_(printf)("  %d\t%d\t%d\t%d\t%s\n",
711                     i, diridx, uu_time, uu_size, name);
712      i++;
713   }
714
715   if (di->ddump_line)
716      VG_(printf)("\n");
717
718   if (*data != 0) {
719      ML_(symerr)(di, True,
720                  "can't find NUL at end of DWARF2 file name table");
721      goto out;
722   }
723   data ++;
724
725   if (di->ddump_line)
726      VG_(printf)(" Line Number Statements:\n");
727
728   /* Now display the statements.  */
729
730   while (data < end_of_sequence) {
731
732      UChar op_code;
733      Int           adv;
734      Int           bytes_read;
735
736      op_code = * data ++;
737
738      if (0) VG_(printf)("dwarf2: OPC: %d\n", op_code);
739
740      if (op_code >= info.li_opcode_base) {
741
742         Int advAddr;
743         op_code -= info.li_opcode_base;
744         adv      = (op_code / info.li_line_range)
745                       * info.li_min_insn_length;
746         advAddr = adv;
747         state_machine_regs.address += adv;
748
749         if (0) VG_(printf)("smr.a += %#x\n", adv );
750         adv = (op_code % info.li_line_range) + info.li_line_base;
751         if (0) VG_(printf)("1002: di->o %#lx, smr.a %#lx\n",
752                            di->text_debug_bias, state_machine_regs.address );
753         state_machine_regs.line += adv;
754
755         if (di->ddump_line)
756            VG_(printf)("  Special opcode %d: advance Address by %d "
757                        "to 0x%lx and Line by %d to %d\n",
758                        (Int)op_code, advAddr, state_machine_regs.address,
759                        (Int)adv, (Int)state_machine_regs.line );
760
761         if (state_machine_regs.is_stmt) {
762            /* only add a statement if there was a previous boundary */
763            if (state_machine_regs.last_address) {
764               Bool inRange = False;
765               const HChar* filename
766                  = (HChar*)index_WordArray( &inRange, &filenames,
767                                             state_machine_regs.last_file);
768               if (!inRange || !filename)
769                  filename = "???";
770               ML_(addLineInfo)(
771                  di,
772                  filename,
773                  lookupDir( state_machine_regs.last_file,
774                             &fnidx2dir, &dirnames ),
775                  di->text_debug_bias + state_machine_regs.last_address,
776                  di->text_debug_bias + state_machine_regs.address,
777                  state_machine_regs.last_line,
778                  0
779               );
780            }
781            state_machine_regs.last_address = state_machine_regs.address;
782            state_machine_regs.last_file = state_machine_regs.file;
783            state_machine_regs.last_line = state_machine_regs.line;
784         }
785
786      }
787
788      else { /* ! (op_code >= info.li_opcode_base) */
789
790      switch (op_code) {
791         case DW_LNS_extended_op:
792            data += process_extended_line_op (
793                       di, &filenames, &dirnames, &fnidx2dir,
794                       data, info.li_default_is_stmt);
795            break;
796
797         case DW_LNS_copy:
798            if (0) VG_(printf)("1002: di->o %#lx, smr.a %#lx\n",
799                               di->text_debug_bias, state_machine_regs.address );
800            if (state_machine_regs.is_stmt) {
801               /* only add a statement if there was a previous boundary */
802               if (state_machine_regs.last_address) {
803                  Bool inRange = False;
804                  const HChar* filename
805                     = (HChar*)index_WordArray( &inRange, &filenames,
806                                                state_machine_regs.last_file );
807                  if (!inRange || !filename)
808                     filename = "???";
809                  ML_(addLineInfo)(
810                     di,
811                     filename,
812                     lookupDir( state_machine_regs.last_file,
813                                &fnidx2dir, &dirnames ),
814                     di->text_debug_bias + state_machine_regs.last_address,
815                     di->text_debug_bias + state_machine_regs.address,
816                     state_machine_regs.last_line,
817                     0
818                  );
819               }
820               state_machine_regs.last_address = state_machine_regs.address;
821               state_machine_regs.last_file = state_machine_regs.file;
822               state_machine_regs.last_line = state_machine_regs.line;
823            }
824            state_machine_regs.basic_block = 0; /* JRS added */
825            if (di->ddump_line)
826               VG_(printf)("  Copy\n");
827            break;
828
829         case DW_LNS_advance_pc:
830            adv = info.li_min_insn_length
831                     * read_leb128 (data, & bytes_read, 0);
832            data += bytes_read;
833            state_machine_regs.address += adv;
834            if (0) VG_(printf)("smr.a += %#x\n", adv );
835            if (di->ddump_line)
836               VG_(printf)("  Advance PC by %d to 0x%lx\n",
837                           (Int)adv, state_machine_regs.address);
838            break;
839
840         case DW_LNS_advance_line:
841            adv = read_leb128 (data, & bytes_read, 1);
842            data += bytes_read;
843            state_machine_regs.line += adv;
844            if (di->ddump_line)
845               VG_(printf)("  Advance Line by %d to %d\n",
846                           (Int)adv, (Int)state_machine_regs.line);
847            break;
848
849         case DW_LNS_set_file:
850            adv = read_leb128 (data, & bytes_read, 0);
851            data += bytes_read;
852            state_machine_regs.file = adv;
853            if (di->ddump_line)
854               VG_(printf)("  Set File Name to entry %d in the File Name Table\n",
855                           (Int)adv);
856            break;
857
858         case DW_LNS_set_column:
859            adv = read_leb128 (data, & bytes_read, 0);
860            data += bytes_read;
861            state_machine_regs.column = adv;
862            if (di->ddump_line)
863               VG_(printf)("  Set column to %d\n", (Int)adv);
864            break;
865
866         case DW_LNS_negate_stmt:
867            adv = state_machine_regs.is_stmt;
868            adv = ! adv;
869            state_machine_regs.is_stmt = adv;
870            if (di->ddump_line)
871               VG_(printf)("  DWARF2-line: negate_stmt\n");
872            break;
873
874         case DW_LNS_set_basic_block:
875            state_machine_regs.basic_block = 1;
876            if (di->ddump_line)
877               VG_(printf)("  DWARF2-line: set_basic_block\n");
878            break;
879
880         case DW_LNS_const_add_pc:
881            adv = (((255 - info.li_opcode_base) / info.li_line_range)
882                   * info.li_min_insn_length);
883            state_machine_regs.address += adv;
884            if (0) VG_(printf)("smr.a += %#x\n", adv );
885            if (di->ddump_line)
886               VG_(printf)("  Advance PC by constant %d to 0x%lx\n",
887                           (Int)adv, (Addr)state_machine_regs.address);
888            break;
889
890         case DW_LNS_fixed_advance_pc:
891            /* XXX: Need something to get 2 bytes */
892            adv = ML_(read_UShort)(data);
893            data += 2;
894            state_machine_regs.address += adv;
895            if (0) VG_(printf)("smr.a += %#x\n", adv );
896            if (di->ddump_line)
897               VG_(printf)("  DWARF2-line: fixed_advance_pc\n");
898            break;
899
900         case DW_LNS_set_prologue_end:
901            if (di->ddump_line)
902               VG_(printf)("  DWARF2-line: set_prologue_end\n");
903            break;
904
905         case DW_LNS_set_epilogue_begin:
906            if (di->ddump_line)
907               VG_(printf)("  DWARF2-line: set_epilogue_begin\n");
908            break;
909
910         case DW_LNS_set_isa:
911            /*adv =*/ read_leb128 (data, & bytes_read, 0);
912            data += bytes_read;
913            if (di->ddump_line)
914               VG_(printf)("  DWARF2-line: set_isa\n");
915            break;
916
917         default: {
918            Int j;
919            for (j = standard_opcodes[op_code - 1]; j > 0 ; --j) {
920               read_leb128 (data, &bytes_read, 0);
921               data += bytes_read;
922            }
923            if (di->ddump_line)
924               VG_(printf)("  Unknown opcode %d\n", (Int)op_code);
925            break;
926         }
927      } /* switch (op_code) */
928
929      } /* if (op_code >= info.li_opcode_base) */
930
931   } /* while (data < end_of_sequence) */
932
933   if (di->ddump_line)
934      VG_(printf)("\n");
935
936  out:
937   free_WordArray(&filenames);
938   free_WordArray(&dirnames);
939   free_WordArray(&fnidx2dir);
940}
941
942////////////////////////////////////////////////////////////////////
943////////////////////////////////////////////////////////////////////
944
945/* Return abbrev for given code
946 * Returned pointer points to the tag
947 * */
948static UChar* lookup_abbrev( UChar* p, UInt acode )
949{
950   UInt code;
951   UInt name;
952   for( ; ; ) {
953      code = read_leb128U( &p );
954      if ( code == acode )
955         return p;
956      read_leb128U( &p ); /* skip tag */
957      p++;                /* skip has_children flag */
958      do {
959         name = read_leb128U( &p ); /* name */
960         read_leb128U( &p );   /* form */
961      }
962      while( name != 0 ); /* until name == form == 0 */
963   }
964   return NULL;
965}
966
967/* Read general information for a particular compile unit block in
968 * the .debug_info section. In particular read the name, compdir and
969 * stmt_list needed to parse the line number information.
970 *
971 * Input: - unitblock is the start of a compilation
972 *          unit block in .debuginfo section
973 *        - debugabbrev is start of .debug_abbrev section
974 *        - debugstr is start of .debug_str section
975 *        - debugstr_alt_img is start of .debug_str section in alt debug file
976 *
977 * Output: Fill members of ui pertaining to the compilation unit:
978 *         - ui->name is the name of the compilation unit
979 *         - ui->compdir is the compilation unit directory
980 *         - ui->stmt_list is the offset in .debug_line section
981 *                for the dbginfos of this compilation unit
982 *
983 * Note : the output strings are not allocated and point
984 * directly to the memory-mapped section.
985 */
986static
987void read_unitinfo_dwarf2( /*OUT*/UnitInfo* ui,
988                                  UChar*    unitblock_img,
989                                  UChar*    debugabbrev_img,
990                                  HChar*    debugstr_img,
991                                  HChar*    debugstr_alt_img )
992{
993   UInt   acode, abcode;
994   ULong  atoffs, blklen;
995   UShort ver;
996
997   UChar addr_size;
998   UChar* p = unitblock_img;
999   UChar* end_img;
1000   UChar* abbrev_img;
1001
1002   VG_(memset)( ui, 0, sizeof( UnitInfo ) );
1003   ui->stmt_list = -1LL;
1004
1005   /* Read the compilation unit header in .debug_info section - See p 70 */
1006
1007   /* This block length */
1008   blklen = read_initial_length_field( p, &ui->dw64 );
1009   p += ui->dw64 ? 12 : 4;
1010
1011   /* version should be 2, 3 or 4 */
1012   ver = ML_(read_UShort)(p);
1013   p += 2;
1014
1015   /* get offset in abbrev */
1016   atoffs = ui->dw64 ? ML_(read_ULong)(p) : (ULong)(ML_(read_UInt)(p));
1017   p += ui->dw64 ? 8 : 4;
1018
1019   /* Address size */
1020   addr_size = *p;
1021   p += 1;
1022
1023   end_img     = unitblock_img
1024                 + blklen + (ui->dw64 ? 12 : 4); /* End of this block */
1025   abbrev_img  = debugabbrev_img
1026                 + atoffs; /* Abbreviation data for this block */
1027
1028   /* Read the compilation unit entry - this is always the first DIE.
1029    * See DWARF4 para 7.5. */
1030   if ( p < end_img ) {
1031      UInt tag;
1032
1033      acode = read_leb128U( &p ); /* abbreviation code */
1034
1035      /* Read abbreviation header */
1036      abcode = read_leb128U( &abbrev_img ); /* abbreviation code */
1037      if ( acode != abcode ) {
1038         /* This isn't illegal, but somewhat unlikely. Normally the
1039          * first abbrev describes the first DIE, the compile_unit.
1040          * But maybe this abbrevation data is shared with another
1041          * or it is a NULL entry used for padding. See para 7.5.3. */
1042         abbrev_img = lookup_abbrev( debugabbrev_img + atoffs, acode );
1043      }
1044
1045      tag = read_leb128U( &abbrev_img );
1046
1047      if ( tag != 0x0011 /*TAG_compile_unit*/ )
1048         return; /* Not a compile unit (might be partial) or broken DWARF. */
1049
1050      abbrev_img++; /* DW_CHILDREN_yes or DW_CHILDREN_no */
1051
1052      /* And loop on entries */
1053      for ( ; ; ) {
1054         /* Read entry definition */
1055         UInt  name, form;
1056         ULong cval = -1LL;  /* Constant value read */
1057         HChar *sval = NULL; /* String value read */
1058         name = read_leb128U( &abbrev_img );
1059         form = read_leb128U( &abbrev_img );
1060         if ( name == 0 )
1061            break;
1062
1063         /* Read data */
1064         /* Attributes encoding explained p 71 */
1065         if ( form == 0x16 /* FORM_indirect */ )
1066            form = read_leb128U( &p );
1067         /* Decode form. For most kinds, Just skip the amount of data since
1068            we don't use it for now */
1069         /* JRS 9 Feb 06: This now handles 64-bit DWARF too.  In
1070            64-bit DWARF, lineptr (and loclistptr,macptr,rangelistptr
1071            classes) use FORM_data8, not FORM_data4.  Also,
1072            FORM_ref_addr and FORM_strp are 64-bit values, not 32-bit
1073            values. */
1074         /* TJH 27 Apr 10: in DWARF 4 lineptr (and loclistptr,macptr,
1075            rangelistptr classes) use FORM_sec_offset which is 64 bits
1076            in 64 bit DWARF and 32 bits in 32 bit DWARF. */
1077         /* JRS 20 Apr 11: LLVM-2.9 encodes DW_AT_stmt_list using
1078            FORM_addr rather than the FORM_data4 that GCC uses.  Hence
1079            handle FORM_addr too. */
1080         switch( form ) {
1081            /* Those cases extract the data properly */
1082            case 0x05: /* FORM_data2 */     cval = ML_(read_UShort)(p); p +=2; break;
1083            case 0x06: /* FORM_data4 */     cval = ML_(read_UInt)(p);   p +=4; break;
1084            case 0x0e: /* FORM_strp */      /* pointer in .debug_str */
1085                       /* 2006-01-01: only generate a value if
1086                          debugstr is non-NULL (which means that a
1087                          debug_str section was found) */
1088                                            if (debugstr_img && !ui->dw64)
1089                                               sval = debugstr_img + ML_(read_UInt)(p);
1090                                            if (debugstr_img && ui->dw64)
1091                                               sval = debugstr_img + ML_(read_ULong)(p);
1092                                            p += ui->dw64 ? 8 : 4;
1093                                            break;
1094            case 0x08: /* FORM_string */    sval = (HChar*)p;
1095                                            p += VG_(strlen)(sval) + 1; break;
1096            case 0x0b: /* FORM_data1 */     cval = *p; p++; break;
1097            case 0x17: /* FORM_sec_offset */if (ui->dw64) {
1098                                               cval = ML_(read_ULong)(p); p += 8;
1099                                            } else {
1100                                               cval = ML_(read_UInt)(p); p += 4;
1101                                            }; break;
1102
1103            case 0x07: /* FORM_data8 */     if (ui->dw64) cval = ML_(read_ULong)(p);
1104                                            p += 8; break;
1105                                            /* perhaps should assign
1106                                               unconditionally to cval? */
1107
1108            /* TODO : Following ones just skip data - implement if you need */
1109            case 0x01: /* FORM_addr */      p += addr_size; break;
1110            case 0x03: /* FORM_block2 */    p += ML_(read_UShort)(p) + 2; break;
1111            case 0x04: /* FORM_block4 */    p += ML_(read_UInt)(p) + 4; break;
1112            case 0x09: /* FORM_block */     /* fallthrough */
1113            case 0x18: /* FORM_exprloc */   { ULong block_len = read_leb128U( &p );
1114                                              p += block_len; break; }
1115            case 0x0a: /* FORM_block1 */    p += *p + 1; break;
1116            case 0x0c: /* FORM_flag */      p++; break;
1117            case 0x0d: /* FORM_sdata */     read_leb128S( &p ); break;
1118            case 0x0f: /* FORM_udata */     read_leb128U( &p ); break;
1119            case 0x10: /* FORM_ref_addr */  p += (ver == 2) ? addr_size : (ui->dw64 ? 8 : 4); break;
1120            case 0x11: /* FORM_ref1 */      p++; break;
1121            case 0x12: /* FORM_ref2 */      p += 2; break;
1122            case 0x13: /* FORM_ref4 */      p += 4; break;
1123            case 0x14: /* FORM_ref8 */      p += 8; break;
1124            case 0x15: /* FORM_ref_udata */ read_leb128U( &p ); break;
1125            case 0x19: /* FORM_flag_present */break;
1126            case 0x20: /* FORM_ref_sig8 */  p += 8; break;
1127            case 0x1f20: /* FORM_GNU_ref_alt */ p += ui->dw64 ? 8 : 4; break;
1128            case 0x1f21: /* FORM_GNU_strp_alt */
1129                                            if (debugstr_alt_img && !ui->dw64)
1130                                               sval = debugstr_alt_img + ML_(read_UInt)(p);
1131                                            if (debugstr_alt_img && ui->dw64)
1132                                               sval = debugstr_alt_img + ML_(read_ULong)(p);
1133                                            p += ui->dw64 ? 8 : 4;
1134                                            break;
1135
1136            default:
1137               VG_(printf)( "### unhandled dwarf2 abbrev form code 0x%x\n", form );
1138               break;
1139         }
1140
1141         /* Now store the members we need in the UnitInfo structure */
1142         if ( tag == 0x0011 /*TAG_compile_unit*/ ) {
1143                 if ( name == 0x03 ) ui->name = sval;      /* DW_AT_name */
1144            else if ( name == 0x1b ) ui->compdir = sval;   /* DW_AT_compdir */
1145            else if ( name == 0x10 ) ui->stmt_list = cval; /* DW_AT_stmt_list */
1146         }
1147      }
1148   } /* Just read the first DIE, if that wasn't the compile_unit then
1149      * this might have been a partial unit or broken DWARF info.
1150      * That's enough info for us, and we are not gdb ! */
1151}
1152
1153
1154////////////////////////////////////////////////////////////////////
1155////////////////////////////////////////////////////////////////////
1156
1157/* Collect the debug info from DWARF3 debugging sections
1158 * of a given module.
1159 *
1160 * Inputs: given .debug_xxx sections
1161 * Output: update di to contain all the DWARF3 debug infos
1162 */
1163void ML_(read_debuginfo_dwarf3)
1164        ( struct _DebugInfo* di,
1165          UChar* debug_info_img, Word debug_info_sz, /* .debug_info */
1166          UChar* debug_types_img, Word debug_types_sz, /* .debug_types */
1167          UChar* debug_abbv_img, Word debug_abbv_sz, /* .debug_abbrev */
1168          UChar* debug_line_img, Word debug_line_sz, /* .debug_line */
1169          HChar* debug_str_img,  Word debug_str_sz, /* .debug_str */
1170          HChar* debug_str_alt_img, Word debug_str_alt_sz ) /* .debug_str */
1171{
1172   UnitInfo ui;
1173   UShort   ver;
1174   UChar*   block_img;
1175   UChar*   end1_img;
1176   ULong    blklen;
1177   Bool     blklen_is_64;
1178   Int      blklen_len;
1179
1180   end1_img  = debug_info_img + debug_info_sz;
1181   blklen_len = 0;
1182
1183   /* Make sure we at least have a header for the first block */
1184   if (debug_info_sz < 4) {
1185      ML_(symerr)( di, True,
1186                   "Last block truncated in .debug_info; ignoring" );
1187      return;
1188   }
1189
1190   /* Iterate on all the blocks we find in .debug_info */
1191   for ( block_img = debug_info_img;
1192         block_img < end1_img - 4;
1193         block_img += blklen + blklen_len ) {
1194
1195      /* Read the compilation unit header in .debug_info section - See
1196         p 70 */
1197      /* This block length */
1198      blklen     = read_initial_length_field( block_img, &blklen_is_64 );
1199      blklen_len = blklen_is_64 ? 12 : 4;
1200      if ( block_img + blklen + blklen_len > end1_img ) {
1201         ML_(symerr)( di, True,
1202                      "Last block truncated in .debug_info; ignoring" );
1203         return;
1204      }
1205
1206      /* version should be 2 */
1207      ver = ML_(read_UShort)( block_img + blklen_len );
1208      if ( ver != 2 && ver != 3 && ver != 4 ) {
1209         ML_(symerr)( di, True,
1210                      "Ignoring non-Dwarf2/3/4 block in .debug_info" );
1211         continue;
1212      }
1213
1214      /* Fill ui with offset in .debug_line and compdir */
1215      if (0)
1216         VG_(printf)( "Reading UnitInfo at 0x%lx.....\n",
1217                      block_img - debug_info_img + 0UL );
1218      read_unitinfo_dwarf2( &ui, block_img,
1219                                 debug_abbv_img, debug_str_img,
1220                                 debug_str_alt_img );
1221      if (0)
1222         VG_(printf)( "   => LINES=0x%llx    NAME=%s     DIR=%s\n",
1223                      ui.stmt_list, ui.name, ui.compdir );
1224
1225      /* Ignore blocks with no .debug_line associated block */
1226      if ( ui.stmt_list == -1LL )
1227         continue;
1228
1229      if (0)
1230         VG_(printf)("debug_line_sz %ld, ui.stmt_list %lld  %s\n",
1231                     debug_line_sz, ui.stmt_list, ui.name );
1232      /* Read the .debug_line block for this compile unit */
1233      read_dwarf2_lineblock(
1234         di, &ui, debug_line_img + ui.stmt_list,
1235                  debug_line_sz  - ui.stmt_list );
1236   }
1237}
1238
1239
1240////////////////////////////////////////////////////////////////////
1241////////////////////////////////////////////////////////////////////
1242
1243/*------------------------------------------------------------*/
1244/*--- Read DWARF1 format line number info.                 ---*/
1245/*------------------------------------------------------------*/
1246
1247/* DWARF1 appears to be redundant, but nevertheless the Lahey Fortran
1248   compiler generates it.
1249*/
1250
1251/* The following three enums (dwarf_tag, dwarf_form, dwarf_attribute)
1252   are taken from the file include/elf/dwarf.h in the GNU gdb-6.0
1253   sources, which are Copyright 1992, 1993, 1995, 1999 Free Software
1254   Foundation, Inc and naturally licensed under the GNU General Public
1255   License version 2 or later.
1256*/
1257
1258/* Tag names and codes.  */
1259
1260enum dwarf_tag {
1261    TAG_padding			= 0x0000,
1262    TAG_array_type		= 0x0001,
1263    TAG_class_type		= 0x0002,
1264    TAG_entry_point		= 0x0003,
1265    TAG_enumeration_type	= 0x0004,
1266    TAG_formal_parameter	= 0x0005,
1267    TAG_global_subroutine	= 0x0006,
1268    TAG_global_variable		= 0x0007,
1269    				/* 0x0008 -- reserved */
1270				/* 0x0009 -- reserved */
1271    TAG_label			= 0x000a,
1272    TAG_lexical_block		= 0x000b,
1273    TAG_local_variable		= 0x000c,
1274    TAG_member			= 0x000d,
1275				/* 0x000e -- reserved */
1276    TAG_pointer_type		= 0x000f,
1277    TAG_reference_type		= 0x0010,
1278    TAG_compile_unit		= 0x0011,
1279    TAG_string_type		= 0x0012,
1280    TAG_structure_type		= 0x0013,
1281    TAG_subroutine		= 0x0014,
1282    TAG_subroutine_type		= 0x0015,
1283    TAG_typedef			= 0x0016,
1284    TAG_union_type		= 0x0017,
1285    TAG_unspecified_parameters	= 0x0018,
1286    TAG_variant			= 0x0019,
1287    TAG_common_block		= 0x001a,
1288    TAG_common_inclusion	= 0x001b,
1289    TAG_inheritance		= 0x001c,
1290    TAG_inlined_subroutine	= 0x001d,
1291    TAG_module			= 0x001e,
1292    TAG_ptr_to_member_type	= 0x001f,
1293    TAG_set_type		= 0x0020,
1294    TAG_subrange_type		= 0x0021,
1295    TAG_with_stmt		= 0x0022,
1296
1297    /* GNU extensions */
1298
1299    TAG_format_label		= 0x8000,  /* for FORTRAN 77 and Fortran 90 */
1300    TAG_namelist		= 0x8001,  /* For Fortran 90 */
1301    TAG_function_template	= 0x8002,  /* for C++ */
1302    TAG_class_template		= 0x8003   /* for C++ */
1303};
1304
1305/* Form names and codes.  */
1306
1307enum dwarf_form {
1308    FORM_ADDR	= 0x1,
1309    FORM_REF	= 0x2,
1310    FORM_BLOCK2	= 0x3,
1311    FORM_BLOCK4	= 0x4,
1312    FORM_DATA2	= 0x5,
1313    FORM_DATA4	= 0x6,
1314    FORM_DATA8	= 0x7,
1315    FORM_STRING	= 0x8
1316};
1317
1318/* Attribute names and codes.  */
1319
1320enum dwarf_attribute {
1321    AT_sibling			= (0x0010|FORM_REF),
1322    AT_location			= (0x0020|FORM_BLOCK2),
1323    AT_name			= (0x0030|FORM_STRING),
1324    AT_fund_type		= (0x0050|FORM_DATA2),
1325    AT_mod_fund_type		= (0x0060|FORM_BLOCK2),
1326    AT_user_def_type		= (0x0070|FORM_REF),
1327    AT_mod_u_d_type		= (0x0080|FORM_BLOCK2),
1328    AT_ordering			= (0x0090|FORM_DATA2),
1329    AT_subscr_data		= (0x00a0|FORM_BLOCK2),
1330    AT_byte_size		= (0x00b0|FORM_DATA4),
1331    AT_bit_offset		= (0x00c0|FORM_DATA2),
1332    AT_bit_size			= (0x00d0|FORM_DATA4),
1333				/* (0x00e0|FORM_xxxx) -- reserved */
1334    AT_element_list		= (0x00f0|FORM_BLOCK4),
1335    AT_stmt_list		= (0x0100|FORM_DATA4),
1336    AT_low_pc			= (0x0110|FORM_ADDR),
1337    AT_high_pc			= (0x0120|FORM_ADDR),
1338    AT_language			= (0x0130|FORM_DATA4),
1339    AT_member			= (0x0140|FORM_REF),
1340    AT_discr			= (0x0150|FORM_REF),
1341    AT_discr_value		= (0x0160|FORM_BLOCK2),
1342				/* (0x0170|FORM_xxxx) -- reserved */
1343				/* (0x0180|FORM_xxxx) -- reserved */
1344    AT_string_length		= (0x0190|FORM_BLOCK2),
1345    AT_common_reference		= (0x01a0|FORM_REF),
1346    AT_comp_dir			= (0x01b0|FORM_STRING),
1347        AT_const_value_string	= (0x01c0|FORM_STRING),
1348        AT_const_value_data2	= (0x01c0|FORM_DATA2),
1349        AT_const_value_data4	= (0x01c0|FORM_DATA4),
1350        AT_const_value_data8	= (0x01c0|FORM_DATA8),
1351        AT_const_value_block2	= (0x01c0|FORM_BLOCK2),
1352        AT_const_value_block4	= (0x01c0|FORM_BLOCK4),
1353    AT_containing_type		= (0x01d0|FORM_REF),
1354        AT_default_value_addr	= (0x01e0|FORM_ADDR),
1355        AT_default_value_data2	= (0x01e0|FORM_DATA2),
1356        AT_default_value_data4	= (0x01e0|FORM_DATA4),
1357        AT_default_value_data8	= (0x01e0|FORM_DATA8),
1358        AT_default_value_string	= (0x01e0|FORM_STRING),
1359    AT_friends			= (0x01f0|FORM_BLOCK2),
1360    AT_inline			= (0x0200|FORM_STRING),
1361    AT_is_optional		= (0x0210|FORM_STRING),
1362        AT_lower_bound_ref	= (0x0220|FORM_REF),
1363        AT_lower_bound_data2	= (0x0220|FORM_DATA2),
1364        AT_lower_bound_data4	= (0x0220|FORM_DATA4),
1365        AT_lower_bound_data8	= (0x0220|FORM_DATA8),
1366    AT_private			= (0x0240|FORM_STRING),
1367    AT_producer			= (0x0250|FORM_STRING),
1368    AT_program			= (0x0230|FORM_STRING),
1369    AT_protected		= (0x0260|FORM_STRING),
1370    AT_prototyped		= (0x0270|FORM_STRING),
1371    AT_public			= (0x0280|FORM_STRING),
1372    AT_pure_virtual		= (0x0290|FORM_STRING),
1373    AT_return_addr		= (0x02a0|FORM_BLOCK2),
1374    AT_abstract_origin		= (0x02b0|FORM_REF),
1375    AT_start_scope		= (0x02c0|FORM_DATA4),
1376    AT_stride_size		= (0x02e0|FORM_DATA4),
1377        AT_upper_bound_ref	= (0x02f0|FORM_REF),
1378        AT_upper_bound_data2	= (0x02f0|FORM_DATA2),
1379        AT_upper_bound_data4	= (0x02f0|FORM_DATA4),
1380        AT_upper_bound_data8	= (0x02f0|FORM_DATA8),
1381    AT_virtual			= (0x0300|FORM_STRING),
1382
1383    /* GNU extensions.  */
1384
1385    AT_sf_names			= (0x8000|FORM_DATA4),
1386    AT_src_info			= (0x8010|FORM_DATA4),
1387    AT_mac_info			= (0x8020|FORM_DATA4),
1388    AT_src_coords		= (0x8030|FORM_DATA4),
1389    AT_body_begin		= (0x8040|FORM_ADDR),
1390    AT_body_end			= (0x8050|FORM_ADDR)
1391};
1392
1393/* end of enums taken from gdb-6.0 sources */
1394
1395void ML_(read_debuginfo_dwarf1) (
1396        struct _DebugInfo* di,
1397        UChar* dwarf1d, Int dwarf1d_sz,
1398        UChar* dwarf1l, Int dwarf1l_sz )
1399{
1400   UInt   stmt_list;
1401   Bool   stmt_list_found;
1402   Int    die_offset, die_szb, at_offset;
1403   UShort die_kind, at_kind;
1404   UChar* at_base;
1405   HChar* src_filename;
1406
1407   if (0)
1408      VG_(printf)("read_debuginfo_dwarf1 ( %p, %d, %p, %d )\n",
1409	          dwarf1d, dwarf1d_sz, dwarf1l, dwarf1l_sz );
1410
1411   /* This loop scans the DIEs. */
1412   die_offset = 0;
1413   while (True) {
1414      if (die_offset >= dwarf1d_sz) break;
1415
1416      die_szb  = ML_(read_Int)(dwarf1d + die_offset);
1417      die_kind = ML_(read_UShort)(dwarf1d + die_offset + 4);
1418
1419      /* We're only interested in compile_unit DIEs; ignore others. */
1420      if (die_kind != TAG_compile_unit) {
1421         die_offset += die_szb;
1422         continue;
1423      }
1424
1425      if (0)
1426         VG_(printf)("compile-unit DIE: offset %d, tag 0x%x, size %d\n",
1427                     die_offset, (Int)die_kind, die_szb );
1428
1429      /* We've got a compile_unit DIE starting at (dwarf1d +
1430         die_offset+6).  Try and find the AT_name and AT_stmt_list
1431         attributes.  Then, finally, we can read the line number info
1432         for this source file. */
1433
1434      /* The next 3 are set as we find the relevant attrs. */
1435      src_filename    = NULL;
1436      stmt_list_found = False;
1437      stmt_list       = 0;
1438
1439      /* This loop scans the Attrs inside compile_unit DIEs. */
1440      at_base = dwarf1d + die_offset + 6;
1441      at_offset = 0;
1442      while (True) {
1443         if (at_offset >= die_szb-6) break;
1444
1445         at_kind = ML_(read_UShort)(at_base + at_offset);
1446         if (0) VG_(printf)("atoffset %d, attag 0x%x\n",
1447                            at_offset, (Int)at_kind );
1448         at_offset += 2; /* step over the attribute itself */
1449	 /* We have to examine the attribute to figure out its
1450            length. */
1451         switch (at_kind) {
1452            case AT_stmt_list:
1453            case AT_language:
1454            case AT_sibling:
1455               if (at_kind == AT_stmt_list) {
1456                  stmt_list_found = True;
1457                  stmt_list = ML_(read_Int)(at_base+at_offset);
1458               }
1459               at_offset += 4; break;
1460            case AT_high_pc:
1461            case AT_low_pc:
1462               at_offset += sizeof(void*); break;
1463            case AT_name:
1464            case AT_producer:
1465            case AT_comp_dir:
1466               /* Zero terminated string, step over it. */
1467               if (at_kind == AT_name)
1468                 src_filename = (HChar *)(at_base + at_offset);
1469               while (at_offset < die_szb-6 && at_base[at_offset] != 0)
1470                  at_offset++;
1471               at_offset++;
1472               break;
1473            default:
1474               VG_(printf)("Unhandled DWARF-1 attribute 0x%x\n",
1475                           (Int)at_kind );
1476               VG_(core_panic)("Unhandled DWARF-1 attribute");
1477         } /* switch (at_kind) */
1478      } /* looping over attributes */
1479
1480      /* So, did we find the required stuff for a line number table in
1481         this DIE?  If yes, read it. */
1482      if (stmt_list_found /* there is a line number table */
1483          && src_filename != NULL /* we know the source filename */
1484         ) {
1485         /* Table starts:
1486               Length:
1487                  4 bytes, includes the entire table
1488               Base address:
1489                  unclear (4? 8?), assuming native pointer size here.
1490            Then a sequence of triples
1491               (source line number -- 32 bits
1492                source line column -- 16 bits
1493                address delta -- 32 bits)
1494	 */
1495         Addr   base;
1496	 Int    len;
1497         HChar* curr_filenm;
1498         UChar* ptr;
1499         UInt   prev_line, prev_delta;
1500
1501         curr_filenm = ML_(addStr) ( di, src_filename, -1 );
1502         prev_line = prev_delta = 0;
1503
1504         ptr = dwarf1l + stmt_list;
1505         len  = ML_(read_Int)(ptr);  ptr += sizeof(Int);
1506         base = ML_(read_Addr)(ptr); ptr += sizeof(void*);
1507         len -= (sizeof(Int) + sizeof(void*));
1508         while (len > 0) {
1509            UInt   line;
1510            UShort col;
1511            UInt   delta;
1512            line = ML_(read_UInt)(ptr);    ptr += sizeof(UInt);
1513            col  = ML_(read_UShort)(ptr);  ptr += sizeof(UShort);
1514            delta = ML_(read_UInt)(ptr);   ptr += sizeof(UInt);
1515	    if (0) VG_(printf)("line %d, col %d, delta %d\n",
1516                               line, (Int)col, delta );
1517            len -= (sizeof(UInt) + sizeof(UShort) + sizeof(UInt));
1518
1519	    if (delta > 0 && prev_line > 0) {
1520	       if (0) VG_(printf) ("     %d  %d-%d\n",
1521                                   prev_line, prev_delta, delta-1);
1522	       ML_(addLineInfo) ( di, curr_filenm, NULL,
1523		 	          base + prev_delta, base + delta,
1524			          prev_line, 0 );
1525	    }
1526	    prev_line = line;
1527	    prev_delta = delta;
1528	 }
1529      }
1530
1531      /* Move on the the next DIE. */
1532      die_offset += die_szb;
1533
1534   } /* Looping over DIEs */
1535
1536}
1537
1538
1539/*------------------------------------------------------------*/
1540/*--- Read call-frame info from an .eh_frame section       ---*/
1541/*------------------------------------------------------------*/
1542
1543/* Sources of info:
1544
1545   The DWARF3 spec, available from http://www.dwarfstd.org/Download.php
1546
1547   This describes how to read CFA data from .debug_frame sections.
1548   So as to maximise everybody's annoyance and confusion, .eh_frame
1549   sections are almost the same as .debug_frame sections, but differ
1550   in a few subtle and ill documented but important aspects.
1551
1552   Generic ELF Specification, sections 7.5 (DWARF Extensions) and 7.6
1553   (Exception Frames), available from
1554
1555   http://www.linux-foundation.org/spec/book/ELF-generic/ELF-generic.html
1556
1557   This really does describe .eh_frame, at least the aspects that
1558   differ from standard DWARF3.  It's better than guessing, and
1559   (marginally) more fun than reading the gdb source code.
1560*/
1561
1562/* Useful info ..
1563
1564   In general:
1565   gdb-6.3/gdb/dwarf2-frame.c
1566
1567   gdb-6.3/gdb/i386-tdep.c:
1568
1569   DWARF2/GCC uses the stack address *before* the function call as a
1570   frame's CFA.  [jrs: I presume this means %esp before the call as
1571   the CFA].
1572
1573   JRS: on amd64, the dwarf register numbering is, as per
1574   gdb-6.3/gdb/amd64-tdep.c and also amd64-abi-0.98.pdf:
1575
1576      0    1    2    3    4    5    6    7
1577      RAX  RDX  RCX  RBX  RSI  RDI  RBP  RSP
1578
1579      8  ...  15
1580      R8 ... R15
1581
1582      16 is the return address (RIP)
1583      "The table defines Return Address to have a register number,
1584      even though the address is stored in 0(%rsp) and not in a
1585      physical register."
1586
1587      17   ...   24
1588      XMM0 ... XMM7
1589
1590      25   ...    32
1591      XMM8 ... XMM15
1592
1593      33   ...   40
1594      ST0  ...  ST7
1595
1596      41   ...   48
1597      MM0  ...  MM7
1598
1599      49                  RFLAGS
1600      50,51,52,53,54,55   ES,CS,SS,DS,FS,GS
1601      58                  FS.BASE  (what's that?)
1602      59                  GS.BASE  (what's that?)
1603      62                  TR (task register)
1604      63                  LDTR (LDT register)
1605      64                  MXCSR
1606      65                  FCW (x87 control word)
1607      66                  FSW (x86 status word)
1608
1609   On x86 I cannot find any documentation.  It _appears_ to be the
1610   actual instruction encoding, viz:
1611
1612      0    1    2    3    4    5    6    7
1613      EAX  ECX  EDX  EBX  ESP  EBP  ESI  EDI
1614
1615      8 is the return address (EIP) */
1616
1617
1618/* Comments re DW_CFA_set_loc, 16 Nov 06.
1619
1620   JRS:
1621   Someone recently sent me a libcrypto.so.0.9.8 as distributed with
1622   Ubuntu of some flavour, compiled with gcc 4.1.2 on amd64.  It
1623   causes V's CF reader to complain a lot:
1624
1625   >> --19976-- DWARF2 CFI reader: unhandled CFI instruction 0:24
1626   >> --19976-- DWARF2 CFI reader: unhandled CFI instruction 0:24
1627   >> --19976-- DWARF2 CFI reader: unhandled CFI instruction 0:24
1628   >> --19976-- DWARF2 CFI reader: unhandled CFI instruction 0:24
1629   >> --19976-- DWARF2 CFI reader: unhandled CFI instruction 0:48
1630   >> --19976-- DWARF2 CFI reader: unhandled CFI instruction 0:24
1631
1632   After chasing this around a bit it seems that the CF bytecode
1633   parser lost sync at a DW_CFA_set_loc, which has a single argument
1634   denoting an address.
1635
1636   As it stands that address is extracted by read_Addr().  On amd64
1637   that just fetches 8 bytes regardless of anything else.
1638
1639   read_encoded_Addr() is more sophisticated.  This appears to take
1640   into account some kind of encoding flag.  When I replace the uses
1641   of read_Addr by read_encoded_Addr for DW_CFA_set_loc, the
1642   complaints go away, there is no loss of sync, and the parsed CF
1643   instructions are the same as shown by readelf --debug-dump=frames.
1644
1645   So it seems a plausible fix.  The problem is I looked in the DWARF3
1646   spec and completely failed to figure out whether or not the arg to
1647   DW_CFA_set_loc is supposed to be encoded in a way suitable for
1648   read_encoded_Addr, nor for that matter any description of what it
1649   is that read_encoded_Addr is really decoding.
1650
1651   TomH:
1652   The problem is that the encoding is not standard - the eh_frame
1653   section uses the same encoding as the dwarf_frame section except
1654   for a few small changes, and this is one of them. So this is not
1655   something the DWARF standard covers.
1656
1657   There is an augmentation string to indicate what is going on though
1658   so that programs can recognise it.
1659
1660   What we are doing seems to match what gdb 6.5 and libdwarf 20060614
1661   do though. I'm not sure about readelf though.
1662
1663   (later): Well dwarfdump barfs on it:
1664
1665      dwarfdump ERROR:  dwarf_get_fde_info_for_reg:
1666                        DW_DLE_DF_FRAME_DECODING_ERROR(193) (193)
1667
1668   I've looked at binutils as well now, and the code in readelf agrees
1669   with your patch - ie it treats set_loc as having an encoded address
1670   if there is a zR augmentation indicating an encoding.
1671
1672   Quite why gdb and libdwarf don't understand this is an interesting
1673   question...
1674
1675   Final outcome: all uses of read_Addr were replaced by
1676   read_encoded_Addr.  A new type AddressDecodingInfo was added to
1677   make it relatively clean to plumb through the extra info needed by
1678   read_encoded_Addr.
1679*/
1680
1681/* More badness re address encoding, 12 Jan 07.
1682
1683   Most gcc provided CIEs have a "zR" augmentation, which means they
1684   supply their own address encoding, and that works fine.  However,
1685   some icc9 supplied CIEs have no augmentation, which means they use
1686   the default_Addr_encoding().  That says to use a machine-word sized
1687   value, literally unmodified.
1688
1689   Since .so's are, in general, relocated when loaded, having absolute
1690   addresses in the CFI data makes no sense when read_encoded_Addr is
1691   used to find the initial location for a FDE.  The resulting saga:
1692
1693   TomH:
1694   > I'm chasing a stack backtrace failure for an amd64 .so which was
1695   > created I believe by icc 9.1.  After a while I wound up looking at
1696   > this: (readdwarf.c)
1697   >
1698   >   5083        tom static UChar default_Addr_encoding ( void )
1699   >   3584        tom {
1700   >   3584        tom    switch (sizeof(Addr)) {
1701   >   3584        tom       case 4: return DW_EH_PE_udata4;
1702   >   3584        tom       case 8: return DW_EH_PE_udata8;
1703   >   3584        tom       default: vg_assert(0);
1704   >   3584        tom    }
1705   >   3584        tom }
1706   >
1707   > If a CIE does not have an "augmentation string" (typically "zR") then
1708   > addresses are decoded as described by default_Addr_encoding.  If there
1709   > is an 'R' in the augmentation string then the encoding to use
1710   > is specified by the CIE itself, which works fine with GCC compiled code
1711   > since that always appears to specify zR.
1712
1713   Correct.
1714
1715   > Problem is this .so has no augmentation string and so uses the
1716   > default encoding, viz DW_EH_PE_udata8.  That appears to mean
1717   > "read a 64 bit number" and use that as-is (for the starting value
1718   > of the program counter when running the CFA program).
1719
1720   Strictly speaking the default is DW_EH_PE_absptr, but that amounts
1721   to either udata4 or udata8 depending on the platform's pointer size
1722   which is a shortcut I used.
1723
1724   > For this .so that gives nonsense (very small) PCs which are later
1725   > rejected by the sanity check which ensures PC ranges fall inside
1726   > the mapped text segment.  It seems like the .so expects to have the
1727   > start VMA of the text segment added on.  This would correspond to
1728   >
1729   >   static UChar default_Addr_encoding ( void )
1730   >   {
1731   >      switch (sizeof(Addr)) {
1732   >         case 4: return DW_EH_PE_textrel + DW_EH_PE_udata4;
1733   >         case 8: return DW_EH_PE_textrel + DW_EH_PE_udata8;
1734   >         default: vg_assert(0);
1735   >      }
1736   >   }
1737
1738   The problem you're seeing is that you have absolute pointers inside
1739   a shared library, which obviously makes little sense on the face of
1740   things as how would the linker know where the library will be
1741   loaded?
1742
1743   The answer of course is that it doesn't, so if it points absolute
1744   pointers in the frame unwind data is has to include relocations for
1745   them, and I'm betting that if you look at the relocations in the
1746   library you will there are some for that data.
1747
1748   That is fine of course when ld.so maps the library - it will
1749   relocate the eh_frame data as it maps it (or prelinking will
1750   already have done so) and when the g++ exception code kicks in and
1751   unwinds the stack it will see relocated data.
1752
1753   We of course are mapping the section from the ELF file ourselves
1754   and are not applying the relocations, hence the problem you are
1755   seeing.
1756
1757   Strictly speaking we should apply the relocations but the cheap
1758   solution is essentially to do what you've done - strictly speaking
1759   you should adjust by the difference between the address the library
1760   was linked for and the address it has been loaded at, but a shared
1761   library will normally be linked for address zero I believe. It's
1762   possible that prelinking might change that though?
1763
1764   JRS:
1765   That all syncs with what I am seeing.
1766
1767   So what I am inclined to do is:
1768
1769   - Leave default_Addr_encoding as it is
1770
1771   - Change read_encoded_Addr's handling of "case DW_EH_PE_absptr" so
1772     it sets base to, as you say, the difference between the address
1773     the library was linked for and the address it has been loaded at
1774     (== the SegInfo's text_bias)
1775
1776   Does that sound sane?  I think it should even handle the prelinked
1777   case.
1778
1779   (JRS, later)
1780
1781   Hmm.  Plausible as it sounds, it doesn't work.  It now produces
1782   bogus backtraces for locations inside the (statically linked)
1783   memcheck executable.
1784
1785   Besides, there are a couple of other places where read_encoded_Addr
1786   is used -- one of which is used to establish the length of the
1787   address range covered by the current FDE:
1788
1789         fde_arange = read_encoded_Addr(&nbytes, &adi, data);
1790
1791   and it doesn't seem to make any sense for read_encoded_Addr to add
1792   on the text segment bias in that context.  The DWARF3 spec says
1793   that both the initial_location and address_range (length) fields
1794   are encoded the same way ("target address"), so it is unclear at
1795   what stage in the process it would be appropriate to relocate the
1796   former but not the latter.
1797
1798   One unprincipled kludge that does work is the following: just
1799   before handing one of the address range fragments off to
1800   ML_(addDiCfSI) for permanent storage, check its start address.  If
1801   that is very low (less than 2 M), and is far below the mapped text
1802   segment, and adding the text bias would move the fragment entirely
1803   inside the mapped text segment, then do so.  A kind of kludged
1804   last-minute relocation, if you like.
1805
1806   12 Jan 07: committing said kludge (see kludge_then_addDiCfSI).  If
1807   the situation clarifies, it can easily enough be backed out and
1808   replaced by a better fix.
1809*/
1810
1811/* --------------- Decls --------------- */
1812
1813#if defined(VGP_x86_linux)
1814#  define FP_REG         5
1815#  define SP_REG         4
1816#  define RA_REG_DEFAULT 8
1817#elif defined(VGP_amd64_linux)
1818#  define FP_REG         6
1819#  define SP_REG         7
1820#  define RA_REG_DEFAULT 16
1821#elif defined(VGP_ppc32_linux)
1822#  define FP_REG         1
1823#  define SP_REG         1
1824#  define RA_REG_DEFAULT 65
1825#elif defined(VGP_ppc64_linux)
1826#  define FP_REG         1
1827#  define SP_REG         1
1828#  define RA_REG_DEFAULT 65
1829#elif defined(VGP_arm_linux)
1830#  define FP_REG         12
1831#  define SP_REG         13
1832#  define RA_REG_DEFAULT 14    //???
1833#elif defined(VGP_x86_darwin)
1834#  define FP_REG         5
1835#  define SP_REG         4
1836#  define RA_REG_DEFAULT 8
1837#elif defined(VGP_amd64_darwin)
1838#  define FP_REG         6
1839#  define SP_REG         7
1840#  define RA_REG_DEFAULT 16
1841#elif defined(VGP_s390x_linux)
1842#  define FP_REG         11    // sometimes s390 has a frame pointer in r11
1843#  define SP_REG         15    // stack is always r15
1844#  define RA_REG_DEFAULT 14    // the return address is in r14
1845#elif defined(VGP_mips32_linux)
1846#  define FP_REG         30
1847#  define SP_REG         29
1848#  define RA_REG_DEFAULT 31
1849#elif defined(VGP_mips64_linux)
1850#  define FP_REG         30
1851#  define SP_REG         29
1852#  define RA_REG_DEFAULT 31
1853#else
1854#  error "Unknown platform"
1855#endif
1856
1857/* The number of regs we are prepared to unwind.  The number for
1858   arm-linux (320) seems ludicrously high, but the ARM IHI 0040A page
1859   7 (DWARF for the ARM Architecture) specifies that values up to 320
1860   might exist, for Neon/VFP-v3. */
1861#if defined(VGP_ppc32_linux) || defined(VGP_ppc64_linux) \
1862    || defined(VGP_mips32_linux) || defined(VGP_mips64_linux)
1863# define N_CFI_REGS 72
1864#elif defined(VGP_arm_linux)
1865# define N_CFI_REGS 320
1866#else
1867# define N_CFI_REGS 20
1868#endif
1869
1870/* Instructions for the automaton */
1871enum dwarf_cfa_primary_ops
1872  {
1873    DW_CFA_use_secondary = 0,
1874    DW_CFA_advance_loc   = 1,
1875    DW_CFA_offset        = 2,
1876    DW_CFA_restore       = 3
1877  };
1878
1879enum dwarf_cfa_secondary_ops
1880  {
1881    DW_CFA_nop                = 0x00,
1882    DW_CFA_set_loc            = 0x01,
1883    DW_CFA_advance_loc1       = 0x02,
1884    DW_CFA_advance_loc2       = 0x03,
1885    DW_CFA_advance_loc4       = 0x04,
1886    DW_CFA_offset_extended    = 0x05,
1887    DW_CFA_restore_extended   = 0x06,
1888    DW_CFA_undefined          = 0x07,
1889    DW_CFA_same_value         = 0x08,
1890    DW_CFA_register           = 0x09,
1891    DW_CFA_remember_state     = 0x0a,
1892    DW_CFA_restore_state      = 0x0b,
1893    DW_CFA_def_cfa            = 0x0c,
1894    DW_CFA_def_cfa_register   = 0x0d,
1895    DW_CFA_def_cfa_offset     = 0x0e,
1896    DW_CFA_def_cfa_expression = 0x0f, /* DWARF3 only */
1897    DW_CFA_expression         = 0x10, /* DWARF3 only */
1898    DW_CFA_offset_extended_sf = 0x11, /* DWARF3 only */
1899    DW_CFA_def_cfa_sf         = 0x12, /* DWARF3 only */
1900    DW_CFA_def_cfa_offset_sf  = 0x13, /* DWARF3 only */
1901    DW_CFA_val_offset         = 0x14, /* DWARF3 only */
1902    DW_CFA_val_offset_sf      = 0x15, /* DWARF3 only */
1903    DW_CFA_val_expression     = 0x16, /* DWARF3 only */
1904    DW_CFA_lo_user            = 0x1c,
1905    DW_CFA_GNU_window_save    = 0x2d, /* GNU extension */
1906    DW_CFA_GNU_args_size      = 0x2e, /* GNU extension */
1907    DW_CFA_GNU_negative_offset_extended = 0x2f, /* GNU extension */
1908    DW_CFA_hi_user            = 0x3f
1909  };
1910
1911#define DW_EH_PE_absptr		0x00
1912#define DW_EH_PE_omit		0xff
1913
1914#define DW_EH_PE_uleb128	0x01
1915#define DW_EH_PE_udata2		0x02
1916#define DW_EH_PE_udata4		0x03
1917#define DW_EH_PE_udata8		0x04
1918#define DW_EH_PE_sleb128	0x09
1919#define DW_EH_PE_sdata2		0x0A
1920#define DW_EH_PE_sdata4		0x0B
1921#define DW_EH_PE_sdata8		0x0C
1922#define DW_EH_PE_signed		0x08
1923
1924#define DW_EH_PE_pcrel		0x10
1925#define DW_EH_PE_textrel	0x20
1926#define DW_EH_PE_datarel	0x30
1927#define DW_EH_PE_funcrel	0x40
1928#define DW_EH_PE_aligned	0x50
1929
1930#define DW_EH_PE_indirect	0x80
1931
1932
1933/* RegRule and UnwindContext are used temporarily to do the unwinding.
1934   The result is then summarised into a sequence of CfiSIs, if
1935   possible.  UnwindContext effectively holds the state of the
1936   abstract machine whilst it is running.
1937
1938   The CFA can either be a signed offset from a register,
1939   or an expression:
1940
1941   CFA = cfa_reg + cfa_off   when UnwindContext.cfa_is_regoff==True
1942       | [[ cfa_expr_id ]]
1943
1944   When .cfa_is_regoff == True,  cfa_expr_id must be zero
1945   When .cfa_is_regoff == False, cfa_reg must be zero
1946                                 and cfa_off must be zero
1947
1948   RegRule describes, for each register, how to get its
1949   value in the previous frame, where 'cfa' denotes the cfa
1950   for the frame as a whole:
1951
1952   RegRule = RR_Undef          -- undefined
1953           | RR_Same           -- same as in previous frame
1954           | RR_CFAOff    arg  -- is at * ( cfa + arg )
1955           | RR_CFAValOff arg  -- is ( cfa + arg )
1956           | RR_Reg       arg  -- is in register 'arg'
1957           | RR_Expr      arg  -- is at * [[ arg ]]
1958           | RR_ValExpr   arg  -- is [[ arg ]]
1959           | RR_Arch           -- dunno
1960
1961   Note that RR_Expr is redundant since the same can be represented
1962   using RR_ValExpr with an explicit dereference (CfiExpr_Deref) at
1963   the outermost level.
1964
1965   All expressions are stored in exprs in the containing
1966   UnwindContext.  Since the UnwindContext gets reinitialised for each
1967   new FDE, summarise_context needs to copy out any expressions it
1968   wants to keep into the cfsi_exprs field of the containing SegInfo.
1969*/
1970typedef
1971   struct {
1972      enum { RR_Undef, RR_Same, RR_CFAOff, RR_CFAValOff,
1973             RR_Reg, /*RR_Expr,*/ RR_ValExpr, RR_Arch } tag;
1974      /* meaning:  int offset for CFAoff/CFAValOff
1975                   reg # for Reg
1976                   expr index for Expr/ValExpr */
1977      Int arg;
1978   }
1979   RegRule;
1980
1981static void ppRegRule ( XArray* exprs, RegRule* rrule )
1982{
1983   vg_assert(exprs);
1984   switch (rrule->tag) {
1985      case RR_Undef:     VG_(printf)("u  "); break;
1986      case RR_Same:      VG_(printf)("s  "); break;
1987      case RR_CFAOff:    VG_(printf)("c%d ", rrule->arg); break;
1988      case RR_CFAValOff: VG_(printf)("v%d ", rrule->arg); break;
1989      case RR_Reg:       VG_(printf)("r%d ", rrule->arg); break;
1990      case RR_ValExpr:   VG_(printf)("ve{");
1991                         ML_(ppCfiExpr)( exprs, rrule->arg );
1992                         VG_(printf)("} ");
1993                         break;
1994      case RR_Arch:      VG_(printf)("a  "); break;
1995      default:           VG_(core_panic)("ppRegRule");
1996   }
1997}
1998
1999
2000/* Size of the stack of register unwind rules.  This is only
2001   exceedingly rarely used, so a stack of size 1 should actually work
2002   with almost all compiler-generated CFA. */
2003#define N_RR_STACK 4
2004
2005typedef
2006   struct {
2007      /* Read-only fields (set by the CIE) */
2008      Int     code_a_f;
2009      Int     data_a_f;
2010      Addr    initloc;
2011      Int     ra_reg;
2012      /* The rest of these fields can be modifed by
2013         run_CF_instruction. */
2014      /* The LOC entry */
2015      Addr    loc;
2016      /* We need a stack of these in order to handle
2017         DW_CFA_{remember,restore}_state. */
2018      struct UnwindContextState {
2019          /* The CFA entry.  This can be either reg+/-offset or an expr. */
2020          Bool    cfa_is_regoff; /* True=>is reg+offset; False=>is expr */
2021          Int     cfa_reg;
2022          Int     cfa_off;  /* in bytes */
2023          Int     cfa_expr_ix; /* index into cfa_exprs */
2024          /* Register unwind rules.  */
2025          RegRule reg[N_CFI_REGS];
2026      }
2027      state[N_RR_STACK];
2028      Int     state_sp; /* 0 <= state_sp < N_RR_STACK; points at the
2029                           currently-in-use rule set. */
2030      /* array of CfiExpr, shared by reg[] and cfa_expr_ix */
2031      XArray* exprs;
2032   }
2033   UnwindContext;
2034
2035static void ppUnwindContext ( UnwindContext* ctx )
2036{
2037   Int j, i;
2038   VG_(printf)("0x%llx: ", (ULong)ctx->loc);
2039   for (j = 0; j <= ctx->state_sp; j++) {
2040      struct UnwindContextState* ctxs = &ctx->state[j];
2041      VG_(printf)("%s[%d]={ ", j > 0 ? " " : "", j);
2042      if (ctxs->cfa_is_regoff) {
2043         VG_(printf)("%d(r%d) ", ctxs->cfa_off, ctxs->cfa_reg);
2044      } else {
2045         vg_assert(ctx->exprs);
2046         VG_(printf)("{");
2047         ML_(ppCfiExpr)( ctx->exprs, ctxs->cfa_expr_ix );
2048         VG_(printf)("} ");
2049      }
2050      VG_(printf)("{ ");
2051      for (i = 0; i < N_CFI_REGS; i++)
2052         ppRegRule(ctx->exprs, &ctxs->reg[i]);
2053      VG_(printf)("}");
2054   }
2055   VG_(printf)("\n");
2056}
2057
2058static void initUnwindContext ( /*OUT*/UnwindContext* ctx )
2059{
2060   Int j, i;
2061   VG_(memset)(ctx, 0, sizeof(*ctx));
2062   /* ctx->code_a_f   = 0;
2063   ctx->data_a_f      = 0;
2064   ctx->initloc       = 0; */
2065   ctx->ra_reg        = RA_REG_DEFAULT;
2066   /* ctx->loc        = 0;
2067   ctx->exprs         = NULL;
2068   ctx->state_sp        = 0; */
2069   for (j = 0; j < N_RR_STACK; j++) {
2070      ctx->state[j].cfa_is_regoff = True;
2071      /* ctx->state[j].cfa_reg    = 0;
2072      ctx->state[j].cfa_off       = 0;
2073      ctx->state[j].cfa_expr_ix   = 0; */
2074      for (i = 0; i < N_CFI_REGS; i++) {
2075         if (RR_Undef != 0)
2076           ctx->state[j].reg[i].tag = RR_Undef;
2077         /* ctx->state[j].reg[i].arg = 0; */
2078      }
2079#     if defined(VGA_arm)
2080      /* All callee-saved registers (or at least the ones we are
2081         summarising for) should start out as RR_Same, on ARM. */
2082      ctx->state[j].reg[11].tag = RR_Same;
2083      /* ctx->state[j].reg[13].tag = RR_Same; */
2084      ctx->state[j].reg[14].tag = RR_Same;
2085      ctx->state[j].reg[12].tag = RR_Same;
2086      ctx->state[j].reg[7].tag  = RR_Same;
2087      /* this can't be right though: R12 (IP) isn't callee saved. */
2088#     endif
2089   }
2090}
2091
2092
2093/* A structure which holds information needed by read_encoded_Addr().
2094*/
2095typedef
2096   struct {
2097      UChar  encoding;
2098      UChar* ehframe_image;
2099      Addr   ehframe_avma;
2100      Addr   text_bias;
2101   }
2102   AddressDecodingInfo;
2103
2104
2105/* ------------ Deal with summary-info records ------------ */
2106
2107static void initCfiSI ( DiCfSI* si )
2108{
2109   VG_(memset)(si, 0, sizeof(*si));
2110}
2111
2112
2113/* --------------- Summarisation --------------- */
2114
2115/* Forward */
2116static
2117Int copy_convert_CfiExpr_tree ( XArray*        dst,
2118                                UnwindContext* srcuc,
2119                                Int            nd );
2120
2121/* Summarise ctx into si, if possible.  Returns True if successful.
2122   This is taken to be just after ctx's loc advances; hence the
2123   summary is up to but not including the current loc.  This works
2124   on both x86 and amd64.
2125*/
2126static Bool summarise_context( /*OUT*/DiCfSI* si,
2127                               Addr loc_start,
2128	                       UnwindContext* ctx,
2129                               struct _DebugInfo* debuginfo )
2130{
2131   Int why = 0;
2132   struct UnwindContextState* ctxs;
2133   initCfiSI(si);
2134
2135   /* Guard against obviously stupid settings of the reg-rule stack
2136      pointer. */
2137   if (ctx->state_sp < 0)           { why = 8; goto failed; }
2138   if (ctx->state_sp >= N_RR_STACK) { why = 9; goto failed; }
2139   ctxs = &ctx->state[ctx->state_sp];
2140
2141   /* First, summarise the method for generating the CFA */
2142   if (!ctxs->cfa_is_regoff) {
2143      /* it was set by DW_CFA_def_cfa_expression; try to convert */
2144      XArray *src, *dst;
2145      Int    conv;
2146      src = ctx->exprs;
2147      dst = debuginfo->cfsi_exprs;
2148      if (src && (VG_(sizeXA)(src) > 0) && (!dst)) {
2149         dst = VG_(newXA)( ML_(dinfo_zalloc), "di.ccCt.1", ML_(dinfo_free),
2150                           sizeof(CfiExpr) );
2151         vg_assert(dst);
2152         debuginfo->cfsi_exprs = dst;
2153      }
2154      conv = copy_convert_CfiExpr_tree
2155                    ( dst, ctx, ctxs->cfa_expr_ix );
2156      vg_assert(conv >= -1);
2157      if (conv == -1) { why = 6; goto failed; }
2158      si->cfa_how = CFIC_EXPR;
2159      si->cfa_off = conv;
2160      if (0 && debuginfo->ddump_frames)
2161         ML_(ppCfiExpr)(dst, conv);
2162   }
2163   else
2164   if (ctxs->cfa_is_regoff && ctxs->cfa_reg == SP_REG) {
2165      si->cfa_off = ctxs->cfa_off;
2166#     if defined(VGA_x86) || defined(VGA_amd64) || defined(VGA_s390x) \
2167         || defined(VGA_mips32) || defined(VGA_mips64)
2168      si->cfa_how = CFIC_IA_SPREL;
2169#     elif defined(VGA_arm)
2170      si->cfa_how = CFIC_ARM_R13REL;
2171#     else
2172      si->cfa_how = 0; /* invalid */
2173#     endif
2174   }
2175   else
2176   if (ctxs->cfa_is_regoff && ctxs->cfa_reg == FP_REG) {
2177      si->cfa_off = ctxs->cfa_off;
2178#     if defined(VGA_x86) || defined(VGA_amd64) || defined(VGA_s390x) \
2179         || defined(VGA_mips32) || defined(VGA_mips64)
2180      si->cfa_how = CFIC_IA_BPREL;
2181#     elif defined(VGA_arm)
2182      si->cfa_how = CFIC_ARM_R12REL;
2183#     else
2184      si->cfa_how = 0; /* invalid */
2185#     endif
2186   }
2187#  if defined(VGA_arm)
2188   else
2189   if (ctxs->cfa_is_regoff && ctxs->cfa_reg == 11/*??_REG*/) {
2190      si->cfa_how = CFIC_ARM_R11REL;
2191      si->cfa_off = ctxs->cfa_off;
2192   }
2193   else
2194   if (ctxs->cfa_is_regoff && ctxs->cfa_reg == 7/*??_REG*/) {
2195      si->cfa_how = CFIC_ARM_R7REL;
2196      si->cfa_off = ctxs->cfa_off;
2197   }
2198#  endif
2199   else {
2200      why = 1;
2201      goto failed;
2202   }
2203
2204#  define SUMMARISE_HOW(_how, _off, _ctxreg)                  \
2205   switch (_ctxreg.tag) {                                     \
2206      case RR_Undef:                                          \
2207         _how = CFIR_UNKNOWN;   _off = 0; break;              \
2208      case RR_Same:                                           \
2209         _how = CFIR_SAME;      _off = 0; break;              \
2210      case RR_CFAOff:                                         \
2211         _how = CFIR_MEMCFAREL; _off = _ctxreg.arg; break;    \
2212      case RR_CFAValOff:                                      \
2213         _how = CFIR_CFAREL;    _off = _ctxreg.arg; break;    \
2214      case RR_ValExpr: {                                      \
2215         XArray *src, *dst;                                   \
2216         Int    conv;                                         \
2217         src = ctx->exprs;                                    \
2218         dst = debuginfo->cfsi_exprs;                         \
2219         if (src && (VG_(sizeXA)(src) > 0) && (!dst)) {       \
2220            dst = VG_(newXA)( ML_(dinfo_zalloc),              \
2221                              "di.ccCt.2",                    \
2222                              ML_(dinfo_free),                \
2223                              sizeof(CfiExpr) );              \
2224            vg_assert(dst);                                   \
2225            debuginfo->cfsi_exprs = dst;                      \
2226         }                                                    \
2227         conv = copy_convert_CfiExpr_tree                     \
2228                       ( dst, ctx, _ctxreg.arg );             \
2229         vg_assert(conv >= -1);                               \
2230         if (conv == -1) { why = 7; goto failed; }            \
2231         _how = CFIR_EXPR;                                    \
2232         _off = conv;                                         \
2233         if (0 && debuginfo->ddump_frames)                    \
2234            ML_(ppCfiExpr)(dst, conv);                        \
2235         break;                                               \
2236      }                                                       \
2237      default:                                                \
2238         why = 2; goto failed; /* otherwise give up */        \
2239   }
2240
2241#  if defined(VGA_x86) || defined(VGA_amd64)
2242
2243   /* --- entire tail of this fn specialised for x86/amd64 --- */
2244
2245   SUMMARISE_HOW(si->ra_how, si->ra_off,
2246                             ctxs->reg[ctx->ra_reg] );
2247   SUMMARISE_HOW(si->bp_how, si->bp_off,
2248                             ctxs->reg[FP_REG] );
2249
2250   /* on x86/amd64, it seems the old %{e,r}sp value before the call is
2251      always the same as the CFA.  Therefore ... */
2252   si->sp_how = CFIR_CFAREL;
2253   si->sp_off = 0;
2254
2255   /* also, gcc says "Undef" for %{e,r}bp when it is unchanged.  So
2256      .. */
2257   if (ctxs->reg[FP_REG].tag == RR_Undef)
2258      si->bp_how = CFIR_SAME;
2259
2260   /* knock out some obviously stupid cases */
2261   if (si->ra_how == CFIR_SAME)
2262      { why = 3; goto failed; }
2263
2264   /* bogus looking range?  Note, we require that the difference is
2265      representable in 32 bits. */
2266   if (loc_start >= ctx->loc)
2267      { why = 4; goto failed; }
2268   if (ctx->loc - loc_start > 10000000 /* let's say */)
2269      { why = 5; goto failed; }
2270
2271   si->base = loc_start + ctx->initloc;
2272   si->len  = (UInt)(ctx->loc - loc_start);
2273
2274   return True;
2275
2276#  elif defined(VGA_arm)
2277
2278   /* ---- entire tail of this fn specialised for arm ---- */
2279
2280   SUMMARISE_HOW(si->r14_how, si->r14_off,
2281                              ctxs->reg[14] );
2282
2283   //SUMMARISE_HOW(si->r13_how, si->r13_off,
2284   //                           ctxs->reg[13] );
2285
2286   SUMMARISE_HOW(si->r12_how, si->r12_off,
2287                              ctxs->reg[FP_REG] );
2288
2289   SUMMARISE_HOW(si->r11_how, si->r11_off,
2290                              ctxs->reg[11/*FP_REG*/] );
2291
2292   SUMMARISE_HOW(si->r7_how, si->r7_off,
2293                             ctxs->reg[7] );
2294
2295   if (ctxs->reg[14/*LR*/].tag == RR_Same
2296       && ctx->ra_reg == 14/*as we expect it always to be*/) {
2297      /* Generate a trivial CfiExpr, which merely says "r14".  First
2298         ensure this DebugInfo has a cfsi_expr array in which to park
2299         it. */
2300      if (!debuginfo->cfsi_exprs)
2301         debuginfo->cfsi_exprs = VG_(newXA)( ML_(dinfo_zalloc),
2302                                             "di.ccCt.2a",
2303                                             ML_(dinfo_free),
2304                                             sizeof(CfiExpr) );
2305      si->ra_off = ML_(CfiExpr_CfiReg)( debuginfo->cfsi_exprs,
2306                                        Creg_ARM_R14);
2307      si->ra_how = CFIR_EXPR;
2308   } else {
2309      /* Just summarise it in the normal way */
2310      SUMMARISE_HOW(si->ra_how, si->ra_off,
2311                                ctxs->reg[ctx->ra_reg] );
2312   }
2313
2314   /* on arm, it seems the old r13 (SP) value before the call is
2315      always the same as the CFA.  Therefore ... */
2316   si->r13_how = CFIR_CFAREL;
2317   si->r13_off = 0;
2318
2319   /* bogus looking range?  Note, we require that the difference is
2320      representable in 32 bits. */
2321   if (loc_start >= ctx->loc)
2322      { why = 4; goto failed; }
2323   if (ctx->loc - loc_start > 10000000 /* let's say */)
2324      { why = 5; goto failed; }
2325
2326   si->base = loc_start + ctx->initloc;
2327   si->len  = (UInt)(ctx->loc - loc_start);
2328
2329   return True;
2330
2331
2332#  elif defined(VGA_s390x)
2333
2334   SUMMARISE_HOW(si->ra_how, si->ra_off,
2335                             ctxs->reg[ctx->ra_reg] );
2336   SUMMARISE_HOW(si->fp_how, si->fp_off,
2337                             ctxs->reg[FP_REG] );
2338   SUMMARISE_HOW(si->sp_how, si->sp_off,
2339                             ctxs->reg[SP_REG] );
2340
2341   /* change some defaults to consumable values */
2342   if (si->sp_how == CFIR_UNKNOWN)
2343      si->sp_how = CFIR_SAME;
2344
2345   if (si->fp_how == CFIR_UNKNOWN)
2346      si->fp_how = CFIR_SAME;
2347
2348   if (si->cfa_how == CFIR_UNKNOWN) {
2349      si->cfa_how = CFIC_IA_SPREL;
2350      si->cfa_off = 160;
2351   }
2352   if (si->ra_how == CFIR_UNKNOWN) {
2353      if (!debuginfo->cfsi_exprs)
2354         debuginfo->cfsi_exprs = VG_(newXA)( ML_(dinfo_zalloc),
2355                                             "di.ccCt.2a",
2356                                             ML_(dinfo_free),
2357                                             sizeof(CfiExpr) );
2358      si->ra_how = CFIR_EXPR;
2359      si->ra_off = ML_(CfiExpr_CfiReg)( debuginfo->cfsi_exprs,
2360                                        Creg_S390_R14);
2361   }
2362
2363   /* knock out some obviously stupid cases */
2364   if (si->ra_how == CFIR_SAME)
2365      { why = 3; goto failed; }
2366
2367   /* bogus looking range?  Note, we require that the difference is
2368      representable in 32 bits. */
2369   if (loc_start >= ctx->loc)
2370      { why = 4; goto failed; }
2371   if (ctx->loc - loc_start > 10000000 /* let's say */)
2372      { why = 5; goto failed; }
2373
2374   si->base = loc_start + ctx->initloc;
2375   si->len  = (UInt)(ctx->loc - loc_start);
2376
2377   return True;
2378
2379
2380#  elif defined(VGA_mips32) || defined(VGA_mips64)
2381
2382   /* --- entire tail of this fn specialised for mips --- */
2383
2384   SUMMARISE_HOW(si->ra_how, si->ra_off,
2385                             ctxs->reg[ctx->ra_reg] );
2386   SUMMARISE_HOW(si->fp_how, si->fp_off,
2387                             ctxs->reg[FP_REG] );
2388   SUMMARISE_HOW(si->sp_how, si->sp_off,
2389                             ctxs->reg[SP_REG] );
2390      si->sp_how = CFIR_CFAREL;
2391   si->sp_off = 0;
2392
2393   if (si->fp_how == CFIR_UNKNOWN)
2394       si->fp_how = CFIR_SAME;
2395   if (si->cfa_how == CFIR_UNKNOWN) {
2396      si->cfa_how = CFIC_IA_SPREL;
2397      si->cfa_off = 160;
2398   }
2399   if (si->ra_how == CFIR_UNKNOWN) {
2400      if (!debuginfo->cfsi_exprs)
2401         debuginfo->cfsi_exprs = VG_(newXA)( ML_(dinfo_zalloc),
2402                                             "di.ccCt.2a",
2403                                             ML_(dinfo_free),
2404                                             sizeof(CfiExpr) );
2405      si->ra_how = CFIR_EXPR;
2406      si->ra_off = ML_(CfiExpr_CfiReg)( debuginfo->cfsi_exprs,
2407                                        Creg_MIPS_RA);
2408   }
2409
2410   if (si->ra_how == CFIR_SAME)
2411      { why = 3; goto failed; }
2412
2413   if (loc_start >= ctx->loc)
2414      { why = 4; goto failed; }
2415   if (ctx->loc - loc_start > 10000000 /* let's say */)
2416      { why = 5; goto failed; }
2417
2418   si->base = loc_start + ctx->initloc;
2419   si->len  = (UInt)(ctx->loc - loc_start);
2420
2421   return True;
2422
2423
2424
2425#  elif defined(VGA_ppc32) || defined(VGA_ppc64)
2426#  else
2427#    error "Unknown arch"
2428#  endif
2429
2430#  undef SUMMARISE_HOW
2431
2432  failed:
2433   if (VG_(clo_verbosity) > 2 || debuginfo->trace_cfi) {
2434      VG_(message)(Vg_DebugMsg,
2435                  "summarise_context(loc_start = %#lx)"
2436                  ": cannot summarise(why=%d):   \n", loc_start, why);
2437      ppUnwindContext(ctx);
2438   }
2439   return False;
2440}
2441
2442/* Copy the tree rooted at srcuc->exprs node srcix to dstxa, on the
2443   way converting any DwReg regs (regs numbered using the Dwarf scheme
2444   defined by each architecture's ABI) into CfiRegs, which are
2445   platform independent.  If the conversion isn't possible because
2446   there is no equivalent register, return -1.  This has the
2447   undesirable side effect of de-dagifying the input; oh well. */
2448static Int copy_convert_CfiExpr_tree ( XArray*        dstxa,
2449                                       UnwindContext* srcuc,
2450                                       Int            srcix )
2451{
2452   CfiExpr* src;
2453   Int      cpL, cpR, cpA;
2454   XArray*  srcxa = srcuc->exprs;
2455   vg_assert(srcxa);
2456   vg_assert(dstxa);
2457   vg_assert(srcix >= 0 && srcix < VG_(sizeXA)(srcxa));
2458
2459   src = VG_(indexXA)( srcxa, srcix );
2460   switch (src->tag) {
2461      case Cex_Undef:
2462         return ML_(CfiExpr_Undef)( dstxa );
2463      case Cex_Deref:
2464         cpA = copy_convert_CfiExpr_tree( dstxa, srcuc, src->Cex.Deref.ixAddr );
2465         if (cpA == -1)
2466            return -1; /* propagate failure */
2467         return ML_(CfiExpr_Deref)( dstxa, cpA );
2468      case Cex_Const:
2469         return ML_(CfiExpr_Const)( dstxa, src->Cex.Const.con );
2470      case Cex_Binop:
2471         cpL = copy_convert_CfiExpr_tree( dstxa, srcuc, src->Cex.Binop.ixL );
2472         cpR = copy_convert_CfiExpr_tree( dstxa, srcuc, src->Cex.Binop.ixR );
2473         vg_assert(cpL >= -1 && cpR >= -1);
2474         if (cpL == -1 || cpR == -1)
2475            return -1; /* propagate failure */
2476         return ML_(CfiExpr_Binop)( dstxa, src->Cex.Binop.op, cpL, cpR );
2477      case Cex_CfiReg:
2478         /* should not see these in input (are created only by this
2479            conversion step!) */
2480         VG_(core_panic)("copy_convert_CfiExpr_tree: CfiReg in input");
2481      case Cex_DwReg: {
2482         /* This is the only place where the conversion can fail. */
2483         Int dwreg __attribute__((unused));
2484         dwreg = src->Cex.DwReg.reg;
2485#        if defined(VGA_x86) || defined(VGA_amd64)
2486         if (dwreg == SP_REG)
2487            return ML_(CfiExpr_CfiReg)( dstxa, Creg_IA_SP );
2488         if (dwreg == FP_REG)
2489            return ML_(CfiExpr_CfiReg)( dstxa, Creg_IA_BP );
2490         if (dwreg == srcuc->ra_reg)
2491            return ML_(CfiExpr_CfiReg)( dstxa, Creg_IA_IP ); /* correct? */
2492#        elif defined(VGA_arm)
2493         if (dwreg == SP_REG)
2494            return ML_(CfiExpr_CfiReg)( dstxa, Creg_ARM_R13 );
2495         if (dwreg == FP_REG)
2496            return ML_(CfiExpr_CfiReg)( dstxa, Creg_ARM_R12 );
2497         if (dwreg == srcuc->ra_reg)
2498           return ML_(CfiExpr_CfiReg)( dstxa, Creg_ARM_R15 ); /* correct? */
2499#        elif defined(VGA_s390x)
2500         if (dwreg == SP_REG)
2501            return ML_(CfiExpr_CfiReg)( dstxa, Creg_IA_SP );
2502         if (dwreg == FP_REG)
2503            return ML_(CfiExpr_CfiReg)( dstxa, Creg_IA_BP );
2504         if (dwreg == srcuc->ra_reg)
2505            return ML_(CfiExpr_CfiReg)( dstxa, Creg_IA_IP ); /* correct? */
2506#        elif defined(VGA_mips32) || defined(VGA_mips64)
2507         if (dwreg == SP_REG)
2508            return ML_(CfiExpr_CfiReg)( dstxa, Creg_IA_SP );
2509         if (dwreg == FP_REG)
2510            return ML_(CfiExpr_CfiReg)( dstxa, Creg_IA_BP );
2511         if (dwreg == srcuc->ra_reg)
2512            return ML_(CfiExpr_CfiReg)( dstxa, Creg_IA_IP );
2513#        elif defined(VGA_ppc32) || defined(VGA_ppc64)
2514#        else
2515#           error "Unknown arch"
2516#        endif
2517         /* else we must fail - can't represent the reg */
2518         return -1;
2519      }
2520      default:
2521         VG_(core_panic)("copy_convert_CfiExpr_tree: default");
2522   }
2523}
2524
2525
2526static void ppUnwindContext_summary ( UnwindContext* ctx )
2527{
2528   struct UnwindContextState* ctxs = &ctx->state[ctx->state_sp];
2529
2530   VG_(printf)("0x%llx-1: ", (ULong)ctx->loc);
2531
2532   if (ctxs->cfa_reg == SP_REG) {
2533      VG_(printf)("SP/CFA=%d+SP   ", ctxs->cfa_off);
2534   } else
2535   if (ctxs->cfa_reg == FP_REG) {
2536      VG_(printf)("SP/CFA=%d+FP   ", ctxs->cfa_off);
2537   } else {
2538      VG_(printf)("SP/CFA=unknown  ");
2539   }
2540
2541   VG_(printf)("RA=");
2542   ppRegRule( ctx->exprs, &ctxs->reg[ctx->ra_reg] );
2543
2544   VG_(printf)("FP=");
2545   ppRegRule( ctx->exprs, &ctxs->reg[FP_REG] );
2546   VG_(printf)("\n");
2547}
2548
2549
2550/* ------------ Pick apart DWARF2 byte streams ------------ */
2551
2552static ULong read_le_u_encoded_literal ( UChar* data, UInt size )
2553{
2554   switch (size) {
2555      case 8:  return (ULong)ML_(read_ULong)( data );
2556      case 4:  return (ULong)ML_(read_UInt)( data );
2557      case 2:  return (ULong)ML_(read_UShort)( data );
2558      case 1:  return (ULong)ML_(read_UChar)( data );
2559      default: vg_assert(0); /*NOTREACHED*/ return 0;
2560   }
2561}
2562
2563static Long read_le_s_encoded_literal ( UChar* data, UInt size )
2564{
2565   Long s64 = read_le_u_encoded_literal( data, size );
2566   switch (size) {
2567      case 8:  break;
2568      case 4:  s64 <<= 32; s64 >>= 32; break;
2569      case 2:  s64 <<= 48; s64 >>= 48; break;
2570      case 1:  s64 <<= 56; s64 >>= 56; break;
2571      default: vg_assert(0); /*NOTREACHED*/ return 0;
2572   }
2573   return s64;
2574}
2575
2576static UChar default_Addr_encoding ( void )
2577{
2578   switch (sizeof(Addr)) {
2579      case 4: return DW_EH_PE_udata4;
2580      case 8: return DW_EH_PE_udata8;
2581      default: vg_assert(0);
2582   }
2583}
2584
2585static UInt size_of_encoded_Addr ( UChar encoding )
2586{
2587   if (encoding == DW_EH_PE_omit)
2588      return 0;
2589
2590   switch (encoding & 0x07) {
2591      case DW_EH_PE_absptr: return sizeof(Addr);
2592      case DW_EH_PE_udata2: return sizeof(UShort);
2593      case DW_EH_PE_udata4: return sizeof(UInt);
2594      case DW_EH_PE_udata8: return sizeof(ULong);
2595      default: vg_assert(0);
2596   }
2597}
2598
2599static Addr read_encoded_Addr ( /*OUT*/Int* nbytes,
2600                                AddressDecodingInfo* adi,
2601                                UChar* data )
2602{
2603   /* Regarding the handling of DW_EH_PE_absptr.  DWARF3 says this
2604      denotes an absolute address, hence you would think 'base' is
2605      zero.  However, that is nonsensical (unless relocations are to
2606      be applied to the unwind data before reading it, which sounds
2607      unlikely).  My interpretation is that DW_EH_PE_absptr indicates
2608      an address relative to where the object was loaded (technically,
2609      relative to its stated load VMA, hence the use of text_bias
2610      rather than text_avma).  Hmm, should we use text_bias or
2611      text_avma here?  Not sure.
2612
2613      This view appears to be supported by DWARF3 spec sec 7.3
2614      "Executable Objects and Shared Objects":
2615
2616         This requirement makes the debugging information for shared
2617         objects position independent.  Virtual addresses in a shared
2618         object may be calculated by adding the offset to the base
2619         address at which the object was attached.  This offset is
2620         available in the run-time linker's data structures.
2621   */
2622   Addr   base;
2623   Word   offset;
2624   UChar  encoding      = adi->encoding;
2625   UChar* ehframe_image = adi->ehframe_image;
2626   Addr   ehframe_avma  = adi->ehframe_avma;
2627
2628   vg_assert((encoding & DW_EH_PE_indirect) == 0);
2629
2630   *nbytes = 0;
2631
2632   switch (encoding & 0x70) {
2633      case DW_EH_PE_absptr:
2634         base = adi->text_bias;
2635         break;
2636      case DW_EH_PE_pcrel:
2637         base = ehframe_avma + ( data - ehframe_image );
2638         break;
2639      case DW_EH_PE_datarel:
2640         vg_assert(0);
2641         base = /* data base address */ 0;
2642         break;
2643      case DW_EH_PE_textrel:
2644         vg_assert(0);
2645         base = /* text base address */ 0;
2646         break;
2647      case DW_EH_PE_funcrel:
2648         base = 0;
2649         break;
2650      case DW_EH_PE_aligned:
2651         base = 0;
2652         offset = data - ehframe_image;
2653         if ((offset % sizeof(Addr)) != 0) {
2654            *nbytes = sizeof(Addr) - (offset % sizeof(Addr));
2655            data += *nbytes;
2656         }
2657         break;
2658      default:
2659         vg_assert(0);
2660   }
2661
2662   if ((encoding & 0x07) == 0x00)
2663      encoding |= default_Addr_encoding();
2664
2665   switch (encoding & 0x0f) {
2666      case DW_EH_PE_udata2:
2667         *nbytes += sizeof(UShort);
2668         return base + ML_(read_UShort)(data);
2669      case DW_EH_PE_udata4:
2670         *nbytes += sizeof(UInt);
2671         return base + ML_(read_UInt)(data);
2672      case DW_EH_PE_udata8:
2673         *nbytes += sizeof(ULong);
2674         return base + ML_(read_ULong)(data);
2675      case DW_EH_PE_sdata2:
2676         *nbytes += sizeof(Short);
2677         return base + ML_(read_Short)(data);
2678      case DW_EH_PE_sdata4:
2679         *nbytes += sizeof(Int);
2680         return base + ML_(read_Int)(data);
2681      case DW_EH_PE_sdata8:
2682         *nbytes += sizeof(Long);
2683         return base + ML_(read_Long)(data);
2684      default:
2685         vg_assert2(0, "read encoded address %d\n", encoding & 0x0f);
2686   }
2687}
2688
2689
2690/* ------------ Run/show DWARF3 expressions ---------- */
2691
2692/* Convert the DWARF3 expression in expr[0 .. exprlen-1] into a dag
2693   (of CfiExprs) stored in ctx->exprs, and return the index in
2694   ctx->exprs of the root node.  Or fail in which case return -1. */
2695/* IMPORTANT: when adding expression forms here, also remember to
2696   add suitable evaluation code in evalCfiExpr in debuginfo.c. */
2697static Int dwarfexpr_to_dag ( UnwindContext* ctx,
2698                              UChar* expr, Int exprlen,
2699                              Bool push_cfa_at_start,
2700                              Bool ddump_frames )
2701{
2702#  define N_EXPR_STACK 20
2703
2704#  define PUSH(_arg)                               \
2705      do {                                         \
2706         vg_assert(sp >= -1 && sp < N_EXPR_STACK); \
2707         if (sp == N_EXPR_STACK-1)                 \
2708            return -1;                             \
2709         sp++;                                     \
2710         stack[sp] = (_arg);                       \
2711      } while (0)
2712
2713#  define POP(_lval)                               \
2714      do {                                         \
2715         vg_assert(sp >= -1 && sp < N_EXPR_STACK); \
2716         if (sp == -1)                             \
2717            return -1;                             \
2718         _lval = stack[sp];                        \
2719         sp--;                                     \
2720      } while (0)
2721
2722   Int      ix, ix2, reg;
2723   UChar    opcode;
2724   Word     sw;
2725   UWord    uw;
2726   CfiUnop  uop;
2727   CfiBinop bop;
2728   const HChar* opname;
2729
2730   Int sp; /* # of top element: valid is -1 .. N_EXPR_STACK-1 */
2731   Int stack[N_EXPR_STACK];  /* indices into ctx->exprs */
2732   struct UnwindContextState* ctxs = &ctx->state[ctx->state_sp];
2733
2734   XArray* dst   = ctx->exprs;
2735   UChar*  limit = expr + exprlen;
2736
2737   vg_assert(dst);
2738   vg_assert(exprlen >= 0);
2739
2740   sp = -1; /* empty */
2741
2742   /* Synthesise the CFA as a CfiExpr */
2743   if (push_cfa_at_start) {
2744      if (ctxs->cfa_is_regoff) {
2745         /* cfa is reg +/- offset */
2746         ix = ML_(CfiExpr_Binop)( dst,
2747                 Cbinop_Add,
2748                 ML_(CfiExpr_DwReg)( dst, ctxs->cfa_reg ),
2749                 ML_(CfiExpr_Const)( dst, (UWord)(Word)ctxs->cfa_off )
2750              );
2751         PUSH(ix);
2752      } else {
2753         /* CFA is already an expr; use its root node */
2754         PUSH(ctxs->cfa_expr_ix);
2755      }
2756   }
2757
2758   while (True) {
2759
2760      vg_assert(sp >= -1 && sp < N_EXPR_STACK);
2761
2762      if (expr > limit)
2763         return -1;  /* overrun - something's wrong */
2764
2765      if (expr == limit) {
2766        /* end of expr - return expr on the top of stack. */
2767        if (sp == -1)
2768           return -1; /* stack empty.  Bad. */
2769        else
2770           break;
2771      }
2772
2773      uop = 0; bop = 0; opname = NULL; /* excessively conservative */
2774
2775      opcode = *expr++;
2776      switch (opcode) {
2777
2778         case DW_OP_lit0 ... DW_OP_lit31:
2779            /* push: literal 0 .. 31 */
2780            sw = (Word)opcode - (Word)DW_OP_lit0;
2781            vg_assert(sw >= 0 && sw <= 31);
2782            PUSH( ML_(CfiExpr_Const)( dst, (UWord)sw ) );
2783            if (ddump_frames)
2784               VG_(printf)("DW_OP_lit%ld", sw);
2785            break;
2786
2787         case DW_OP_breg0 ... DW_OP_breg31:
2788            /* push: reg + sleb128 */
2789            reg = (Int)opcode - (Int)DW_OP_breg0;
2790            vg_assert(reg >= 0 && reg <= 31);
2791            sw = read_leb128S( &expr );
2792            ix = ML_(CfiExpr_Binop)( dst,
2793                    Cbinop_Add,
2794                    ML_(CfiExpr_DwReg)( dst, reg ),
2795                    ML_(CfiExpr_Const)( dst, (UWord)sw )
2796                 );
2797            PUSH(ix);
2798            if (ddump_frames)
2799               VG_(printf)("DW_OP_breg%d: %ld", reg, sw);
2800            break;
2801
2802         case DW_OP_reg0 ... DW_OP_reg31:
2803            /* push: reg */
2804            reg = (Int)opcode - (Int)DW_OP_reg0;
2805            vg_assert(reg >= 0 && reg <= 31);
2806            ix = ML_(CfiExpr_DwReg)( dst, reg );
2807            PUSH(ix);
2808            if (ddump_frames)
2809               VG_(printf)("DW_OP_reg%d", reg);
2810            break;
2811
2812         case DW_OP_plus_uconst:
2813            uw = read_leb128U( &expr );
2814            PUSH( ML_(CfiExpr_Const)( dst, uw ) );
2815            POP( ix );
2816            POP( ix2 );
2817            PUSH( ML_(CfiExpr_Binop)( dst, Cbinop_Add, ix2, ix ) );
2818            if (ddump_frames)
2819               VG_(printf)("DW_OP_plus_uconst: %lu", uw);
2820            break;
2821
2822         case DW_OP_const4s:
2823            /* push: 32-bit signed immediate */
2824            sw = read_le_s_encoded_literal( expr, 4 );
2825            expr += 4;
2826            PUSH( ML_(CfiExpr_Const)( dst, (UWord)sw ) );
2827            if (ddump_frames)
2828               VG_(printf)("DW_OP_const4s: %ld", sw);
2829            break;
2830
2831         case DW_OP_const2s:
2832            /* push: 16-bit signed immediate */
2833            sw = read_le_s_encoded_literal( expr, 2 );
2834            expr += 2;
2835            PUSH( ML_(CfiExpr_Const)( dst, (UWord)sw ) );
2836            if (ddump_frames)
2837               VG_(printf)("DW_OP_const2s: %ld", sw);
2838            break;
2839
2840         case DW_OP_const1s:
2841            /* push: 8-bit signed immediate */
2842            sw = read_le_s_encoded_literal( expr, 1 );
2843            expr += 1;
2844            PUSH( ML_(CfiExpr_Const)( dst, (UWord)sw ) );
2845            if (ddump_frames)
2846               VG_(printf)("DW_OP_const1s: %ld", sw);
2847            break;
2848
2849         case DW_OP_const1u:
2850            /* push: 8-bit unsigned immediate */
2851            uw = read_le_u_encoded_literal( expr, 1 );
2852            expr += 1;
2853            PUSH( ML_(CfiExpr_Const)( dst, uw ) );
2854            if (ddump_frames)
2855               VG_(printf)("DW_OP_const1: %lu", uw);
2856            break;
2857
2858         case DW_OP_const2u:
2859            /* push: 16-bit unsigned immediate */
2860            uw = read_le_u_encoded_literal( expr, 2 );
2861            expr += 2;
2862            PUSH( ML_(CfiExpr_Const)( dst, uw ) );
2863            if (ddump_frames)
2864               VG_(printf)("DW_OP_const2: %lu", uw);
2865            break;
2866
2867         case DW_OP_const4u:
2868            /* push: 32-bit unsigned immediate */
2869            uw = read_le_u_encoded_literal( expr, 4 );
2870            expr += 4;
2871            PUSH( ML_(CfiExpr_Const)( dst, uw ) );
2872            if (ddump_frames)
2873               VG_(printf)("DW_OP_const4: %lu", uw);
2874            break;
2875
2876         case DW_OP_abs:
2877            uop = Cunop_Abs; opname = "abs"; goto unop;
2878         case DW_OP_neg:
2879            uop = Cunop_Neg; opname = "neg"; goto unop;
2880         case DW_OP_not:
2881            uop = Cunop_Not; opname = "not"; goto unop;
2882         unop:
2883            POP( ix );
2884            PUSH( ML_(CfiExpr_Unop)( dst, uop, ix ) );
2885            if (ddump_frames)
2886               VG_(printf)("DW_OP_%s", opname);
2887            break;
2888
2889         case DW_OP_minus:
2890            bop = Cbinop_Sub; opname = "minus"; goto binop;
2891         case DW_OP_plus:
2892            bop = Cbinop_Add; opname = "plus"; goto binop;
2893         case DW_OP_and:
2894            bop = Cbinop_And; opname = "and"; goto binop;
2895         case DW_OP_mul:
2896            bop = Cbinop_Mul; opname = "mul"; goto binop;
2897         case DW_OP_shl:
2898            bop = Cbinop_Shl; opname = "shl"; goto binop;
2899         case DW_OP_shr:
2900            bop = Cbinop_Shr; opname = "shr"; goto binop;
2901         case DW_OP_eq:
2902            bop = Cbinop_Eq; opname = "eq"; goto binop;
2903         case DW_OP_ge:
2904            bop = Cbinop_Ge; opname = "ge"; goto binop;
2905         case DW_OP_gt:
2906            bop = Cbinop_Gt; opname = "gt"; goto binop;
2907         case DW_OP_le:
2908            bop = Cbinop_Le; opname = "le"; goto binop;
2909         case DW_OP_lt:
2910            bop = Cbinop_Lt; opname = "lt"; goto binop;
2911         case DW_OP_ne:
2912            bop = Cbinop_Ne; opname = "ne"; goto binop;
2913         binop:
2914            POP( ix );
2915            POP( ix2 );
2916            PUSH( ML_(CfiExpr_Binop)( dst, bop, ix2, ix ) );
2917            if (ddump_frames)
2918               VG_(printf)("DW_OP_%s", opname);
2919            break;
2920
2921         case DW_OP_deref:
2922            POP( ix );
2923            PUSH( ML_(CfiExpr_Deref)( dst, ix ) );
2924            if (ddump_frames)
2925               VG_(printf)("DW_OP_deref");
2926            break;
2927
2928         default:
2929            if (!VG_(clo_xml))
2930               VG_(message)(Vg_DebugMsg,
2931                            "Warning: DWARF2 CFI reader: unhandled DW_OP_ "
2932                            "opcode 0x%x\n", (Int)opcode);
2933            return -1;
2934      }
2935
2936      if (expr < limit && ddump_frames)
2937         VG_(printf)("; ");
2938
2939   }
2940
2941   vg_assert(sp >= -1 && sp < N_EXPR_STACK);
2942   if (sp == -1)
2943      return -1;
2944
2945   if (0 && ddump_frames)
2946      ML_(ppCfiExpr)( dst, stack[sp] );
2947   return stack[sp];
2948
2949#  undef POP
2950#  undef PUSH
2951#  undef N_EXPR_STACK
2952}
2953
2954
2955/* ------------ Run/show CFI instructions ------------ */
2956
2957/* Run a CFI instruction, and also return its length.
2958   Returns 0 if the instruction could not be executed.
2959*/
2960static Int run_CF_instruction ( /*MOD*/UnwindContext* ctx,
2961                                UChar* instr,
2962                                UnwindContext* restore_ctx,
2963                                AddressDecodingInfo* adi,
2964                                struct _DebugInfo* di )
2965{
2966   Int    off, reg, reg2, nleb, len;
2967   UInt   delta;
2968   UChar* expr;
2969   Int    j;
2970   Int    i   = 0;
2971   UChar  hi2 = (instr[i] >> 6) & 3;
2972   UChar  lo6 = instr[i] & 0x3F;
2973   Addr   printing_bias = ((Addr)ctx->initloc) - ((Addr)di->text_bias);
2974   struct UnwindContextState* ctxs;
2975   i++;
2976
2977   if (ctx->state_sp < 0 || ctx->state_sp >= N_RR_STACK)
2978      return 0; /* bogus reg-rule stack pointer */
2979
2980   ctxs = &ctx->state[ctx->state_sp];
2981   if (hi2 == DW_CFA_advance_loc) {
2982      delta = (UInt)lo6;
2983      delta *= ctx->code_a_f;
2984      ctx->loc += delta;
2985      if (di->ddump_frames)
2986         VG_(printf)("  DW_CFA_advance_loc: %d to %08lx\n",
2987                     (Int)delta, (Addr)ctx->loc + printing_bias);
2988      return i;
2989   }
2990
2991   if (hi2 == DW_CFA_offset) {
2992      /* Set rule for reg 'lo6' to CFAOff(off * data_af) */
2993      off = read_leb128( &instr[i], &nleb, 0 );
2994      i += nleb;
2995      reg = (Int)lo6;
2996      if (reg < 0 || reg >= N_CFI_REGS)
2997         return 0; /* fail */
2998      ctxs->reg[reg].tag = RR_CFAOff;
2999      ctxs->reg[reg].arg = off * ctx->data_a_f;
3000      if (di->ddump_frames)
3001         VG_(printf)("  DW_CFA_offset: r%d at cfa%s%d\n",
3002                     (Int)reg,
3003                     ctxs->reg[reg].arg < 0 ? "" : "+",
3004                     (Int)ctxs->reg[reg].arg );
3005      return i;
3006   }
3007
3008   if (hi2 == DW_CFA_restore) {
3009      reg = (Int)lo6;
3010      if (reg < 0 || reg >= N_CFI_REGS)
3011         return 0; /* fail */
3012      if (restore_ctx == NULL)
3013         return 0; /* fail */
3014      ctxs->reg[reg] = restore_ctx->state[restore_ctx->state_sp].reg[reg];
3015      if (di->ddump_frames)
3016         VG_(printf)("  DW_CFA_restore: r%d\n", (Int)reg);
3017      return i;
3018   }
3019
3020   vg_assert(hi2 == DW_CFA_use_secondary);
3021
3022   switch (lo6) {
3023      case DW_CFA_nop:
3024         if (di->ddump_frames)
3025            VG_(printf)("  DW_CFA_nop\n");
3026         break;
3027      case DW_CFA_set_loc:
3028         /* WAS:
3029            ctx->loc = read_Addr(&instr[i]) - ctx->initloc; i+= sizeof(Addr);
3030            Was this ever right? */
3031         /* 2007 Feb 23: No.  binutils/dwarf.c treats it as an encoded
3032            address and that appears to be in accordance with the
3033            DWARF3 spec. */
3034         ctx->loc = read_encoded_Addr(&len, adi, &instr[i]);
3035         i += len;
3036         if (di->ddump_frames)
3037            VG_(printf)("  rci:DW_CFA_set_loc\n");
3038         break;
3039      case DW_CFA_advance_loc1:
3040         delta = (UInt)ML_(read_UChar)(&instr[i]); i+= sizeof(UChar);
3041         delta *= ctx->code_a_f;
3042         ctx->loc += delta;
3043         if (di->ddump_frames)
3044            VG_(printf)("  DW_CFA_advance_loc1: %d to %08lx\n",
3045                        (Int)delta, (Addr)ctx->loc + printing_bias);
3046         break;
3047      case DW_CFA_advance_loc2:
3048         delta = (UInt)ML_(read_UShort)(&instr[i]); i+= sizeof(UShort);
3049         delta *= ctx->code_a_f;
3050         ctx->loc += delta;
3051         if (di->ddump_frames)
3052            VG_(printf)("  DW_CFA_advance_loc2: %d to %08lx\n",
3053                        (Int)delta, (Addr)ctx->loc + printing_bias);
3054         break;
3055      case DW_CFA_advance_loc4:
3056         delta = (UInt)ML_(read_UInt)(&instr[i]); i+= sizeof(UInt);
3057         delta *= ctx->code_a_f;
3058         ctx->loc += delta;
3059         if (di->ddump_frames)
3060            VG_(printf)("  DW_CFA_advance_loc4: %d to %08lx\n",
3061                        (Int)delta, (Addr)ctx->loc + printing_bias);
3062         break;
3063
3064      case DW_CFA_def_cfa:
3065         reg = read_leb128( &instr[i], &nleb, 0 );
3066         i += nleb;
3067         off = read_leb128( &instr[i], &nleb, 0 );
3068         i += nleb;
3069         if (reg < 0 || reg >= N_CFI_REGS)
3070            return 0; /* fail */
3071         ctxs->cfa_is_regoff = True;
3072         ctxs->cfa_expr_ix   = 0;
3073         ctxs->cfa_reg       = reg;
3074         ctxs->cfa_off       = off;
3075         if (di->ddump_frames)
3076            VG_(printf)("  DW_CFA_def_cfa: r%d ofs %d\n", (Int)reg, (Int)off);
3077         break;
3078
3079      case DW_CFA_def_cfa_sf:
3080         reg = read_leb128( &instr[i], &nleb, 0 );
3081         i += nleb;
3082         off = read_leb128( &instr[i], &nleb, 1 );
3083         i += nleb;
3084         if (reg < 0 || reg >= N_CFI_REGS)
3085            return 0; /* fail */
3086         ctxs->cfa_is_regoff = True;
3087         ctxs->cfa_expr_ix   = 0;
3088         ctxs->cfa_reg       = reg;
3089         ctxs->cfa_off       = off * ctx->data_a_f;
3090         if (di->ddump_frames)
3091            VG_(printf)("  rci:DW_CFA_def_cfa_sf\n");
3092         break;
3093
3094      case DW_CFA_register:
3095         reg = read_leb128( &instr[i], &nleb, 0);
3096         i += nleb;
3097         reg2 = read_leb128( &instr[i], &nleb, 0);
3098         i += nleb;
3099         if (reg < 0 || reg >= N_CFI_REGS)
3100            return 0; /* fail */
3101         if (reg2 < 0 || reg2 >= N_CFI_REGS)
3102            return 0; /* fail */
3103         ctxs->reg[reg].tag = RR_Reg;
3104         ctxs->reg[reg].arg = reg2;
3105         if (di->ddump_frames)
3106            VG_(printf)("  DW_CFA_register: r%d in r%d\n",
3107                        (Int)reg, (Int)reg2);
3108         break;
3109
3110      case DW_CFA_offset_extended:
3111         reg = read_leb128( &instr[i], &nleb, 0 );
3112         i += nleb;
3113         off = read_leb128( &instr[i], &nleb, 0 );
3114         i += nleb;
3115         if (reg < 0 || reg >= N_CFI_REGS)
3116            return 0; /* fail */
3117         ctxs->reg[reg].tag = RR_CFAOff;
3118         ctxs->reg[reg].arg = off * ctx->data_a_f;
3119         if (di->ddump_frames)
3120            VG_(printf)("  rci:DW_CFA_offset_extended\n");
3121         break;
3122
3123      case DW_CFA_offset_extended_sf:
3124         reg = read_leb128( &instr[i], &nleb, 0 );
3125         i += nleb;
3126         off = read_leb128( &instr[i], &nleb, 1 );
3127         i += nleb;
3128         if (reg < 0 || reg >= N_CFI_REGS)
3129            return 0; /* fail */
3130         ctxs->reg[reg].tag = RR_CFAOff;
3131         ctxs->reg[reg].arg = off * ctx->data_a_f;
3132         if (di->ddump_frames)
3133            VG_(printf)("  DW_CFA_offset_extended_sf: r%d at cfa%s%d\n",
3134                        reg,
3135                        ctxs->reg[reg].arg < 0 ? "" : "+",
3136                        (Int)ctxs->reg[reg].arg);
3137         break;
3138
3139      case DW_CFA_GNU_negative_offset_extended:
3140         reg = read_leb128( &instr[i], &nleb, 0 );
3141         i += nleb;
3142         off = read_leb128( &instr[i], &nleb, 0 );
3143         i += nleb;
3144         if (reg < 0 || reg >= N_CFI_REGS)
3145            return 0; /* fail */
3146         ctxs->reg[reg].tag = RR_CFAOff;
3147         ctxs->reg[reg].arg = (-off) * ctx->data_a_f;
3148         if (di->ddump_frames)
3149            VG_(printf)("  rci:DW_CFA_GNU_negative_offset_extended\n");
3150         break;
3151
3152      case DW_CFA_restore_extended:
3153         reg = read_leb128( &instr[i], &nleb, 0 );
3154         i += nleb;
3155         if (reg < 0 || reg >= N_CFI_REGS)
3156            return 0; /* fail */
3157	 if (restore_ctx == NULL)
3158	    return 0; /* fail */
3159	 ctxs->reg[reg] = restore_ctx->state[restore_ctx->state_sp].reg[reg];
3160         if (di->ddump_frames)
3161            VG_(printf)("  rci:DW_CFA_restore_extended\n");
3162         break;
3163
3164      case DW_CFA_val_offset:
3165         reg = read_leb128( &instr[i], &nleb, 0 );
3166         i += nleb;
3167         off = read_leb128( &instr[i], &nleb, 0 );
3168         i += nleb;
3169         if (reg < 0 || reg >= N_CFI_REGS)
3170            return 0; /* fail */
3171         ctxs->reg[reg].tag = RR_CFAValOff;
3172         ctxs->reg[reg].arg = off * ctx->data_a_f;
3173         if (di->ddump_frames)
3174            VG_(printf)("  rci:DW_CFA_val_offset\n");
3175         break;
3176
3177      case DW_CFA_val_offset_sf:
3178         reg = read_leb128( &instr[i], &nleb, 0 );
3179         i += nleb;
3180         off = read_leb128( &instr[i], &nleb, 1 );
3181         i += nleb;
3182         if (reg < 0 || reg >= N_CFI_REGS)
3183            return 0; /* fail */
3184         ctxs->reg[reg].tag = RR_CFAValOff;
3185         ctxs->reg[reg].arg = off * ctx->data_a_f;
3186         if (di->ddump_frames)
3187            VG_(printf)("  rci:DW_CFA_val_offset_sf\n");
3188         break;
3189
3190      case DW_CFA_def_cfa_register:
3191         reg = read_leb128( &instr[i], &nleb, 0);
3192         i += nleb;
3193         if (reg < 0 || reg >= N_CFI_REGS)
3194            return 0; /* fail */
3195         ctxs->cfa_is_regoff = True;
3196         ctxs->cfa_expr_ix   = 0;
3197         ctxs->cfa_reg       = reg;
3198         /* ->cfa_off unchanged */
3199         if (di->ddump_frames)
3200            VG_(printf)("  DW_CFA_def_cfa_register: r%d\n", (Int)reg );
3201         break;
3202
3203      case DW_CFA_def_cfa_offset:
3204         off = read_leb128( &instr[i], &nleb, 0);
3205         i += nleb;
3206         ctxs->cfa_is_regoff = True;
3207         ctxs->cfa_expr_ix   = 0;
3208         /* ->reg is unchanged */
3209         ctxs->cfa_off       = off;
3210         if (di->ddump_frames)
3211            VG_(printf)("  DW_CFA_def_cfa_offset: %d\n", (Int)off);
3212         break;
3213
3214      case DW_CFA_def_cfa_offset_sf:
3215         off = read_leb128( &instr[i], &nleb, 1);
3216         i += nleb;
3217         ctxs->cfa_is_regoff = True;
3218         ctxs->cfa_expr_ix   = 0;
3219         /* ->reg is unchanged */
3220         ctxs->cfa_off       = off * ctx->data_a_f;
3221         if (di->ddump_frames)
3222            VG_(printf)("  DW_CFA_def_cfa_offset_sf: %d\n", ctxs->cfa_off);
3223         break;
3224
3225      case DW_CFA_undefined:
3226         reg = read_leb128( &instr[i], &nleb, 0);
3227         i += nleb;
3228         if (reg < 0 || reg >= N_CFI_REGS)
3229            return 0; /* fail */
3230         ctxs->reg[reg].tag = RR_Undef;
3231         ctxs->reg[reg].arg = 0;
3232         if (di->ddump_frames)
3233            VG_(printf)("  rci:DW_CFA_undefined\n");
3234         break;
3235
3236      case DW_CFA_same_value:
3237         reg = read_leb128( &instr[i], &nleb, 0);
3238         i += nleb;
3239         if (reg < 0 || reg >= N_CFI_REGS)
3240            return 0; /* fail */
3241         ctxs->reg[reg].tag = RR_Same;
3242         ctxs->reg[reg].arg = 0;
3243         if (di->ddump_frames)
3244            VG_(printf)("  rci:DW_CFA_same_value\n");
3245         break;
3246
3247      case DW_CFA_GNU_args_size:
3248         /* No idea what is supposed to happen.  gdb-6.3 simply
3249            ignores these. */
3250         /*off = */ read_leb128( &instr[i], &nleb, 0 );
3251         i += nleb;
3252         if (di->ddump_frames)
3253            VG_(printf)("  rci:DW_CFA_GNU_args_size (ignored)\n");
3254         break;
3255
3256      case DW_CFA_expression:
3257         /* Identical to DW_CFA_val_expression except that the value
3258            computed is an address and so needs one final
3259            dereference. */
3260         reg = read_leb128( &instr[i], &nleb, 0 );
3261         i += nleb;
3262         len = read_leb128( &instr[i], &nleb, 0 );
3263         i += nleb;
3264         expr = &instr[i];
3265         i += len;
3266         if (reg < 0 || reg >= N_CFI_REGS)
3267            return 0; /* fail */
3268         if (di->ddump_frames)
3269            VG_(printf)("  DW_CFA_expression: r%d (",
3270                        (Int)reg);
3271         /* Convert the expression into a dag rooted at ctx->exprs index j,
3272            or fail. */
3273         j = dwarfexpr_to_dag ( ctx, expr, len, True/*push CFA at start*/,
3274                                di->ddump_frames);
3275         if (di->ddump_frames)
3276            VG_(printf)(")\n");
3277         vg_assert(j >= -1);
3278         if (j >= 0) {
3279            vg_assert(ctx->exprs);
3280            vg_assert( j < VG_(sizeXA)(ctx->exprs) );
3281         }
3282         if (j == -1)
3283            return 0; /* fail */
3284         /* Add an extra dereference */
3285         j = ML_(CfiExpr_Deref)( ctx->exprs, j );
3286         ctxs->reg[reg].tag = RR_ValExpr;
3287         ctxs->reg[reg].arg = j;
3288         break;
3289
3290      case DW_CFA_val_expression:
3291         reg = read_leb128( &instr[i], &nleb, 0 );
3292         i += nleb;
3293         len = read_leb128( &instr[i], &nleb, 0 );
3294         i += nleb;
3295         expr = &instr[i];
3296         i += len;
3297         if (reg < 0 || reg >= N_CFI_REGS)
3298            return 0; /* fail */
3299         if (di->ddump_frames)
3300            VG_(printf)("  DW_CFA_val_expression: r%d (",
3301                        (Int)reg);
3302         /* Convert the expression into a dag rooted at ctx->exprs index j,
3303            or fail. */
3304         j = dwarfexpr_to_dag ( ctx, expr, len, True/*push CFA at start*/,
3305                                di->ddump_frames);
3306         if (di->ddump_frames)
3307            VG_(printf)(")\n");
3308         vg_assert(j >= -1);
3309         if (j >= 0) {
3310            vg_assert(ctx->exprs);
3311            vg_assert( j < VG_(sizeXA)(ctx->exprs) );
3312         }
3313         if (j == -1)
3314            return 0; /* fail */
3315         ctxs->reg[reg].tag = RR_ValExpr;
3316         ctxs->reg[reg].arg = j;
3317         break;
3318
3319      case DW_CFA_def_cfa_expression:
3320         len = read_leb128( &instr[i], &nleb, 0 );
3321         i += nleb;
3322         expr = &instr[i];
3323         i += len;
3324         if (di->ddump_frames)
3325            VG_(printf)("  DW_CFA_def_cfa_expression (");
3326         /* Convert the expression into a dag rooted at ctx->exprs index j,
3327            or fail. */
3328         j = dwarfexpr_to_dag ( ctx, expr, len, True/*push CFA at start*/,
3329                                di->ddump_frames);
3330         if (di->ddump_frames)
3331            VG_(printf)(")\n");
3332         ctxs->cfa_is_regoff = False;
3333         ctxs->cfa_reg       = 0;
3334         ctxs->cfa_off       = 0;
3335         ctxs->cfa_expr_ix   = j;
3336         break;
3337
3338      case DW_CFA_GNU_window_save:
3339         /* Ignored.  This appears to be sparc-specific; quite why it
3340            turns up in SuSE-supplied x86 .so's beats me. */
3341         if (di->ddump_frames)
3342            VG_(printf)("  DW_CFA_GNU_window_save\n");
3343         break;
3344
3345      case DW_CFA_remember_state:
3346         if (di->ddump_frames)
3347            VG_(printf)("  DW_CFA_remember_state\n");
3348         /* we just checked this at entry, so: */
3349         vg_assert(ctx->state_sp >= 0 && ctx->state_sp < N_RR_STACK);
3350         ctx->state_sp++;
3351         if (ctx->state_sp == N_RR_STACK) {
3352            /* stack overflow.  We're hosed. */
3353            VG_(message)(Vg_DebugMsg, "DWARF2 CFI reader: N_RR_STACK is "
3354                                      "too low; increase and recompile.");
3355            i = 0; /* indicate failure */
3356         } else {
3357            VG_(memcpy)(/*dst*/&ctx->state[ctx->state_sp],
3358                        /*src*/&ctx->state[ctx->state_sp - 1],
3359                        sizeof(ctx->state[ctx->state_sp]) );
3360         }
3361         break;
3362
3363      case DW_CFA_restore_state:
3364         if (di->ddump_frames)
3365            VG_(printf)("  DW_CFA_restore_state\n");
3366         /* we just checked this at entry, so: */
3367         vg_assert(ctx->state_sp >= 0 && ctx->state_sp < N_RR_STACK);
3368         if (ctx->state_sp == 0) {
3369            /* stack overflow.  Give up. */
3370            i = 0; /* indicate failure */
3371         } else {
3372            /* simply fall back to previous entry */
3373            ctx->state_sp--;
3374         }
3375         break;
3376
3377      default:
3378         VG_(message)(Vg_DebugMsg, "DWARF2 CFI reader: unhandled CFI "
3379                                   "instruction 0:%d\n", (Int)lo6);
3380         if (di->ddump_frames)
3381            VG_(printf)("  rci:run_CF_instruction:default\n");
3382         i = 0;
3383         break;
3384   }
3385
3386   return i;
3387}
3388
3389
3390/* Show a CFI instruction, and also return its length.  Show it as
3391   close as possible (preferably identical) to how GNU binutils
3392   readelf --debug-dump=frames would. */
3393
3394static Int show_CF_instruction ( UChar* instr,
3395                                 AddressDecodingInfo* adi,
3396                                 Int code_a_f, Int data_a_f )
3397{
3398   UInt  delta;
3399   Int   off, coff, reg, reg2, nleb, len;
3400   Addr  loc;
3401   Int   i   = 0;
3402   UChar hi2 = (instr[i] >> 6) & 3;
3403   UChar lo6 = instr[i] & 0x3F;
3404   i++;
3405
3406   if (0) VG_(printf)("raw:%x/%x:%x:%x:%x:%x:%x:%x:%x:%x\n",
3407                      hi2, lo6,
3408                      instr[i+0], instr[i+1], instr[i+2], instr[i+3],
3409                      instr[i+4], instr[i+5], instr[i+6], instr[i+7] );
3410
3411   if (hi2 == DW_CFA_advance_loc) {
3412      VG_(printf)("  sci:DW_CFA_advance_loc(%d)\n", (Int)lo6);
3413      return i;
3414   }
3415
3416   if (hi2 == DW_CFA_offset) {
3417      off = read_leb128( &instr[i], &nleb, 0 );
3418      i += nleb;
3419      coff = off * data_a_f;
3420      VG_(printf)("  DW_CFA_offset: r%d at cfa%s%d\n",
3421                  (Int)lo6, coff < 0 ? "" : "+", (Int)coff );
3422      return i;
3423   }
3424
3425   if (hi2 == DW_CFA_restore) {
3426      VG_(printf)("  sci:DW_CFA_restore(r%d)\n", (Int)lo6);
3427      return i;
3428   }
3429
3430   vg_assert(hi2 == DW_CFA_use_secondary);
3431
3432   switch (lo6) {
3433
3434      case DW_CFA_nop:
3435         VG_(printf)("  DW_CFA_nop\n");
3436         break;
3437
3438      case DW_CFA_set_loc:
3439         /* WAS: loc = read_Addr(&instr[i]); i+= sizeof(Addr);
3440            (now known to be incorrect -- the address is encoded) */
3441         loc = read_encoded_Addr(&len, adi, &instr[i]);
3442         i += len;
3443         VG_(printf)("  sci:DW_CFA_set_loc(%#lx)\n", loc);
3444         break;
3445
3446      case DW_CFA_advance_loc1:
3447         delta = (UInt)ML_(read_UChar)(&instr[i]); i+= sizeof(UChar);
3448         VG_(printf)("  sci:DW_CFA_advance_loc1(%d)\n", delta);
3449         break;
3450
3451      case DW_CFA_advance_loc2:
3452         delta = (UInt)ML_(read_UShort)(&instr[i]); i+= sizeof(UShort);
3453         VG_(printf)("  sci:DW_CFA_advance_loc2(%d)\n", delta);
3454         break;
3455
3456      case DW_CFA_advance_loc4:
3457         delta = (UInt)ML_(read_UInt)(&instr[i]); i+= sizeof(UInt);
3458         VG_(printf)("  DW_CFA_advance_loc4(%d)\n", delta);
3459         break;
3460
3461      case DW_CFA_def_cfa:
3462         reg = read_leb128( &instr[i], &nleb, 0 );
3463         i += nleb;
3464         off = read_leb128( &instr[i], &nleb, 0 );
3465         i += nleb;
3466         VG_(printf)("  DW_CFA_def_cfa: r%d ofs %d\n", (Int)reg, (Int)off);
3467         break;
3468
3469      case DW_CFA_def_cfa_sf:
3470         reg = read_leb128( &instr[i], &nleb, 0 );
3471         i += nleb;
3472         off = read_leb128( &instr[i], &nleb, 1 );
3473         i += nleb;
3474         VG_(printf)("  DW_CFA_def_cfa_sf: r%d ofs %d\n",
3475                     (Int)reg, (Int)(off * data_a_f));
3476         break;
3477
3478      case DW_CFA_register:
3479         reg = read_leb128( &instr[i], &nleb, 0);
3480         i += nleb;
3481         reg2 = read_leb128( &instr[i], &nleb, 0);
3482         i += nleb;
3483         VG_(printf)("  sci:DW_CFA_register(r%d, r%d)\n", reg, reg2);
3484         break;
3485
3486      case DW_CFA_def_cfa_register:
3487         reg = read_leb128( &instr[i], &nleb, 0);
3488         i += nleb;
3489         VG_(printf)("  sci:DW_CFA_def_cfa_register(r%d)\n", reg);
3490         break;
3491
3492      case DW_CFA_def_cfa_offset:
3493         off = read_leb128( &instr[i], &nleb, 0);
3494         i += nleb;
3495         VG_(printf)("  sci:DW_CFA_def_cfa_offset(%d)\n", off);
3496         break;
3497
3498      case DW_CFA_def_cfa_offset_sf:
3499         off = read_leb128( &instr[i], &nleb, 1);
3500         i += nleb;
3501         VG_(printf)("  sci:DW_CFA_def_cfa_offset_sf(%d)\n", off);
3502         break;
3503
3504      case DW_CFA_restore_extended:
3505         reg = read_leb128( &instr[i], &nleb, 0);
3506         i += nleb;
3507         VG_(printf)("  sci:DW_CFA_restore_extended(r%d)\n", reg);
3508         break;
3509
3510      case DW_CFA_undefined:
3511         reg = read_leb128( &instr[i], &nleb, 0);
3512         i += nleb;
3513         VG_(printf)("  sci:DW_CFA_undefined(r%d)\n", reg);
3514         break;
3515
3516      case DW_CFA_same_value:
3517         reg = read_leb128( &instr[i], &nleb, 0);
3518         i += nleb;
3519         VG_(printf)("  sci:DW_CFA_same_value(r%d)\n", reg);
3520         break;
3521
3522      case DW_CFA_remember_state:
3523         VG_(printf)("  sci:DW_CFA_remember_state\n");
3524         break;
3525
3526      case DW_CFA_restore_state:
3527         VG_(printf)("  sci:DW_CFA_restore_state\n");
3528         break;
3529
3530      case DW_CFA_GNU_args_size:
3531         off = read_leb128( &instr[i], &nleb, 0 );
3532         i += nleb;
3533         VG_(printf)("  sci:DW_CFA_GNU_args_size(%d)\n", off );
3534         break;
3535
3536      case DW_CFA_def_cfa_expression:
3537         len = read_leb128( &instr[i], &nleb, 0 );
3538         i += nleb;
3539         i += len;
3540         VG_(printf)("  sci:DW_CFA_def_cfa_expression(length %d)\n", len);
3541         break;
3542
3543      case DW_CFA_expression:
3544         reg = read_leb128( &instr[i], &nleb, 0 );
3545         i += nleb;
3546         len = read_leb128( &instr[i], &nleb, 0 );
3547         i += nleb;
3548         i += len;
3549         VG_(printf)("  sci:DW_CFA_expression(r%d, length %d)\n", reg, len);
3550         break;
3551
3552      case DW_CFA_val_expression:
3553         reg = read_leb128( &instr[i], &nleb, 0 );
3554         i += nleb;
3555         len = read_leb128( &instr[i], &nleb, 0 );
3556         i += nleb;
3557         i += len;
3558         VG_(printf)("  sci:DW_CFA_val_expression(r%d, length %d)\n", reg, len);
3559         break;
3560
3561      case DW_CFA_offset_extended:
3562         reg = read_leb128( &instr[i], &nleb, 0 );
3563         i += nleb;
3564         off = read_leb128( &instr[i], &nleb, 0 );
3565         i += nleb;
3566         VG_(printf)("  sci:DW_CFA_offset_extended(r%d, "
3567                     "off %d x data_af)\n", reg, off);
3568         break;
3569
3570      case DW_CFA_offset_extended_sf:
3571         reg = read_leb128( &instr[i], &nleb, 0 );
3572         i += nleb;
3573         off = read_leb128( &instr[i], &nleb, 1 );
3574         i += nleb;
3575	 coff = (Int)(off * data_a_f);
3576         VG_(printf)("  DW_CFA_offset_extended_sf: r%d at cfa%s%d\n",
3577                        reg, coff < 0 ? "" : "+", coff);
3578         break;
3579
3580      case DW_CFA_GNU_negative_offset_extended:
3581         reg = read_leb128( &instr[i], &nleb, 0 );
3582         i += nleb;
3583         off = read_leb128( &instr[i], &nleb, 0 );
3584         i += nleb;
3585         VG_(printf)("  sci:DW_CFA_GNU_negative_offset_extended"
3586                     "(r%d, off %d x data_af)\n", reg, -off);
3587         break;
3588
3589      case DW_CFA_val_offset:
3590         reg = read_leb128( &instr[i], &nleb, 0 );
3591         i += nleb;
3592         off = read_leb128( &instr[i], &nleb, 0 );
3593         i += nleb;
3594         VG_(printf)("  sci:DW_CFA_val_offset(r%d, off %d x data_af)\n",
3595                     reg, off);
3596         break;
3597
3598       case DW_CFA_val_offset_sf:
3599         reg = read_leb128( &instr[i], &nleb, 0 );
3600         i += nleb;
3601         off = read_leb128( &instr[i], &nleb, 1 );
3602         i += nleb;
3603         VG_(printf)("  sci:DW_CFA_val_offset_sf(r%d, off %d x data_af)\n",
3604                     reg, off);
3605         break;
3606
3607      case DW_CFA_GNU_window_save:
3608         VG_(printf)("  sci:DW_CFA_GNU_window_save\n");
3609         break;
3610
3611      default:
3612         VG_(printf)("  sci:0:%d\n", (Int)lo6);
3613         break;
3614   }
3615
3616   return i;
3617}
3618
3619
3620/* Show the instructions in instrs[0 .. ilen-1]. */
3621static void show_CF_instructions ( UChar* instrs, Int ilen,
3622                                   AddressDecodingInfo* adi,
3623                                   Int code_a_f, Int data_a_f )
3624{
3625   Int i = 0;
3626   while (True) {
3627      if (i >= ilen) break;
3628      i += show_CF_instruction( &instrs[i], adi, code_a_f, data_a_f );
3629   }
3630}
3631
3632
3633/* Run the CF instructions in instrs[0 .. ilen-1], until the end is
3634   reached, or until there is a failure.  Return True iff success.
3635*/
3636static
3637Bool run_CF_instructions ( struct _DebugInfo* di,
3638                           Bool record,
3639                           UnwindContext* ctx, UChar* instrs, Int ilen,
3640                           UWord fde_arange,
3641                           UnwindContext* restore_ctx,
3642                           AddressDecodingInfo* adi )
3643{
3644   DiCfSI cfsi;
3645   Bool summ_ok;
3646   Int j, i = 0;
3647   Addr loc_prev;
3648   if (0) ppUnwindContext(ctx);
3649   if (0) ppUnwindContext_summary(ctx);
3650   while (True) {
3651      loc_prev = ctx->loc;
3652      if (i >= ilen) break;
3653      if (0) (void)show_CF_instruction( &instrs[i], adi,
3654                                        ctx->code_a_f, ctx->data_a_f );
3655      j = run_CF_instruction( ctx, &instrs[i], restore_ctx, adi, di );
3656      if (j == 0)
3657         return False; /* execution failed */
3658      i += j;
3659      if (0) ppUnwindContext(ctx);
3660      if (record && loc_prev != ctx->loc) {
3661         summ_ok = summarise_context ( &cfsi, loc_prev, ctx, di );
3662         if (summ_ok) {
3663            ML_(addDiCfSI)(di, &cfsi);
3664            if (di->trace_cfi)
3665               ML_(ppDiCfSI)(di->cfsi_exprs, &cfsi);
3666         }
3667      }
3668   }
3669   if (ctx->loc < fde_arange) {
3670      loc_prev = ctx->loc;
3671      ctx->loc = fde_arange;
3672      if (record) {
3673         summ_ok = summarise_context ( &cfsi, loc_prev, ctx, di );
3674         if (summ_ok) {
3675            ML_(addDiCfSI)(di, &cfsi);
3676            if (di->trace_cfi)
3677               ML_(ppDiCfSI)(di->cfsi_exprs, &cfsi);
3678         }
3679      }
3680   }
3681   return True;
3682}
3683
3684
3685/* ------------ Main entry point for CFI reading ------------ */
3686
3687typedef
3688   struct {
3689      /* This gives the CIE an identity to which FDEs will refer. */
3690      ULong  offset;
3691      /* Code, data factors. */
3692      Int    code_a_f;
3693      Int    data_a_f;
3694      /* Return-address pseudo-register. */
3695      Int    ra_reg;
3696      UChar  address_encoding;
3697      /* Where are the instrs?  Note, this are simply pointers back to
3698         the transiently-mapped-in section. */
3699      UChar* instrs;
3700      Int    ilen;
3701      /* God knows .. don't ask */
3702      Bool   saw_z_augmentation;
3703   }
3704   CIE;
3705
3706static void init_CIE ( CIE* cie )
3707{
3708   cie->offset             = 0;
3709   cie->code_a_f           = 0;
3710   cie->data_a_f           = 0;
3711   cie->ra_reg             = 0;
3712   cie->address_encoding   = 0;
3713   cie->instrs             = NULL;
3714   cie->ilen               = 0;
3715   cie->saw_z_augmentation = False;
3716}
3717
3718#define N_CIEs 4000
3719static CIE the_CIEs[N_CIEs];
3720
3721
3722/* Read, summarise and store CFA unwind info from .eh_frame and
3723   .debug_frame sections.  is_ehframe tells us which kind we are
3724   dealing with -- they are slightly different. */
3725void ML_(read_callframe_info_dwarf3)
3726        ( /*OUT*/struct _DebugInfo* di,
3727          UChar* frame_image, SizeT frame_size, Addr frame_avma,
3728          Bool is_ehframe )
3729{
3730   Int    nbytes;
3731   const HChar* how = NULL;
3732   Int    n_CIEs = 0;
3733   UChar* data = frame_image;
3734   UWord  cfsi_used_orig;
3735
3736   /* If we're dealing with a .debug_frame, assume zero frame_avma. */
3737   if (!is_ehframe)
3738      vg_assert(frame_avma == 0);
3739
3740#  if defined(VGP_ppc32_linux) || defined(VGP_ppc64_linux)
3741   /* These targets don't use CFI-based stack unwinding.  */
3742   return;
3743#  endif
3744
3745   /* If we read more than one .debug_frame or .eh_frame for this
3746      DebugInfo*, the second and subsequent reads should only add FDEs
3747      for address ranges not already covered by the FDEs already
3748      present.  To be able to quickly check which address ranges are
3749      already present, any existing records (DiCFSIs) must be sorted,
3750      so we can binary-search them in the code below.  We also record
3751      di->cfsi_used so that we know where the boundary is between
3752      existing and new records. */
3753   if (di->cfsi_used > 0) {
3754      ML_(canonicaliseCFI) ( di );
3755   }
3756   cfsi_used_orig = di->cfsi_used;
3757
3758   if (di->trace_cfi) {
3759      VG_(printf)("\n-----------------------------------------------\n");
3760      VG_(printf)("CFI info: szB %ld, _avma %#lx, _image %p\n",
3761                  frame_size, frame_avma, frame_image );
3762      VG_(printf)("CFI info: name %s\n",
3763                  di->fsm.filename );
3764   }
3765
3766   /* Loop over CIEs/FDEs */
3767
3768   /* Conceptually, the frame info is a sequence of FDEs, one for each
3769      function.  Inside an FDE is a miniature program for a special
3770      state machine, which, when run, produces the stack-unwinding
3771      info for that function.
3772
3773      Because the FDEs typically have much in common, and because the
3774      DWARF designers appear to have been fanatical about space
3775      saving, the common parts are factored out into so-called CIEs.
3776      That means that what we traverse is a sequence of structs, each
3777      of which is either a FDE (usually) or a CIE (occasionally).
3778      Each FDE has a field indicating which CIE is the one pertaining
3779      to it.
3780
3781      The following loop traverses the sequence.  FDEs are dealt with
3782      immediately; once we harvest the useful info in an FDE, it is
3783      then forgotten about.  By contrast, CIEs are validated and
3784      dumped into an array, because later FDEs may refer to any
3785      previously-seen CIE.
3786   */
3787   while (True) {
3788      UChar* ciefde_start;
3789      ULong  ciefde_len;
3790      ULong  cie_pointer;
3791      Bool   dw64;
3792
3793      /* Are we done? */
3794      if (data == frame_image + frame_size)
3795         return;
3796
3797      /* Overshot the end?  Means something is wrong */
3798      if (data > frame_image + frame_size) {
3799         how = "overran the end of .eh_frame";
3800         goto bad;
3801      }
3802
3803      /* Ok, we must be looking at the start of a new CIE or FDE.
3804         Figure out which it is. */
3805
3806      ciefde_start = data;
3807      if (di->trace_cfi)
3808         VG_(printf)("\ncie/fde.start   = %p (frame_image + 0x%lx)\n",
3809                     ciefde_start,
3810                     ciefde_start - frame_image + 0UL);
3811
3812      ciefde_len = (ULong)ML_(read_UInt)(data); data += sizeof(UInt);
3813      if (di->trace_cfi)
3814         VG_(printf)("cie/fde.length  = %lld\n", ciefde_len);
3815
3816      /* Apparently, if the .length field is zero, we are at the end
3817         of the sequence.  This is stated in the Generic Elf
3818         Specification (see comments far above here) and is one of the
3819         places where .eh_frame and .debug_frame data differ. */
3820      if (ciefde_len == 0) {
3821         if (di->ddump_frames)
3822            VG_(printf)("%08lx ZERO terminator\n\n",
3823                        ((Addr)ciefde_start) - ((Addr)frame_image));
3824         return;
3825      }
3826
3827      /* If the .length field is 0xFFFFFFFF then we're dealing with
3828         64-bit DWARF, and the real length is stored as a 64-bit
3829         number immediately following it. */
3830      dw64 = False;
3831      if (ciefde_len == 0xFFFFFFFFUL) {
3832         dw64 = True;
3833         ciefde_len = ML_(read_ULong)(data); data += sizeof(ULong);
3834      }
3835
3836      /* Now get the CIE ID, whose size depends on the DWARF 32 vs
3837	 64-ness. */
3838      if (dw64) {
3839         cie_pointer = ML_(read_ULong)(data);
3840         data += sizeof(ULong); /* XXX see XXX below */
3841      } else {
3842         cie_pointer = (ULong)ML_(read_UInt)(data);
3843         data += sizeof(UInt); /* XXX see XXX below */
3844      }
3845
3846      if (di->trace_cfi)
3847         VG_(printf)("cie.pointer     = %lld\n", cie_pointer);
3848
3849      /* If cie_pointer is zero for .eh_frame or all ones for .debug_frame,
3850         we've got a CIE; else it's an FDE. */
3851      if (cie_pointer == (is_ehframe ? 0ULL
3852                          : dw64 ? 0xFFFFFFFFFFFFFFFFULL : 0xFFFFFFFFULL)) {
3853
3854         Int    this_CIE;
3855         UChar  cie_version;
3856         HChar* cie_augmentation;
3857
3858         /* --------- CIE --------- */
3859	 if (di->trace_cfi)
3860            VG_(printf)("------ new CIE (#%d of 0 .. %d) ------\n",
3861                        n_CIEs, N_CIEs - 1);
3862
3863	 /* Allocate a new CIE record. */
3864         vg_assert(n_CIEs >= 0 && n_CIEs <= N_CIEs);
3865         if (n_CIEs == N_CIEs) {
3866            how = "N_CIEs is too low.  Increase and recompile.";
3867            goto bad;
3868         }
3869
3870         this_CIE = n_CIEs;
3871         n_CIEs++;
3872         init_CIE( &the_CIEs[this_CIE] );
3873
3874	 /* Record its offset.  This is how we will find it again
3875            later when looking at an FDE. */
3876         the_CIEs[this_CIE].offset = (ULong)(ciefde_start - frame_image);
3877
3878         if (di->ddump_frames)
3879            VG_(printf)("%08lx %08lx %08lx CIE\n",
3880                        ((Addr)ciefde_start) - ((Addr)frame_image),
3881                        (Addr)ciefde_len,
3882                        (Addr)(UWord)cie_pointer );
3883
3884         cie_version = ML_(read_UChar)(data); data += sizeof(UChar);
3885         if (di->trace_cfi)
3886            VG_(printf)("cie.version     = %d\n", (Int)cie_version);
3887         if (di->ddump_frames)
3888            VG_(printf)("  Version:               %d\n", (Int)cie_version);
3889         if (cie_version != 1 && cie_version != 3 && cie_version != 4) {
3890            how = "unexpected CIE version (not 1 nor 3 nor 4)";
3891            goto bad;
3892         }
3893
3894         cie_augmentation = (HChar *)data;
3895         data += 1 + VG_(strlen)(cie_augmentation);
3896         if (di->trace_cfi)
3897            VG_(printf)("cie.augment     = \"%s\"\n", cie_augmentation);
3898         if (di->ddump_frames)
3899            VG_(printf)("  Augmentation:          \"%s\"\n", cie_augmentation);
3900
3901         if (cie_augmentation[0] == 'e' && cie_augmentation[1] == 'h') {
3902            data += sizeof(Addr);
3903            cie_augmentation += 2;
3904         }
3905
3906         if (cie_version >= 4) {
3907            if (ML_(read_UChar)(data) != sizeof(Addr)) {
3908               how = "unexpected address size";
3909               goto bad;
3910            }
3911            data += sizeof(UChar);
3912            if (ML_(read_UChar)(data) != 0) {
3913               how = "unexpected non-zero segment size";
3914               goto bad;
3915            }
3916            data += sizeof(UChar);
3917         }
3918
3919         the_CIEs[this_CIE].code_a_f = read_leb128( data, &nbytes, 0);
3920         data += nbytes;
3921         if (di->trace_cfi)
3922            VG_(printf)("cie.code_af     = %d\n",
3923                        the_CIEs[this_CIE].code_a_f);
3924         if (di->ddump_frames)
3925            VG_(printf)("  Code alignment factor: %d\n",
3926                        (Int)the_CIEs[this_CIE].code_a_f);
3927
3928         the_CIEs[this_CIE].data_a_f = read_leb128( data, &nbytes, 1);
3929         data += nbytes;
3930         if (di->trace_cfi)
3931            VG_(printf)("cie.data_af     = %d\n",
3932                        the_CIEs[this_CIE].data_a_f);
3933         if (di->ddump_frames)
3934            VG_(printf)("  Data alignment factor: %d\n",
3935                        (Int)the_CIEs[this_CIE].data_a_f);
3936
3937         if (cie_version == 1) {
3938            the_CIEs[this_CIE].ra_reg = (Int)ML_(read_UChar)(data);
3939            data += sizeof(UChar);
3940         } else {
3941            the_CIEs[this_CIE].ra_reg = read_leb128( data, &nbytes, 0);
3942            data += nbytes;
3943         }
3944         if (di->trace_cfi)
3945            VG_(printf)("cie.ra_reg      = %d\n",
3946                        the_CIEs[this_CIE].ra_reg);
3947         if (di->ddump_frames)
3948            VG_(printf)("  Return address column: %d\n",
3949                        (Int)the_CIEs[this_CIE].ra_reg);
3950
3951         if (the_CIEs[this_CIE].ra_reg < 0
3952             || the_CIEs[this_CIE].ra_reg >= N_CFI_REGS) {
3953            how = "cie.ra_reg has implausible value";
3954            goto bad;
3955         }
3956
3957         the_CIEs[this_CIE].saw_z_augmentation
3958            = *cie_augmentation == 'z';
3959         if (the_CIEs[this_CIE].saw_z_augmentation) {
3960            UInt length = read_leb128( data, &nbytes, 0);
3961            data += nbytes;
3962            the_CIEs[this_CIE].instrs = data + length;
3963            cie_augmentation++;
3964            if (di->ddump_frames) {
3965               UInt i;
3966               VG_(printf)("  Augmentation data:    ");
3967               for (i = 0; i < length; i++)
3968                  VG_(printf)(" %02x", (UInt)data[i]);
3969               VG_(printf)("\n");
3970            }
3971         } else {
3972            the_CIEs[this_CIE].instrs = NULL;
3973         }
3974
3975         the_CIEs[this_CIE].address_encoding = default_Addr_encoding();
3976
3977         while (*cie_augmentation) {
3978            switch (*cie_augmentation) {
3979               case 'L':
3980                  data++;
3981                  cie_augmentation++;
3982                  break;
3983               case 'R':
3984                  the_CIEs[this_CIE].address_encoding
3985                     = ML_(read_UChar)(data); data += sizeof(UChar);
3986                  cie_augmentation++;
3987                  break;
3988               case 'P':
3989                  data += size_of_encoded_Addr( ML_(read_UChar)(data) );
3990                  data++;
3991                  cie_augmentation++;
3992                  break;
3993               case 'S':
3994                  cie_augmentation++;
3995                  break;
3996               default:
3997                  if (the_CIEs[this_CIE].instrs == NULL) {
3998                     how = "unhandled cie.augmentation";
3999                     goto bad;
4000                  }
4001                  data = the_CIEs[this_CIE].instrs;
4002                  goto done_augmentation;
4003            }
4004         }
4005
4006        done_augmentation:
4007
4008         if (di->trace_cfi)
4009            VG_(printf)("cie.encoding    = 0x%x\n",
4010                        the_CIEs[this_CIE].address_encoding);
4011
4012         the_CIEs[this_CIE].instrs = data;
4013         the_CIEs[this_CIE].ilen
4014            = ciefde_start + ciefde_len + sizeof(UInt) - data;
4015         if (di->trace_cfi) {
4016            VG_(printf)("cie.instrs      = %p\n", the_CIEs[this_CIE].instrs);
4017            VG_(printf)("cie.ilen        = %d\n", the_CIEs[this_CIE].ilen);
4018	 }
4019
4020         if (the_CIEs[this_CIE].ilen < 0
4021             || the_CIEs[this_CIE].ilen > frame_size) {
4022            how = "implausible # cie initial insns";
4023            goto bad;
4024         }
4025
4026         data += the_CIEs[this_CIE].ilen;
4027
4028         /* Show the CIE's instructions (the preamble for each FDE
4029            that uses this CIE). */
4030         if (di->ddump_frames)
4031            VG_(printf)("\n");
4032
4033         if (di->trace_cfi || di->ddump_frames) {
4034            AddressDecodingInfo adi;
4035            adi.encoding      = the_CIEs[this_CIE].address_encoding;
4036            adi.ehframe_image = frame_image;
4037            adi.ehframe_avma  = frame_avma;
4038            adi.text_bias     = di->text_debug_bias;
4039            show_CF_instructions( the_CIEs[this_CIE].instrs,
4040                                  the_CIEs[this_CIE].ilen, &adi,
4041                                  the_CIEs[this_CIE].code_a_f,
4042                                  the_CIEs[this_CIE].data_a_f );
4043         }
4044
4045         if (di->ddump_frames)
4046            VG_(printf)("\n");
4047
4048      } else {
4049
4050         AddressDecodingInfo adi;
4051         UnwindContext ctx, restore_ctx;
4052         Int    cie;
4053         ULong  look_for;
4054         Bool   ok;
4055         Addr   fde_initloc;
4056         UWord  fde_arange;
4057         UChar* fde_instrs;
4058         Int    fde_ilen;
4059
4060         /* --------- FDE --------- */
4061
4062         /* Find the relevant CIE.  The CIE we want is located
4063            cie_pointer bytes back from here. */
4064
4065         /* re sizeof(UInt) / sizeof(ULong), matches XXX above. */
4066         if (is_ehframe)
4067            look_for = (data - (dw64 ? sizeof(ULong) : sizeof(UInt))
4068                             - frame_image)
4069                       - cie_pointer;
4070         else
4071            look_for = cie_pointer;
4072
4073         for (cie = 0; cie < n_CIEs; cie++) {
4074            if (0) VG_(printf)("look for %lld   %lld\n",
4075                               look_for, the_CIEs[cie].offset );
4076            if (the_CIEs[cie].offset == look_for)
4077               break;
4078	 }
4079         vg_assert(cie >= 0 && cie <= n_CIEs);
4080         if (cie == n_CIEs) {
4081            how = "FDE refers to not-findable CIE";
4082            goto bad;
4083	 }
4084
4085         adi.encoding      = the_CIEs[cie].address_encoding;
4086         adi.ehframe_image = frame_image;
4087         adi.ehframe_avma  = frame_avma;
4088         adi.text_bias     = di->text_debug_bias;
4089         fde_initloc = read_encoded_Addr(&nbytes, &adi, data);
4090         data += nbytes;
4091         if (di->trace_cfi)
4092            VG_(printf)("fde.initloc     = %#lx\n", fde_initloc);
4093
4094         adi.encoding      = the_CIEs[cie].address_encoding & 0xf;
4095         adi.ehframe_image = frame_image;
4096         adi.ehframe_avma  = frame_avma;
4097         adi.text_bias     = di->text_debug_bias;
4098
4099         /* WAS (incorrectly):
4100            fde_arange = read_encoded_Addr(&nbytes, &adi, data);
4101            data += nbytes;
4102            The following corresponds to what binutils/dwarf.c does:
4103         */
4104         { UInt ptr_size = size_of_encoded_Addr( adi.encoding );
4105           switch (ptr_size) {
4106              case 8: case 4: case 2: case 1:
4107                 fde_arange
4108                    = (UWord)read_le_u_encoded_literal(data, ptr_size);
4109                 data += ptr_size;
4110                 break;
4111              default:
4112                 how = "unknown arange field encoding in FDE";
4113                 goto bad;
4114           }
4115         }
4116
4117         if (di->trace_cfi)
4118            VG_(printf)("fde.arangec     = %#lx\n", fde_arange);
4119
4120         if (di->ddump_frames)
4121            VG_(printf)("%08lx %08lx %08lx FDE cie=%08lx pc=%08lx..%08lx\n",
4122                        ((Addr)ciefde_start) - ((Addr)frame_image),
4123                        (Addr)ciefde_len,
4124                        (Addr)(UWord)cie_pointer,
4125                        (Addr)look_for,
4126                        ((Addr)fde_initloc) - di->text_debug_bias,
4127                        ((Addr)fde_initloc) - di->text_debug_bias + fde_arange);
4128
4129         if (the_CIEs[cie].saw_z_augmentation) {
4130            UInt length = read_leb128( data, &nbytes, 0);
4131            data += nbytes;
4132            if (di->ddump_frames && (length > 0)) {
4133               UInt i;
4134               VG_(printf)("  Augmentation data:    ");
4135               for (i = 0; i < length; i++)
4136                  VG_(printf)(" %02x", (UInt)data[i]);
4137               VG_(printf)("\n\n");
4138            }
4139            data += length;
4140         }
4141
4142         fde_instrs = data;
4143         fde_ilen   = ciefde_start + ciefde_len + sizeof(UInt) - data;
4144         if (di->trace_cfi) {
4145            VG_(printf)("fde.instrs      = %p\n", fde_instrs);
4146            VG_(printf)("fde.ilen        = %d\n", (Int)fde_ilen);
4147	 }
4148
4149         if (fde_ilen < 0 || fde_ilen > frame_size) {
4150            how = "implausible # fde insns";
4151            goto bad;
4152         }
4153
4154	 data += fde_ilen;
4155
4156         /* If this object's DebugInfo* had some DiCFSIs from a
4157            previous .eh_frame or .debug_frame read, we must check
4158            that we're not adding a duplicate. */
4159         if (cfsi_used_orig > 0) {
4160            Addr a_mid_lo, a_mid_hi;
4161            Word mid, size,
4162                 lo = 0,
4163                 hi = cfsi_used_orig-1;
4164            while (True) {
4165               /* current unsearched space is from lo to hi, inclusive. */
4166               if (lo > hi) break; /* not found */
4167               mid      = (lo + hi) / 2;
4168               a_mid_lo = di->cfsi[mid].base;
4169               size     = di->cfsi[mid].len;
4170               a_mid_hi = a_mid_lo + size - 1;
4171               vg_assert(a_mid_hi >= a_mid_lo);
4172               if (fde_initloc + fde_arange <= a_mid_lo) {
4173                  hi = mid-1; continue;
4174               }
4175               if (fde_initloc > a_mid_hi) { lo = mid+1; continue; }
4176               break;
4177            }
4178
4179            /* The range this .debug_frame FDE covers has been already
4180               covered in .eh_frame section.  Don't add it from .debug_frame
4181               section again.  */
4182            if (lo <= hi)
4183               continue;
4184         }
4185
4186         adi.encoding      = the_CIEs[cie].address_encoding;
4187         adi.ehframe_image = frame_image;
4188         adi.ehframe_avma  = frame_avma;
4189         adi.text_bias     = di->text_debug_bias;
4190
4191         if (di->trace_cfi)
4192            show_CF_instructions( fde_instrs, fde_ilen, &adi,
4193                                  the_CIEs[cie].code_a_f,
4194                                  the_CIEs[cie].data_a_f );
4195
4196	 initUnwindContext(&ctx);
4197         ctx.code_a_f = the_CIEs[cie].code_a_f;
4198         ctx.data_a_f = the_CIEs[cie].data_a_f;
4199         ctx.initloc  = fde_initloc;
4200         ctx.ra_reg   = the_CIEs[cie].ra_reg;
4201         ctx.exprs    = VG_(newXA)( ML_(dinfo_zalloc), "di.rcid.1",
4202                                    ML_(dinfo_free),
4203                                    sizeof(CfiExpr) );
4204         vg_assert(ctx.exprs);
4205
4206	 /* Run the CIE's instructions.  Ugly hack: if
4207            --debug-dump=frames is in effect, suppress output for
4208            these instructions since they will already have been shown
4209            at the time the CIE was first encountered.  Note, not
4210            thread safe - if this reader is ever made threaded, should
4211            fix properly. */
4212	 { Bool hack = di->ddump_frames;
4213           di->ddump_frames = False;
4214           initUnwindContext(&restore_ctx);
4215           ok = run_CF_instructions(
4216                   di, False, &ctx, the_CIEs[cie].instrs,
4217                   the_CIEs[cie].ilen, 0, NULL, &adi
4218                );
4219           di->ddump_frames = hack;
4220         }
4221         /* And now run the instructions for the FDE, starting from
4222            the state created by running the CIE preamble
4223            instructions. */
4224         if (ok) {
4225            restore_ctx = ctx;
4226	    ok = run_CF_instructions(
4227                    di, True, &ctx, fde_instrs, fde_ilen, fde_arange,
4228                    &restore_ctx, &adi
4229                 );
4230            if (di->ddump_frames)
4231               VG_(printf)("\n");
4232	 }
4233
4234         VG_(deleteXA)( ctx.exprs );
4235      }
4236   }
4237
4238   return;
4239
4240   bad:
4241    if (!VG_(clo_xml) && VG_(clo_verbosity) > 1)
4242       VG_(message)(Vg_UserMsg,
4243                    "Warning: %s in DWARF2 CFI reading\n", how);
4244    return;
4245}
4246
4247#endif // defined(VGO_linux) || defined(VGO_darwin)
4248
4249/*--------------------------------------------------------------------*/
4250/*--- end                                                          ---*/
4251/*--------------------------------------------------------------------*/
4252