record-btrace: extend unwinder
[platform/upstream/binutils.git] / gdb / dwarf2-frame.c
1 /* Frame unwinder for frames with DWARF Call Frame Information.
2
3    Copyright (C) 2003-2014 Free Software Foundation, Inc.
4
5    Contributed by Mark Kettenis.
6
7    This file is part of GDB.
8
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 3 of the License, or
12    (at your option) any later version.
13
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18
19    You should have received a copy of the GNU General Public License
20    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
21
22 #include "defs.h"
23 #include "dwarf2expr.h"
24 #include "dwarf2.h"
25 #include "frame.h"
26 #include "frame-base.h"
27 #include "frame-unwind.h"
28 #include "gdbcore.h"
29 #include "gdbtypes.h"
30 #include "symtab.h"
31 #include "objfiles.h"
32 #include "regcache.h"
33 #include "value.h"
34 #include "record.h"
35
36 #include "gdb_assert.h"
37 #include <string.h>
38
39 #include "complaints.h"
40 #include "dwarf2-frame.h"
41 #include "ax.h"
42 #include "dwarf2loc.h"
43 #include "exceptions.h"
44 #include "dwarf2-frame-tailcall.h"
45
46 struct comp_unit;
47
48 /* Call Frame Information (CFI).  */
49
50 /* Common Information Entry (CIE).  */
51
52 struct dwarf2_cie
53 {
54   /* Computation Unit for this CIE.  */
55   struct comp_unit *unit;
56
57   /* Offset into the .debug_frame section where this CIE was found.
58      Used to identify this CIE.  */
59   ULONGEST cie_pointer;
60
61   /* Constant that is factored out of all advance location
62      instructions.  */
63   ULONGEST code_alignment_factor;
64
65   /* Constants that is factored out of all offset instructions.  */
66   LONGEST data_alignment_factor;
67
68   /* Return address column.  */
69   ULONGEST return_address_register;
70
71   /* Instruction sequence to initialize a register set.  */
72   const gdb_byte *initial_instructions;
73   const gdb_byte *end;
74
75   /* Saved augmentation, in case it's needed later.  */
76   char *augmentation;
77
78   /* Encoding of addresses.  */
79   gdb_byte encoding;
80
81   /* Target address size in bytes.  */
82   int addr_size;
83
84   /* Target pointer size in bytes.  */
85   int ptr_size;
86
87   /* True if a 'z' augmentation existed.  */
88   unsigned char saw_z_augmentation;
89
90   /* True if an 'S' augmentation existed.  */
91   unsigned char signal_frame;
92
93   /* The version recorded in the CIE.  */
94   unsigned char version;
95
96   /* The segment size.  */
97   unsigned char segment_size;
98 };
99
100 struct dwarf2_cie_table
101 {
102   int num_entries;
103   struct dwarf2_cie **entries;
104 };
105
106 /* Frame Description Entry (FDE).  */
107
108 struct dwarf2_fde
109 {
110   /* CIE for this FDE.  */
111   struct dwarf2_cie *cie;
112
113   /* First location associated with this FDE.  */
114   CORE_ADDR initial_location;
115
116   /* Number of bytes of program instructions described by this FDE.  */
117   CORE_ADDR address_range;
118
119   /* Instruction sequence.  */
120   const gdb_byte *instructions;
121   const gdb_byte *end;
122
123   /* True if this FDE is read from a .eh_frame instead of a .debug_frame
124      section.  */
125   unsigned char eh_frame_p;
126 };
127
128 struct dwarf2_fde_table
129 {
130   int num_entries;
131   struct dwarf2_fde **entries;
132 };
133
134 /* A minimal decoding of DWARF2 compilation units.  We only decode
135    what's needed to get to the call frame information.  */
136
137 struct comp_unit
138 {
139   /* Keep the bfd convenient.  */
140   bfd *abfd;
141
142   struct objfile *objfile;
143
144   /* Pointer to the .debug_frame section loaded into memory.  */
145   const gdb_byte *dwarf_frame_buffer;
146
147   /* Length of the loaded .debug_frame section.  */
148   bfd_size_type dwarf_frame_size;
149
150   /* Pointer to the .debug_frame section.  */
151   asection *dwarf_frame_section;
152
153   /* Base for DW_EH_PE_datarel encodings.  */
154   bfd_vma dbase;
155
156   /* Base for DW_EH_PE_textrel encodings.  */
157   bfd_vma tbase;
158 };
159
160 static struct dwarf2_fde *dwarf2_frame_find_fde (CORE_ADDR *pc,
161                                                  CORE_ADDR *out_offset);
162
163 static int dwarf2_frame_adjust_regnum (struct gdbarch *gdbarch, int regnum,
164                                        int eh_frame_p);
165
166 static CORE_ADDR read_encoded_value (struct comp_unit *unit, gdb_byte encoding,
167                                      int ptr_len, const gdb_byte *buf,
168                                      unsigned int *bytes_read_ptr,
169                                      CORE_ADDR func_base);
170 \f
171
172 /* Structure describing a frame state.  */
173
174 struct dwarf2_frame_state
175 {
176   /* Each register save state can be described in terms of a CFA slot,
177      another register, or a location expression.  */
178   struct dwarf2_frame_state_reg_info
179   {
180     struct dwarf2_frame_state_reg *reg;
181     int num_regs;
182
183     LONGEST cfa_offset;
184     ULONGEST cfa_reg;
185     enum {
186       CFA_UNSET,
187       CFA_REG_OFFSET,
188       CFA_EXP
189     } cfa_how;
190     const gdb_byte *cfa_exp;
191
192     /* Used to implement DW_CFA_remember_state.  */
193     struct dwarf2_frame_state_reg_info *prev;
194   } regs;
195
196   /* The PC described by the current frame state.  */
197   CORE_ADDR pc;
198
199   /* Initial register set from the CIE.
200      Used to implement DW_CFA_restore.  */
201   struct dwarf2_frame_state_reg_info initial;
202
203   /* The information we care about from the CIE.  */
204   LONGEST data_align;
205   ULONGEST code_align;
206   ULONGEST retaddr_column;
207
208   /* Flags for known producer quirks.  */
209
210   /* The ARM compilers, in DWARF2 mode, assume that DW_CFA_def_cfa
211      and DW_CFA_def_cfa_offset takes a factored offset.  */
212   int armcc_cfa_offsets_sf;
213
214   /* The ARM compilers, in DWARF2 or DWARF3 mode, may assume that
215      the CFA is defined as REG - OFFSET rather than REG + OFFSET.  */
216   int armcc_cfa_offsets_reversed;
217 };
218
219 /* Store the length the expression for the CFA in the `cfa_reg' field,
220    which is unused in that case.  */
221 #define cfa_exp_len cfa_reg
222
223 /* Assert that the register set RS is large enough to store gdbarch_num_regs
224    columns.  If necessary, enlarge the register set.  */
225
226 static void
227 dwarf2_frame_state_alloc_regs (struct dwarf2_frame_state_reg_info *rs,
228                                int num_regs)
229 {
230   size_t size = sizeof (struct dwarf2_frame_state_reg);
231
232   if (num_regs <= rs->num_regs)
233     return;
234
235   rs->reg = (struct dwarf2_frame_state_reg *)
236     xrealloc (rs->reg, num_regs * size);
237
238   /* Initialize newly allocated registers.  */
239   memset (rs->reg + rs->num_regs, 0, (num_regs - rs->num_regs) * size);
240   rs->num_regs = num_regs;
241 }
242
243 /* Copy the register columns in register set RS into newly allocated
244    memory and return a pointer to this newly created copy.  */
245
246 static struct dwarf2_frame_state_reg *
247 dwarf2_frame_state_copy_regs (struct dwarf2_frame_state_reg_info *rs)
248 {
249   size_t size = rs->num_regs * sizeof (struct dwarf2_frame_state_reg);
250   struct dwarf2_frame_state_reg *reg;
251
252   reg = (struct dwarf2_frame_state_reg *) xmalloc (size);
253   memcpy (reg, rs->reg, size);
254
255   return reg;
256 }
257
258 /* Release the memory allocated to register set RS.  */
259
260 static void
261 dwarf2_frame_state_free_regs (struct dwarf2_frame_state_reg_info *rs)
262 {
263   if (rs)
264     {
265       dwarf2_frame_state_free_regs (rs->prev);
266
267       xfree (rs->reg);
268       xfree (rs);
269     }
270 }
271
272 /* Release the memory allocated to the frame state FS.  */
273
274 static void
275 dwarf2_frame_state_free (void *p)
276 {
277   struct dwarf2_frame_state *fs = p;
278
279   dwarf2_frame_state_free_regs (fs->initial.prev);
280   dwarf2_frame_state_free_regs (fs->regs.prev);
281   xfree (fs->initial.reg);
282   xfree (fs->regs.reg);
283   xfree (fs);
284 }
285 \f
286
287 /* Helper functions for execute_stack_op.  */
288
289 static CORE_ADDR
290 read_addr_from_reg (void *baton, int reg)
291 {
292   struct frame_info *this_frame = (struct frame_info *) baton;
293   struct gdbarch *gdbarch = get_frame_arch (this_frame);
294   int regnum;
295   gdb_byte *buf;
296
297   regnum = gdbarch_dwarf2_reg_to_regnum (gdbarch, reg);
298
299   buf = alloca (register_size (gdbarch, regnum));
300   get_frame_register (this_frame, regnum, buf);
301
302   return unpack_pointer (register_type (gdbarch, regnum), buf);
303 }
304
305 /* Implement struct dwarf_expr_context_funcs' "get_reg_value" callback.  */
306
307 static struct value *
308 get_reg_value (void *baton, struct type *type, int reg)
309 {
310   struct frame_info *this_frame = (struct frame_info *) baton;
311   struct gdbarch *gdbarch = get_frame_arch (this_frame);
312   int regnum = gdbarch_dwarf2_reg_to_regnum (gdbarch, reg);
313
314   return value_from_register (type, regnum, this_frame);
315 }
316
317 static void
318 read_mem (void *baton, gdb_byte *buf, CORE_ADDR addr, size_t len)
319 {
320   read_memory (addr, buf, len);
321 }
322
323 /* Execute the required actions for both the DW_CFA_restore and
324 DW_CFA_restore_extended instructions.  */
325 static void
326 dwarf2_restore_rule (struct gdbarch *gdbarch, ULONGEST reg_num,
327                      struct dwarf2_frame_state *fs, int eh_frame_p)
328 {
329   ULONGEST reg;
330
331   gdb_assert (fs->initial.reg);
332   reg = dwarf2_frame_adjust_regnum (gdbarch, reg_num, eh_frame_p);
333   dwarf2_frame_state_alloc_regs (&fs->regs, reg + 1);
334
335   /* Check if this register was explicitly initialized in the
336   CIE initial instructions.  If not, default the rule to
337   UNSPECIFIED.  */
338   if (reg < fs->initial.num_regs)
339     fs->regs.reg[reg] = fs->initial.reg[reg];
340   else
341     fs->regs.reg[reg].how = DWARF2_FRAME_REG_UNSPECIFIED;
342
343   if (fs->regs.reg[reg].how == DWARF2_FRAME_REG_UNSPECIFIED)
344     complaint (&symfile_complaints, _("\
345 incomplete CFI data; DW_CFA_restore unspecified\n\
346 register %s (#%d) at %s"),
347                        gdbarch_register_name
348                        (gdbarch, gdbarch_dwarf2_reg_to_regnum (gdbarch, reg)),
349                        gdbarch_dwarf2_reg_to_regnum (gdbarch, reg),
350                        paddress (gdbarch, fs->pc));
351 }
352
353 /* Virtual method table for execute_stack_op below.  */
354
355 static const struct dwarf_expr_context_funcs dwarf2_frame_ctx_funcs =
356 {
357   read_addr_from_reg,
358   get_reg_value,
359   read_mem,
360   ctx_no_get_frame_base,
361   ctx_no_get_frame_cfa,
362   ctx_no_get_frame_pc,
363   ctx_no_get_tls_address,
364   ctx_no_dwarf_call,
365   ctx_no_get_base_type,
366   ctx_no_push_dwarf_reg_entry_value,
367   ctx_no_get_addr_index
368 };
369
370 static CORE_ADDR
371 execute_stack_op (const gdb_byte *exp, ULONGEST len, int addr_size,
372                   CORE_ADDR offset, struct frame_info *this_frame,
373                   CORE_ADDR initial, int initial_in_stack_memory)
374 {
375   struct dwarf_expr_context *ctx;
376   CORE_ADDR result;
377   struct cleanup *old_chain;
378
379   ctx = new_dwarf_expr_context ();
380   old_chain = make_cleanup_free_dwarf_expr_context (ctx);
381   make_cleanup_value_free_to_mark (value_mark ());
382
383   ctx->gdbarch = get_frame_arch (this_frame);
384   ctx->addr_size = addr_size;
385   ctx->ref_addr_size = -1;
386   ctx->offset = offset;
387   ctx->baton = this_frame;
388   ctx->funcs = &dwarf2_frame_ctx_funcs;
389
390   dwarf_expr_push_address (ctx, initial, initial_in_stack_memory);
391   dwarf_expr_eval (ctx, exp, len);
392
393   if (ctx->location == DWARF_VALUE_MEMORY)
394     result = dwarf_expr_fetch_address (ctx, 0);
395   else if (ctx->location == DWARF_VALUE_REGISTER)
396     result = read_addr_from_reg (this_frame,
397                                  value_as_long (dwarf_expr_fetch (ctx, 0)));
398   else
399     {
400       /* This is actually invalid DWARF, but if we ever do run across
401          it somehow, we might as well support it.  So, instead, report
402          it as unimplemented.  */
403       error (_("\
404 Not implemented: computing unwound register using explicit value operator"));
405     }
406
407   do_cleanups (old_chain);
408
409   return result;
410 }
411 \f
412
413 /* Execute FDE program from INSN_PTR possibly up to INSN_END or up to inferior
414    PC.  Modify FS state accordingly.  Return current INSN_PTR where the
415    execution has stopped, one can resume it on the next call.  */
416
417 static const gdb_byte *
418 execute_cfa_program (struct dwarf2_fde *fde, const gdb_byte *insn_ptr,
419                      const gdb_byte *insn_end, struct gdbarch *gdbarch,
420                      CORE_ADDR pc, struct dwarf2_frame_state *fs)
421 {
422   int eh_frame_p = fde->eh_frame_p;
423   unsigned int bytes_read;
424   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
425
426   while (insn_ptr < insn_end && fs->pc <= pc)
427     {
428       gdb_byte insn = *insn_ptr++;
429       uint64_t utmp, reg;
430       int64_t offset;
431
432       if ((insn & 0xc0) == DW_CFA_advance_loc)
433         fs->pc += (insn & 0x3f) * fs->code_align;
434       else if ((insn & 0xc0) == DW_CFA_offset)
435         {
436           reg = insn & 0x3f;
437           reg = dwarf2_frame_adjust_regnum (gdbarch, reg, eh_frame_p);
438           insn_ptr = safe_read_uleb128 (insn_ptr, insn_end, &utmp);
439           offset = utmp * fs->data_align;
440           dwarf2_frame_state_alloc_regs (&fs->regs, reg + 1);
441           fs->regs.reg[reg].how = DWARF2_FRAME_REG_SAVED_OFFSET;
442           fs->regs.reg[reg].loc.offset = offset;
443         }
444       else if ((insn & 0xc0) == DW_CFA_restore)
445         {
446           reg = insn & 0x3f;
447           dwarf2_restore_rule (gdbarch, reg, fs, eh_frame_p);
448         }
449       else
450         {
451           switch (insn)
452             {
453             case DW_CFA_set_loc:
454               fs->pc = read_encoded_value (fde->cie->unit, fde->cie->encoding,
455                                            fde->cie->ptr_size, insn_ptr,
456                                            &bytes_read, fde->initial_location);
457               /* Apply the objfile offset for relocatable objects.  */
458               fs->pc += ANOFFSET (fde->cie->unit->objfile->section_offsets,
459                                   SECT_OFF_TEXT (fde->cie->unit->objfile));
460               insn_ptr += bytes_read;
461               break;
462
463             case DW_CFA_advance_loc1:
464               utmp = extract_unsigned_integer (insn_ptr, 1, byte_order);
465               fs->pc += utmp * fs->code_align;
466               insn_ptr++;
467               break;
468             case DW_CFA_advance_loc2:
469               utmp = extract_unsigned_integer (insn_ptr, 2, byte_order);
470               fs->pc += utmp * fs->code_align;
471               insn_ptr += 2;
472               break;
473             case DW_CFA_advance_loc4:
474               utmp = extract_unsigned_integer (insn_ptr, 4, byte_order);
475               fs->pc += utmp * fs->code_align;
476               insn_ptr += 4;
477               break;
478
479             case DW_CFA_offset_extended:
480               insn_ptr = safe_read_uleb128 (insn_ptr, insn_end, &reg);
481               reg = dwarf2_frame_adjust_regnum (gdbarch, reg, eh_frame_p);
482               insn_ptr = safe_read_uleb128 (insn_ptr, insn_end, &utmp);
483               offset = utmp * fs->data_align;
484               dwarf2_frame_state_alloc_regs (&fs->regs, reg + 1);
485               fs->regs.reg[reg].how = DWARF2_FRAME_REG_SAVED_OFFSET;
486               fs->regs.reg[reg].loc.offset = offset;
487               break;
488
489             case DW_CFA_restore_extended:
490               insn_ptr = safe_read_uleb128 (insn_ptr, insn_end, &reg);
491               dwarf2_restore_rule (gdbarch, reg, fs, eh_frame_p);
492               break;
493
494             case DW_CFA_undefined:
495               insn_ptr = safe_read_uleb128 (insn_ptr, insn_end, &reg);
496               reg = dwarf2_frame_adjust_regnum (gdbarch, reg, eh_frame_p);
497               dwarf2_frame_state_alloc_regs (&fs->regs, reg + 1);
498               fs->regs.reg[reg].how = DWARF2_FRAME_REG_UNDEFINED;
499               break;
500
501             case DW_CFA_same_value:
502               insn_ptr = safe_read_uleb128 (insn_ptr, insn_end, &reg);
503               reg = dwarf2_frame_adjust_regnum (gdbarch, reg, eh_frame_p);
504               dwarf2_frame_state_alloc_regs (&fs->regs, reg + 1);
505               fs->regs.reg[reg].how = DWARF2_FRAME_REG_SAME_VALUE;
506               break;
507
508             case DW_CFA_register:
509               insn_ptr = safe_read_uleb128 (insn_ptr, insn_end, &reg);
510               reg = dwarf2_frame_adjust_regnum (gdbarch, reg, eh_frame_p);
511               insn_ptr = safe_read_uleb128 (insn_ptr, insn_end, &utmp);
512               utmp = dwarf2_frame_adjust_regnum (gdbarch, utmp, eh_frame_p);
513               dwarf2_frame_state_alloc_regs (&fs->regs, reg + 1);
514               fs->regs.reg[reg].how = DWARF2_FRAME_REG_SAVED_REG;
515               fs->regs.reg[reg].loc.reg = utmp;
516               break;
517
518             case DW_CFA_remember_state:
519               {
520                 struct dwarf2_frame_state_reg_info *new_rs;
521
522                 new_rs = XNEW (struct dwarf2_frame_state_reg_info);
523                 *new_rs = fs->regs;
524                 fs->regs.reg = dwarf2_frame_state_copy_regs (&fs->regs);
525                 fs->regs.prev = new_rs;
526               }
527               break;
528
529             case DW_CFA_restore_state:
530               {
531                 struct dwarf2_frame_state_reg_info *old_rs = fs->regs.prev;
532
533                 if (old_rs == NULL)
534                   {
535                     complaint (&symfile_complaints, _("\
536 bad CFI data; mismatched DW_CFA_restore_state at %s"),
537                                paddress (gdbarch, fs->pc));
538                   }
539                 else
540                   {
541                     xfree (fs->regs.reg);
542                     fs->regs = *old_rs;
543                     xfree (old_rs);
544                   }
545               }
546               break;
547
548             case DW_CFA_def_cfa:
549               insn_ptr = safe_read_uleb128 (insn_ptr, insn_end, &reg);
550               fs->regs.cfa_reg = reg;
551               insn_ptr = safe_read_uleb128 (insn_ptr, insn_end, &utmp);
552
553               if (fs->armcc_cfa_offsets_sf)
554                 utmp *= fs->data_align;
555
556               fs->regs.cfa_offset = utmp;
557               fs->regs.cfa_how = CFA_REG_OFFSET;
558               break;
559
560             case DW_CFA_def_cfa_register:
561               insn_ptr = safe_read_uleb128 (insn_ptr, insn_end, &reg);
562               fs->regs.cfa_reg = dwarf2_frame_adjust_regnum (gdbarch, reg,
563                                                              eh_frame_p);
564               fs->regs.cfa_how = CFA_REG_OFFSET;
565               break;
566
567             case DW_CFA_def_cfa_offset:
568               insn_ptr = safe_read_uleb128 (insn_ptr, insn_end, &utmp);
569
570               if (fs->armcc_cfa_offsets_sf)
571                 utmp *= fs->data_align;
572
573               fs->regs.cfa_offset = utmp;
574               /* cfa_how deliberately not set.  */
575               break;
576
577             case DW_CFA_nop:
578               break;
579
580             case DW_CFA_def_cfa_expression:
581               insn_ptr = safe_read_uleb128 (insn_ptr, insn_end, &utmp);
582               fs->regs.cfa_exp_len = utmp;
583               fs->regs.cfa_exp = insn_ptr;
584               fs->regs.cfa_how = CFA_EXP;
585               insn_ptr += fs->regs.cfa_exp_len;
586               break;
587
588             case DW_CFA_expression:
589               insn_ptr = safe_read_uleb128 (insn_ptr, insn_end, &reg);
590               reg = dwarf2_frame_adjust_regnum (gdbarch, reg, eh_frame_p);
591               dwarf2_frame_state_alloc_regs (&fs->regs, reg + 1);
592               insn_ptr = safe_read_uleb128 (insn_ptr, insn_end, &utmp);
593               fs->regs.reg[reg].loc.exp = insn_ptr;
594               fs->regs.reg[reg].exp_len = utmp;
595               fs->regs.reg[reg].how = DWARF2_FRAME_REG_SAVED_EXP;
596               insn_ptr += utmp;
597               break;
598
599             case DW_CFA_offset_extended_sf:
600               insn_ptr = safe_read_uleb128 (insn_ptr, insn_end, &reg);
601               reg = dwarf2_frame_adjust_regnum (gdbarch, reg, eh_frame_p);
602               insn_ptr = safe_read_sleb128 (insn_ptr, insn_end, &offset);
603               offset *= fs->data_align;
604               dwarf2_frame_state_alloc_regs (&fs->regs, reg + 1);
605               fs->regs.reg[reg].how = DWARF2_FRAME_REG_SAVED_OFFSET;
606               fs->regs.reg[reg].loc.offset = offset;
607               break;
608
609             case DW_CFA_val_offset:
610               insn_ptr = safe_read_uleb128 (insn_ptr, insn_end, &reg);
611               dwarf2_frame_state_alloc_regs (&fs->regs, reg + 1);
612               insn_ptr = safe_read_uleb128 (insn_ptr, insn_end, &utmp);
613               offset = utmp * fs->data_align;
614               fs->regs.reg[reg].how = DWARF2_FRAME_REG_SAVED_VAL_OFFSET;
615               fs->regs.reg[reg].loc.offset = offset;
616               break;
617
618             case DW_CFA_val_offset_sf:
619               insn_ptr = safe_read_uleb128 (insn_ptr, insn_end, &reg);
620               dwarf2_frame_state_alloc_regs (&fs->regs, reg + 1);
621               insn_ptr = safe_read_sleb128 (insn_ptr, insn_end, &offset);
622               offset *= fs->data_align;
623               fs->regs.reg[reg].how = DWARF2_FRAME_REG_SAVED_VAL_OFFSET;
624               fs->regs.reg[reg].loc.offset = offset;
625               break;
626
627             case DW_CFA_val_expression:
628               insn_ptr = safe_read_uleb128 (insn_ptr, insn_end, &reg);
629               dwarf2_frame_state_alloc_regs (&fs->regs, reg + 1);
630               insn_ptr = safe_read_uleb128 (insn_ptr, insn_end, &utmp);
631               fs->regs.reg[reg].loc.exp = insn_ptr;
632               fs->regs.reg[reg].exp_len = utmp;
633               fs->regs.reg[reg].how = DWARF2_FRAME_REG_SAVED_VAL_EXP;
634               insn_ptr += utmp;
635               break;
636
637             case DW_CFA_def_cfa_sf:
638               insn_ptr = safe_read_uleb128 (insn_ptr, insn_end, &reg);
639               fs->regs.cfa_reg = dwarf2_frame_adjust_regnum (gdbarch, reg,
640                                                              eh_frame_p);
641               insn_ptr = safe_read_sleb128 (insn_ptr, insn_end, &offset);
642               fs->regs.cfa_offset = offset * fs->data_align;
643               fs->regs.cfa_how = CFA_REG_OFFSET;
644               break;
645
646             case DW_CFA_def_cfa_offset_sf:
647               insn_ptr = safe_read_sleb128 (insn_ptr, insn_end, &offset);
648               fs->regs.cfa_offset = offset * fs->data_align;
649               /* cfa_how deliberately not set.  */
650               break;
651
652             case DW_CFA_GNU_window_save:
653               /* This is SPARC-specific code, and contains hard-coded
654                  constants for the register numbering scheme used by
655                  GCC.  Rather than having a architecture-specific
656                  operation that's only ever used by a single
657                  architecture, we provide the implementation here.
658                  Incidentally that's what GCC does too in its
659                  unwinder.  */
660               {
661                 int size = register_size (gdbarch, 0);
662
663                 dwarf2_frame_state_alloc_regs (&fs->regs, 32);
664                 for (reg = 8; reg < 16; reg++)
665                   {
666                     fs->regs.reg[reg].how = DWARF2_FRAME_REG_SAVED_REG;
667                     fs->regs.reg[reg].loc.reg = reg + 16;
668                   }
669                 for (reg = 16; reg < 32; reg++)
670                   {
671                     fs->regs.reg[reg].how = DWARF2_FRAME_REG_SAVED_OFFSET;
672                     fs->regs.reg[reg].loc.offset = (reg - 16) * size;
673                   }
674               }
675               break;
676
677             case DW_CFA_GNU_args_size:
678               /* Ignored.  */
679               insn_ptr = safe_read_uleb128 (insn_ptr, insn_end, &utmp);
680               break;
681
682             case DW_CFA_GNU_negative_offset_extended:
683               insn_ptr = safe_read_uleb128 (insn_ptr, insn_end, &reg);
684               reg = dwarf2_frame_adjust_regnum (gdbarch, reg, eh_frame_p);
685               insn_ptr = safe_read_uleb128 (insn_ptr, insn_end, &utmp);
686               offset = utmp * fs->data_align;
687               dwarf2_frame_state_alloc_regs (&fs->regs, reg + 1);
688               fs->regs.reg[reg].how = DWARF2_FRAME_REG_SAVED_OFFSET;
689               fs->regs.reg[reg].loc.offset = -offset;
690               break;
691
692             default:
693               internal_error (__FILE__, __LINE__,
694                               _("Unknown CFI encountered."));
695             }
696         }
697     }
698
699   if (fs->initial.reg == NULL)
700     {
701       /* Don't allow remember/restore between CIE and FDE programs.  */
702       dwarf2_frame_state_free_regs (fs->regs.prev);
703       fs->regs.prev = NULL;
704     }
705
706   return insn_ptr;
707 }
708 \f
709
710 /* Architecture-specific operations.  */
711
712 /* Per-architecture data key.  */
713 static struct gdbarch_data *dwarf2_frame_data;
714
715 struct dwarf2_frame_ops
716 {
717   /* Pre-initialize the register state REG for register REGNUM.  */
718   void (*init_reg) (struct gdbarch *, int, struct dwarf2_frame_state_reg *,
719                     struct frame_info *);
720
721   /* Check whether the THIS_FRAME is a signal trampoline.  */
722   int (*signal_frame_p) (struct gdbarch *, struct frame_info *);
723
724   /* Convert .eh_frame register number to DWARF register number, or
725      adjust .debug_frame register number.  */
726   int (*adjust_regnum) (struct gdbarch *, int, int);
727 };
728
729 /* Default architecture-specific register state initialization
730    function.  */
731
732 static void
733 dwarf2_frame_default_init_reg (struct gdbarch *gdbarch, int regnum,
734                                struct dwarf2_frame_state_reg *reg,
735                                struct frame_info *this_frame)
736 {
737   /* If we have a register that acts as a program counter, mark it as
738      a destination for the return address.  If we have a register that
739      serves as the stack pointer, arrange for it to be filled with the
740      call frame address (CFA).  The other registers are marked as
741      unspecified.
742
743      We copy the return address to the program counter, since many
744      parts in GDB assume that it is possible to get the return address
745      by unwinding the program counter register.  However, on ISA's
746      with a dedicated return address register, the CFI usually only
747      contains information to unwind that return address register.
748
749      The reason we're treating the stack pointer special here is
750      because in many cases GCC doesn't emit CFI for the stack pointer
751      and implicitly assumes that it is equal to the CFA.  This makes
752      some sense since the DWARF specification (version 3, draft 8,
753      p. 102) says that:
754
755      "Typically, the CFA is defined to be the value of the stack
756      pointer at the call site in the previous frame (which may be
757      different from its value on entry to the current frame)."
758
759      However, this isn't true for all platforms supported by GCC
760      (e.g. IBM S/390 and zSeries).  Those architectures should provide
761      their own architecture-specific initialization function.  */
762
763   if (regnum == gdbarch_pc_regnum (gdbarch))
764     reg->how = DWARF2_FRAME_REG_RA;
765   else if (regnum == gdbarch_sp_regnum (gdbarch))
766     reg->how = DWARF2_FRAME_REG_CFA;
767 }
768
769 /* Return a default for the architecture-specific operations.  */
770
771 static void *
772 dwarf2_frame_init (struct obstack *obstack)
773 {
774   struct dwarf2_frame_ops *ops;
775   
776   ops = OBSTACK_ZALLOC (obstack, struct dwarf2_frame_ops);
777   ops->init_reg = dwarf2_frame_default_init_reg;
778   return ops;
779 }
780
781 /* Set the architecture-specific register state initialization
782    function for GDBARCH to INIT_REG.  */
783
784 void
785 dwarf2_frame_set_init_reg (struct gdbarch *gdbarch,
786                            void (*init_reg) (struct gdbarch *, int,
787                                              struct dwarf2_frame_state_reg *,
788                                              struct frame_info *))
789 {
790   struct dwarf2_frame_ops *ops = gdbarch_data (gdbarch, dwarf2_frame_data);
791
792   ops->init_reg = init_reg;
793 }
794
795 /* Pre-initialize the register state REG for register REGNUM.  */
796
797 static void
798 dwarf2_frame_init_reg (struct gdbarch *gdbarch, int regnum,
799                        struct dwarf2_frame_state_reg *reg,
800                        struct frame_info *this_frame)
801 {
802   struct dwarf2_frame_ops *ops = gdbarch_data (gdbarch, dwarf2_frame_data);
803
804   ops->init_reg (gdbarch, regnum, reg, this_frame);
805 }
806
807 /* Set the architecture-specific signal trampoline recognition
808    function for GDBARCH to SIGNAL_FRAME_P.  */
809
810 void
811 dwarf2_frame_set_signal_frame_p (struct gdbarch *gdbarch,
812                                  int (*signal_frame_p) (struct gdbarch *,
813                                                         struct frame_info *))
814 {
815   struct dwarf2_frame_ops *ops = gdbarch_data (gdbarch, dwarf2_frame_data);
816
817   ops->signal_frame_p = signal_frame_p;
818 }
819
820 /* Query the architecture-specific signal frame recognizer for
821    THIS_FRAME.  */
822
823 static int
824 dwarf2_frame_signal_frame_p (struct gdbarch *gdbarch,
825                              struct frame_info *this_frame)
826 {
827   struct dwarf2_frame_ops *ops = gdbarch_data (gdbarch, dwarf2_frame_data);
828
829   if (ops->signal_frame_p == NULL)
830     return 0;
831   return ops->signal_frame_p (gdbarch, this_frame);
832 }
833
834 /* Set the architecture-specific adjustment of .eh_frame and .debug_frame
835    register numbers.  */
836
837 void
838 dwarf2_frame_set_adjust_regnum (struct gdbarch *gdbarch,
839                                 int (*adjust_regnum) (struct gdbarch *,
840                                                       int, int))
841 {
842   struct dwarf2_frame_ops *ops = gdbarch_data (gdbarch, dwarf2_frame_data);
843
844   ops->adjust_regnum = adjust_regnum;
845 }
846
847 /* Translate a .eh_frame register to DWARF register, or adjust a .debug_frame
848    register.  */
849
850 static int
851 dwarf2_frame_adjust_regnum (struct gdbarch *gdbarch,
852                             int regnum, int eh_frame_p)
853 {
854   struct dwarf2_frame_ops *ops = gdbarch_data (gdbarch, dwarf2_frame_data);
855
856   if (ops->adjust_regnum == NULL)
857     return regnum;
858   return ops->adjust_regnum (gdbarch, regnum, eh_frame_p);
859 }
860
861 static void
862 dwarf2_frame_find_quirks (struct dwarf2_frame_state *fs,
863                           struct dwarf2_fde *fde)
864 {
865   struct symtab *s;
866
867   s = find_pc_symtab (fs->pc);
868   if (s == NULL)
869     return;
870
871   if (producer_is_realview (s->producer))
872     {
873       if (fde->cie->version == 1)
874         fs->armcc_cfa_offsets_sf = 1;
875
876       if (fde->cie->version == 1)
877         fs->armcc_cfa_offsets_reversed = 1;
878
879       /* The reversed offset problem is present in some compilers
880          using DWARF3, but it was eventually fixed.  Check the ARM
881          defined augmentations, which are in the format "armcc" followed
882          by a list of one-character options.  The "+" option means
883          this problem is fixed (no quirk needed).  If the armcc
884          augmentation is missing, the quirk is needed.  */
885       if (fde->cie->version == 3
886           && (strncmp (fde->cie->augmentation, "armcc", 5) != 0
887               || strchr (fde->cie->augmentation + 5, '+') == NULL))
888         fs->armcc_cfa_offsets_reversed = 1;
889
890       return;
891     }
892 }
893 \f
894
895 void
896 dwarf2_compile_cfa_to_ax (struct agent_expr *expr, struct axs_value *loc,
897                           struct gdbarch *gdbarch,
898                           CORE_ADDR pc,
899                           struct dwarf2_per_cu_data *data)
900 {
901   struct dwarf2_fde *fde;
902   CORE_ADDR text_offset;
903   struct dwarf2_frame_state fs;
904   int addr_size;
905
906   memset (&fs, 0, sizeof (struct dwarf2_frame_state));
907
908   fs.pc = pc;
909
910   /* Find the correct FDE.  */
911   fde = dwarf2_frame_find_fde (&fs.pc, &text_offset);
912   if (fde == NULL)
913     error (_("Could not compute CFA; needed to translate this expression"));
914
915   /* Extract any interesting information from the CIE.  */
916   fs.data_align = fde->cie->data_alignment_factor;
917   fs.code_align = fde->cie->code_alignment_factor;
918   fs.retaddr_column = fde->cie->return_address_register;
919   addr_size = fde->cie->addr_size;
920
921   /* Check for "quirks" - known bugs in producers.  */
922   dwarf2_frame_find_quirks (&fs, fde);
923
924   /* First decode all the insns in the CIE.  */
925   execute_cfa_program (fde, fde->cie->initial_instructions,
926                        fde->cie->end, gdbarch, pc, &fs);
927
928   /* Save the initialized register set.  */
929   fs.initial = fs.regs;
930   fs.initial.reg = dwarf2_frame_state_copy_regs (&fs.regs);
931
932   /* Then decode the insns in the FDE up to our target PC.  */
933   execute_cfa_program (fde, fde->instructions, fde->end, gdbarch, pc, &fs);
934
935   /* Calculate the CFA.  */
936   switch (fs.regs.cfa_how)
937     {
938     case CFA_REG_OFFSET:
939       {
940         int regnum = gdbarch_dwarf2_reg_to_regnum (gdbarch, fs.regs.cfa_reg);
941
942         if (regnum == -1)
943           error (_("Unable to access DWARF register number %d"),
944                  (int) fs.regs.cfa_reg); /* FIXME */
945         ax_reg (expr, regnum);
946
947         if (fs.regs.cfa_offset != 0)
948           {
949             if (fs.armcc_cfa_offsets_reversed)
950               ax_const_l (expr, -fs.regs.cfa_offset);
951             else
952               ax_const_l (expr, fs.regs.cfa_offset);
953             ax_simple (expr, aop_add);
954           }
955       }
956       break;
957
958     case CFA_EXP:
959       ax_const_l (expr, text_offset);
960       dwarf2_compile_expr_to_ax (expr, loc, gdbarch, addr_size,
961                                  fs.regs.cfa_exp,
962                                  fs.regs.cfa_exp + fs.regs.cfa_exp_len,
963                                  data);
964       break;
965
966     default:
967       internal_error (__FILE__, __LINE__, _("Unknown CFA rule."));
968     }
969 }
970
971 \f
972 struct dwarf2_frame_cache
973 {
974   /* DWARF Call Frame Address.  */
975   CORE_ADDR cfa;
976
977   /* Set if the return address column was marked as unavailable
978      (required non-collected memory or registers to compute).  */
979   int unavailable_retaddr;
980
981   /* Set if the return address column was marked as undefined.  */
982   int undefined_retaddr;
983
984   /* Saved registers, indexed by GDB register number, not by DWARF
985      register number.  */
986   struct dwarf2_frame_state_reg *reg;
987
988   /* Return address register.  */
989   struct dwarf2_frame_state_reg retaddr_reg;
990
991   /* Target address size in bytes.  */
992   int addr_size;
993
994   /* The .text offset.  */
995   CORE_ADDR text_offset;
996
997   /* True if we already checked whether this frame is the bottom frame
998      of a virtual tail call frame chain.  */
999   int checked_tailcall_bottom;
1000
1001   /* If not NULL then this frame is the bottom frame of a TAILCALL_FRAME
1002      sequence.  If NULL then it is a normal case with no TAILCALL_FRAME
1003      involved.  Non-bottom frames of a virtual tail call frames chain use
1004      dwarf2_tailcall_frame_unwind unwinder so this field does not apply for
1005      them.  */
1006   void *tailcall_cache;
1007
1008   /* The number of bytes to subtract from TAILCALL_FRAME frames frame
1009      base to get the SP, to simulate the return address pushed on the
1010      stack.  */
1011   LONGEST entry_cfa_sp_offset;
1012   int entry_cfa_sp_offset_p;
1013 };
1014
1015 /* A cleanup that sets a pointer to NULL.  */
1016
1017 static void
1018 clear_pointer_cleanup (void *arg)
1019 {
1020   void **ptr = arg;
1021
1022   *ptr = NULL;
1023 }
1024
1025 static struct dwarf2_frame_cache *
1026 dwarf2_frame_cache (struct frame_info *this_frame, void **this_cache)
1027 {
1028   struct cleanup *reset_cache_cleanup, *old_chain;
1029   struct gdbarch *gdbarch = get_frame_arch (this_frame);
1030   const int num_regs = gdbarch_num_regs (gdbarch)
1031                        + gdbarch_num_pseudo_regs (gdbarch);
1032   struct dwarf2_frame_cache *cache;
1033   struct dwarf2_frame_state *fs;
1034   struct dwarf2_fde *fde;
1035   volatile struct gdb_exception ex;
1036   CORE_ADDR entry_pc;
1037   const gdb_byte *instr;
1038
1039   if (*this_cache)
1040     return *this_cache;
1041
1042   /* Allocate a new cache.  */
1043   cache = FRAME_OBSTACK_ZALLOC (struct dwarf2_frame_cache);
1044   cache->reg = FRAME_OBSTACK_CALLOC (num_regs, struct dwarf2_frame_state_reg);
1045   *this_cache = cache;
1046   reset_cache_cleanup = make_cleanup (clear_pointer_cleanup, this_cache);
1047
1048   /* Allocate and initialize the frame state.  */
1049   fs = XCNEW (struct dwarf2_frame_state);
1050   old_chain = make_cleanup (dwarf2_frame_state_free, fs);
1051
1052   /* Unwind the PC.
1053
1054      Note that if the next frame is never supposed to return (i.e. a call
1055      to abort), the compiler might optimize away the instruction at
1056      its return address.  As a result the return address will
1057      point at some random instruction, and the CFI for that
1058      instruction is probably worthless to us.  GCC's unwinder solves
1059      this problem by substracting 1 from the return address to get an
1060      address in the middle of a presumed call instruction (or the
1061      instruction in the associated delay slot).  This should only be
1062      done for "normal" frames and not for resume-type frames (signal
1063      handlers, sentinel frames, dummy frames).  The function
1064      get_frame_address_in_block does just this.  It's not clear how
1065      reliable the method is though; there is the potential for the
1066      register state pre-call being different to that on return.  */
1067   fs->pc = get_frame_address_in_block (this_frame);
1068
1069   /* Find the correct FDE.  */
1070   fde = dwarf2_frame_find_fde (&fs->pc, &cache->text_offset);
1071   gdb_assert (fde != NULL);
1072
1073   /* Extract any interesting information from the CIE.  */
1074   fs->data_align = fde->cie->data_alignment_factor;
1075   fs->code_align = fde->cie->code_alignment_factor;
1076   fs->retaddr_column = fde->cie->return_address_register;
1077   cache->addr_size = fde->cie->addr_size;
1078
1079   /* Check for "quirks" - known bugs in producers.  */
1080   dwarf2_frame_find_quirks (fs, fde);
1081
1082   /* First decode all the insns in the CIE.  */
1083   execute_cfa_program (fde, fde->cie->initial_instructions,
1084                        fde->cie->end, gdbarch,
1085                        get_frame_address_in_block (this_frame), fs);
1086
1087   /* Save the initialized register set.  */
1088   fs->initial = fs->regs;
1089   fs->initial.reg = dwarf2_frame_state_copy_regs (&fs->regs);
1090
1091   if (get_frame_func_if_available (this_frame, &entry_pc))
1092     {
1093       /* Decode the insns in the FDE up to the entry PC.  */
1094       instr = execute_cfa_program (fde, fde->instructions, fde->end, gdbarch,
1095                                    entry_pc, fs);
1096
1097       if (fs->regs.cfa_how == CFA_REG_OFFSET
1098           && (gdbarch_dwarf2_reg_to_regnum (gdbarch, fs->regs.cfa_reg)
1099               == gdbarch_sp_regnum (gdbarch)))
1100         {
1101           cache->entry_cfa_sp_offset = fs->regs.cfa_offset;
1102           cache->entry_cfa_sp_offset_p = 1;
1103         }
1104     }
1105   else
1106     instr = fde->instructions;
1107
1108   /* Then decode the insns in the FDE up to our target PC.  */
1109   execute_cfa_program (fde, instr, fde->end, gdbarch,
1110                        get_frame_address_in_block (this_frame), fs);
1111
1112   TRY_CATCH (ex, RETURN_MASK_ERROR)
1113     {
1114       /* Calculate the CFA.  */
1115       switch (fs->regs.cfa_how)
1116         {
1117         case CFA_REG_OFFSET:
1118           cache->cfa = read_addr_from_reg (this_frame, fs->regs.cfa_reg);
1119           if (fs->armcc_cfa_offsets_reversed)
1120             cache->cfa -= fs->regs.cfa_offset;
1121           else
1122             cache->cfa += fs->regs.cfa_offset;
1123           break;
1124
1125         case CFA_EXP:
1126           cache->cfa =
1127             execute_stack_op (fs->regs.cfa_exp, fs->regs.cfa_exp_len,
1128                               cache->addr_size, cache->text_offset,
1129                               this_frame, 0, 0);
1130           break;
1131
1132         default:
1133           internal_error (__FILE__, __LINE__, _("Unknown CFA rule."));
1134         }
1135     }
1136   if (ex.reason < 0)
1137     {
1138       if (ex.error == NOT_AVAILABLE_ERROR)
1139         {
1140           cache->unavailable_retaddr = 1;
1141           do_cleanups (old_chain);
1142           discard_cleanups (reset_cache_cleanup);
1143           return cache;
1144         }
1145
1146       throw_exception (ex);
1147     }
1148
1149   /* Initialize the register state.  */
1150   {
1151     int regnum;
1152
1153     for (regnum = 0; regnum < num_regs; regnum++)
1154       dwarf2_frame_init_reg (gdbarch, regnum, &cache->reg[regnum], this_frame);
1155   }
1156
1157   /* Go through the DWARF2 CFI generated table and save its register
1158      location information in the cache.  Note that we don't skip the
1159      return address column; it's perfectly all right for it to
1160      correspond to a real register.  If it doesn't correspond to a
1161      real register, or if we shouldn't treat it as such,
1162      gdbarch_dwarf2_reg_to_regnum should be defined to return a number outside
1163      the range [0, gdbarch_num_regs).  */
1164   {
1165     int column;         /* CFI speak for "register number".  */
1166
1167     for (column = 0; column < fs->regs.num_regs; column++)
1168       {
1169         /* Use the GDB register number as the destination index.  */
1170         int regnum = gdbarch_dwarf2_reg_to_regnum (gdbarch, column);
1171
1172         /* If there's no corresponding GDB register, ignore it.  */
1173         if (regnum < 0 || regnum >= num_regs)
1174           continue;
1175
1176         /* NOTE: cagney/2003-09-05: CFI should specify the disposition
1177            of all debug info registers.  If it doesn't, complain (but
1178            not too loudly).  It turns out that GCC assumes that an
1179            unspecified register implies "same value" when CFI (draft
1180            7) specifies nothing at all.  Such a register could equally
1181            be interpreted as "undefined".  Also note that this check
1182            isn't sufficient; it only checks that all registers in the
1183            range [0 .. max column] are specified, and won't detect
1184            problems when a debug info register falls outside of the
1185            table.  We need a way of iterating through all the valid
1186            DWARF2 register numbers.  */
1187         if (fs->regs.reg[column].how == DWARF2_FRAME_REG_UNSPECIFIED)
1188           {
1189             if (cache->reg[regnum].how == DWARF2_FRAME_REG_UNSPECIFIED)
1190               complaint (&symfile_complaints, _("\
1191 incomplete CFI data; unspecified registers (e.g., %s) at %s"),
1192                          gdbarch_register_name (gdbarch, regnum),
1193                          paddress (gdbarch, fs->pc));
1194           }
1195         else
1196           cache->reg[regnum] = fs->regs.reg[column];
1197       }
1198   }
1199
1200   /* Eliminate any DWARF2_FRAME_REG_RA rules, and save the information
1201      we need for evaluating DWARF2_FRAME_REG_RA_OFFSET rules.  */
1202   {
1203     int regnum;
1204
1205     for (regnum = 0; regnum < num_regs; regnum++)
1206       {
1207         if (cache->reg[regnum].how == DWARF2_FRAME_REG_RA
1208             || cache->reg[regnum].how == DWARF2_FRAME_REG_RA_OFFSET)
1209           {
1210             struct dwarf2_frame_state_reg *retaddr_reg =
1211               &fs->regs.reg[fs->retaddr_column];
1212
1213             /* It seems rather bizarre to specify an "empty" column as
1214                the return adress column.  However, this is exactly
1215                what GCC does on some targets.  It turns out that GCC
1216                assumes that the return address can be found in the
1217                register corresponding to the return address column.
1218                Incidentally, that's how we should treat a return
1219                address column specifying "same value" too.  */
1220             if (fs->retaddr_column < fs->regs.num_regs
1221                 && retaddr_reg->how != DWARF2_FRAME_REG_UNSPECIFIED
1222                 && retaddr_reg->how != DWARF2_FRAME_REG_SAME_VALUE)
1223               {
1224                 if (cache->reg[regnum].how == DWARF2_FRAME_REG_RA)
1225                   cache->reg[regnum] = *retaddr_reg;
1226                 else
1227                   cache->retaddr_reg = *retaddr_reg;
1228               }
1229             else
1230               {
1231                 if (cache->reg[regnum].how == DWARF2_FRAME_REG_RA)
1232                   {
1233                     cache->reg[regnum].loc.reg = fs->retaddr_column;
1234                     cache->reg[regnum].how = DWARF2_FRAME_REG_SAVED_REG;
1235                   }
1236                 else
1237                   {
1238                     cache->retaddr_reg.loc.reg = fs->retaddr_column;
1239                     cache->retaddr_reg.how = DWARF2_FRAME_REG_SAVED_REG;
1240                   }
1241               }
1242           }
1243       }
1244   }
1245
1246   if (fs->retaddr_column < fs->regs.num_regs
1247       && fs->regs.reg[fs->retaddr_column].how == DWARF2_FRAME_REG_UNDEFINED)
1248     cache->undefined_retaddr = 1;
1249
1250   do_cleanups (old_chain);
1251   discard_cleanups (reset_cache_cleanup);
1252   return cache;
1253 }
1254
1255 static enum unwind_stop_reason
1256 dwarf2_frame_unwind_stop_reason (struct frame_info *this_frame,
1257                                  void **this_cache)
1258 {
1259   struct dwarf2_frame_cache *cache
1260     = dwarf2_frame_cache (this_frame, this_cache);
1261
1262   if (cache->unavailable_retaddr)
1263     return UNWIND_UNAVAILABLE;
1264
1265   if (cache->undefined_retaddr)
1266     return UNWIND_OUTERMOST;
1267
1268   return UNWIND_NO_REASON;
1269 }
1270
1271 static void
1272 dwarf2_frame_this_id (struct frame_info *this_frame, void **this_cache,
1273                       struct frame_id *this_id)
1274 {
1275   struct dwarf2_frame_cache *cache =
1276     dwarf2_frame_cache (this_frame, this_cache);
1277
1278   if (cache->unavailable_retaddr)
1279     (*this_id) = frame_id_build_unavailable_stack (get_frame_func (this_frame));
1280   else if (cache->undefined_retaddr)
1281     return;
1282   else
1283     (*this_id) = frame_id_build (cache->cfa, get_frame_func (this_frame));
1284 }
1285
1286 static struct value *
1287 dwarf2_frame_prev_register (struct frame_info *this_frame, void **this_cache,
1288                             int regnum)
1289 {
1290   struct gdbarch *gdbarch = get_frame_arch (this_frame);
1291   struct dwarf2_frame_cache *cache =
1292     dwarf2_frame_cache (this_frame, this_cache);
1293   CORE_ADDR addr;
1294   int realnum;
1295
1296   /* Check whether THIS_FRAME is the bottom frame of a virtual tail
1297      call frame chain.  */
1298   if (!cache->checked_tailcall_bottom)
1299     {
1300       cache->checked_tailcall_bottom = 1;
1301       dwarf2_tailcall_sniffer_first (this_frame, &cache->tailcall_cache,
1302                                      (cache->entry_cfa_sp_offset_p
1303                                       ? &cache->entry_cfa_sp_offset : NULL));
1304     }
1305
1306   /* Non-bottom frames of a virtual tail call frames chain use
1307      dwarf2_tailcall_frame_unwind unwinder so this code does not apply for
1308      them.  If dwarf2_tailcall_prev_register_first does not have specific value
1309      unwind the register, tail call frames are assumed to have the register set
1310      of the top caller.  */
1311   if (cache->tailcall_cache)
1312     {
1313       struct value *val;
1314       
1315       val = dwarf2_tailcall_prev_register_first (this_frame,
1316                                                  &cache->tailcall_cache,
1317                                                  regnum);
1318       if (val)
1319         return val;
1320     }
1321
1322   switch (cache->reg[regnum].how)
1323     {
1324     case DWARF2_FRAME_REG_UNDEFINED:
1325       /* If CFI explicitly specified that the value isn't defined,
1326          mark it as optimized away; the value isn't available.  */
1327       return frame_unwind_got_optimized (this_frame, regnum);
1328
1329     case DWARF2_FRAME_REG_SAVED_OFFSET:
1330       addr = cache->cfa + cache->reg[regnum].loc.offset;
1331       return frame_unwind_got_memory (this_frame, regnum, addr);
1332
1333     case DWARF2_FRAME_REG_SAVED_REG:
1334       realnum
1335         = gdbarch_dwarf2_reg_to_regnum (gdbarch, cache->reg[regnum].loc.reg);
1336       return frame_unwind_got_register (this_frame, regnum, realnum);
1337
1338     case DWARF2_FRAME_REG_SAVED_EXP:
1339       addr = execute_stack_op (cache->reg[regnum].loc.exp,
1340                                cache->reg[regnum].exp_len,
1341                                cache->addr_size, cache->text_offset,
1342                                this_frame, cache->cfa, 1);
1343       return frame_unwind_got_memory (this_frame, regnum, addr);
1344
1345     case DWARF2_FRAME_REG_SAVED_VAL_OFFSET:
1346       addr = cache->cfa + cache->reg[regnum].loc.offset;
1347       return frame_unwind_got_constant (this_frame, regnum, addr);
1348
1349     case DWARF2_FRAME_REG_SAVED_VAL_EXP:
1350       addr = execute_stack_op (cache->reg[regnum].loc.exp,
1351                                cache->reg[regnum].exp_len,
1352                                cache->addr_size, cache->text_offset,
1353                                this_frame, cache->cfa, 1);
1354       return frame_unwind_got_constant (this_frame, regnum, addr);
1355
1356     case DWARF2_FRAME_REG_UNSPECIFIED:
1357       /* GCC, in its infinite wisdom decided to not provide unwind
1358          information for registers that are "same value".  Since
1359          DWARF2 (3 draft 7) doesn't define such behavior, said
1360          registers are actually undefined (which is different to CFI
1361          "undefined").  Code above issues a complaint about this.
1362          Here just fudge the books, assume GCC, and that the value is
1363          more inner on the stack.  */
1364       return frame_unwind_got_register (this_frame, regnum, regnum);
1365
1366     case DWARF2_FRAME_REG_SAME_VALUE:
1367       return frame_unwind_got_register (this_frame, regnum, regnum);
1368
1369     case DWARF2_FRAME_REG_CFA:
1370       return frame_unwind_got_address (this_frame, regnum, cache->cfa);
1371
1372     case DWARF2_FRAME_REG_CFA_OFFSET:
1373       addr = cache->cfa + cache->reg[regnum].loc.offset;
1374       return frame_unwind_got_address (this_frame, regnum, addr);
1375
1376     case DWARF2_FRAME_REG_RA_OFFSET:
1377       addr = cache->reg[regnum].loc.offset;
1378       regnum = gdbarch_dwarf2_reg_to_regnum
1379         (gdbarch, cache->retaddr_reg.loc.reg);
1380       addr += get_frame_register_unsigned (this_frame, regnum);
1381       return frame_unwind_got_address (this_frame, regnum, addr);
1382
1383     case DWARF2_FRAME_REG_FN:
1384       return cache->reg[regnum].loc.fn (this_frame, this_cache, regnum);
1385
1386     default:
1387       internal_error (__FILE__, __LINE__, _("Unknown register rule."));
1388     }
1389 }
1390
1391 /* Proxy for tailcall_frame_dealloc_cache for bottom frame of a virtual tail
1392    call frames chain.  */
1393
1394 static void
1395 dwarf2_frame_dealloc_cache (struct frame_info *self, void *this_cache)
1396 {
1397   struct dwarf2_frame_cache *cache = dwarf2_frame_cache (self, &this_cache);
1398
1399   if (cache->tailcall_cache)
1400     dwarf2_tailcall_frame_unwind.dealloc_cache (self, cache->tailcall_cache);
1401 }
1402
1403 static int
1404 dwarf2_frame_sniffer (const struct frame_unwind *self,
1405                       struct frame_info *this_frame, void **this_cache)
1406 {
1407   /* Grab an address that is guarenteed to reside somewhere within the
1408      function.  get_frame_pc(), with a no-return next function, can
1409      end up returning something past the end of this function's body.
1410      If the frame we're sniffing for is a signal frame whose start
1411      address is placed on the stack by the OS, its FDE must
1412      extend one byte before its start address or we could potentially
1413      select the FDE of the previous function.  */
1414   CORE_ADDR block_addr = get_frame_address_in_block (this_frame);
1415   struct dwarf2_fde *fde = dwarf2_frame_find_fde (&block_addr, NULL);
1416
1417   if (!fde)
1418     return 0;
1419
1420   /* On some targets, signal trampolines may have unwind information.
1421      We need to recognize them so that we set the frame type
1422      correctly.  */
1423
1424   if (fde->cie->signal_frame
1425       || dwarf2_frame_signal_frame_p (get_frame_arch (this_frame),
1426                                       this_frame))
1427     return self->type == SIGTRAMP_FRAME;
1428
1429   if (self->type != NORMAL_FRAME)
1430     return 0;
1431
1432   return 1;
1433 }
1434
1435 static const struct frame_unwind dwarf2_frame_unwind =
1436 {
1437   NORMAL_FRAME,
1438   dwarf2_frame_unwind_stop_reason,
1439   dwarf2_frame_this_id,
1440   dwarf2_frame_prev_register,
1441   NULL,
1442   dwarf2_frame_sniffer,
1443   dwarf2_frame_dealloc_cache
1444 };
1445
1446 static const struct frame_unwind dwarf2_signal_frame_unwind =
1447 {
1448   SIGTRAMP_FRAME,
1449   dwarf2_frame_unwind_stop_reason,
1450   dwarf2_frame_this_id,
1451   dwarf2_frame_prev_register,
1452   NULL,
1453   dwarf2_frame_sniffer,
1454
1455   /* TAILCALL_CACHE can never be in such frame to need dealloc_cache.  */
1456   NULL
1457 };
1458
1459 /* Append the DWARF-2 frame unwinders to GDBARCH's list.  */
1460
1461 void
1462 dwarf2_append_unwinders (struct gdbarch *gdbarch)
1463 {
1464   /* TAILCALL_FRAME must be first to find the record by
1465      dwarf2_tailcall_sniffer_first.  */
1466   frame_unwind_append_unwinder (gdbarch, &dwarf2_tailcall_frame_unwind);
1467
1468   frame_unwind_append_unwinder (gdbarch, &dwarf2_frame_unwind);
1469   frame_unwind_append_unwinder (gdbarch, &dwarf2_signal_frame_unwind);
1470 }
1471 \f
1472
1473 /* There is no explicitly defined relationship between the CFA and the
1474    location of frame's local variables and arguments/parameters.
1475    Therefore, frame base methods on this page should probably only be
1476    used as a last resort, just to avoid printing total garbage as a
1477    response to the "info frame" command.  */
1478
1479 static CORE_ADDR
1480 dwarf2_frame_base_address (struct frame_info *this_frame, void **this_cache)
1481 {
1482   struct dwarf2_frame_cache *cache =
1483     dwarf2_frame_cache (this_frame, this_cache);
1484
1485   return cache->cfa;
1486 }
1487
1488 static const struct frame_base dwarf2_frame_base =
1489 {
1490   &dwarf2_frame_unwind,
1491   dwarf2_frame_base_address,
1492   dwarf2_frame_base_address,
1493   dwarf2_frame_base_address
1494 };
1495
1496 const struct frame_base *
1497 dwarf2_frame_base_sniffer (struct frame_info *this_frame)
1498 {
1499   CORE_ADDR block_addr = get_frame_address_in_block (this_frame);
1500
1501   if (dwarf2_frame_find_fde (&block_addr, NULL))
1502     return &dwarf2_frame_base;
1503
1504   return NULL;
1505 }
1506
1507 /* Compute the CFA for THIS_FRAME, but only if THIS_FRAME came from
1508    the DWARF unwinder.  This is used to implement
1509    DW_OP_call_frame_cfa.  */
1510
1511 CORE_ADDR
1512 dwarf2_frame_cfa (struct frame_info *this_frame)
1513 {
1514   if (frame_unwinder_is (this_frame, &record_btrace_tailcall_frame_unwind)
1515       || frame_unwinder_is (this_frame, &record_btrace_frame_unwind))
1516     throw_error (NOT_AVAILABLE_ERROR,
1517                  _("cfa not available for record btrace target"));
1518
1519   while (get_frame_type (this_frame) == INLINE_FRAME)
1520     this_frame = get_prev_frame (this_frame);
1521   if (get_frame_unwind_stop_reason (this_frame) == UNWIND_UNAVAILABLE)
1522     throw_error (NOT_AVAILABLE_ERROR,
1523                 _("can't compute CFA for this frame: "
1524                   "required registers or memory are unavailable"));
1525   /* This restriction could be lifted if other unwinders are known to
1526      compute the frame base in a way compatible with the DWARF
1527      unwinder.  */
1528   if (!frame_unwinder_is (this_frame, &dwarf2_frame_unwind)
1529       && !frame_unwinder_is (this_frame, &dwarf2_tailcall_frame_unwind))
1530     error (_("can't compute CFA for this frame"));
1531   return get_frame_base (this_frame);
1532 }
1533 \f
1534 const struct objfile_data *dwarf2_frame_objfile_data;
1535
1536 static unsigned int
1537 read_1_byte (bfd *abfd, const gdb_byte *buf)
1538 {
1539   return bfd_get_8 (abfd, buf);
1540 }
1541
1542 static unsigned int
1543 read_4_bytes (bfd *abfd, const gdb_byte *buf)
1544 {
1545   return bfd_get_32 (abfd, buf);
1546 }
1547
1548 static ULONGEST
1549 read_8_bytes (bfd *abfd, const gdb_byte *buf)
1550 {
1551   return bfd_get_64 (abfd, buf);
1552 }
1553
1554 static ULONGEST
1555 read_initial_length (bfd *abfd, const gdb_byte *buf,
1556                      unsigned int *bytes_read_ptr)
1557 {
1558   LONGEST result;
1559
1560   result = bfd_get_32 (abfd, buf);
1561   if (result == 0xffffffff)
1562     {
1563       result = bfd_get_64 (abfd, buf + 4);
1564       *bytes_read_ptr = 12;
1565     }
1566   else
1567     *bytes_read_ptr = 4;
1568
1569   return result;
1570 }
1571 \f
1572
1573 /* Pointer encoding helper functions.  */
1574
1575 /* GCC supports exception handling based on DWARF2 CFI.  However, for
1576    technical reasons, it encodes addresses in its FDE's in a different
1577    way.  Several "pointer encodings" are supported.  The encoding
1578    that's used for a particular FDE is determined by the 'R'
1579    augmentation in the associated CIE.  The argument of this
1580    augmentation is a single byte.  
1581
1582    The address can be encoded as 2 bytes, 4 bytes, 8 bytes, or as a
1583    LEB128.  This is encoded in bits 0, 1 and 2.  Bit 3 encodes whether
1584    the address is signed or unsigned.  Bits 4, 5 and 6 encode how the
1585    address should be interpreted (absolute, relative to the current
1586    position in the FDE, ...).  Bit 7, indicates that the address
1587    should be dereferenced.  */
1588
1589 static gdb_byte
1590 encoding_for_size (unsigned int size)
1591 {
1592   switch (size)
1593     {
1594     case 2:
1595       return DW_EH_PE_udata2;
1596     case 4:
1597       return DW_EH_PE_udata4;
1598     case 8:
1599       return DW_EH_PE_udata8;
1600     default:
1601       internal_error (__FILE__, __LINE__, _("Unsupported address size"));
1602     }
1603 }
1604
1605 static CORE_ADDR
1606 read_encoded_value (struct comp_unit *unit, gdb_byte encoding,
1607                     int ptr_len, const gdb_byte *buf,
1608                     unsigned int *bytes_read_ptr,
1609                     CORE_ADDR func_base)
1610 {
1611   ptrdiff_t offset;
1612   CORE_ADDR base;
1613
1614   /* GCC currently doesn't generate DW_EH_PE_indirect encodings for
1615      FDE's.  */
1616   if (encoding & DW_EH_PE_indirect)
1617     internal_error (__FILE__, __LINE__, 
1618                     _("Unsupported encoding: DW_EH_PE_indirect"));
1619
1620   *bytes_read_ptr = 0;
1621
1622   switch (encoding & 0x70)
1623     {
1624     case DW_EH_PE_absptr:
1625       base = 0;
1626       break;
1627     case DW_EH_PE_pcrel:
1628       base = bfd_get_section_vma (unit->abfd, unit->dwarf_frame_section);
1629       base += (buf - unit->dwarf_frame_buffer);
1630       break;
1631     case DW_EH_PE_datarel:
1632       base = unit->dbase;
1633       break;
1634     case DW_EH_PE_textrel:
1635       base = unit->tbase;
1636       break;
1637     case DW_EH_PE_funcrel:
1638       base = func_base;
1639       break;
1640     case DW_EH_PE_aligned:
1641       base = 0;
1642       offset = buf - unit->dwarf_frame_buffer;
1643       if ((offset % ptr_len) != 0)
1644         {
1645           *bytes_read_ptr = ptr_len - (offset % ptr_len);
1646           buf += *bytes_read_ptr;
1647         }
1648       break;
1649     default:
1650       internal_error (__FILE__, __LINE__,
1651                       _("Invalid or unsupported encoding"));
1652     }
1653
1654   if ((encoding & 0x07) == 0x00)
1655     {
1656       encoding |= encoding_for_size (ptr_len);
1657       if (bfd_get_sign_extend_vma (unit->abfd))
1658         encoding |= DW_EH_PE_signed;
1659     }
1660
1661   switch (encoding & 0x0f)
1662     {
1663     case DW_EH_PE_uleb128:
1664       {
1665         uint64_t value;
1666         const gdb_byte *end_buf = buf + (sizeof (value) + 1) * 8 / 7;
1667
1668         *bytes_read_ptr += safe_read_uleb128 (buf, end_buf, &value) - buf;
1669         return base + value;
1670       }
1671     case DW_EH_PE_udata2:
1672       *bytes_read_ptr += 2;
1673       return (base + bfd_get_16 (unit->abfd, (bfd_byte *) buf));
1674     case DW_EH_PE_udata4:
1675       *bytes_read_ptr += 4;
1676       return (base + bfd_get_32 (unit->abfd, (bfd_byte *) buf));
1677     case DW_EH_PE_udata8:
1678       *bytes_read_ptr += 8;
1679       return (base + bfd_get_64 (unit->abfd, (bfd_byte *) buf));
1680     case DW_EH_PE_sleb128:
1681       {
1682         int64_t value;
1683         const gdb_byte *end_buf = buf + (sizeof (value) + 1) * 8 / 7;
1684
1685         *bytes_read_ptr += safe_read_sleb128 (buf, end_buf, &value) - buf;
1686         return base + value;
1687       }
1688     case DW_EH_PE_sdata2:
1689       *bytes_read_ptr += 2;
1690       return (base + bfd_get_signed_16 (unit->abfd, (bfd_byte *) buf));
1691     case DW_EH_PE_sdata4:
1692       *bytes_read_ptr += 4;
1693       return (base + bfd_get_signed_32 (unit->abfd, (bfd_byte *) buf));
1694     case DW_EH_PE_sdata8:
1695       *bytes_read_ptr += 8;
1696       return (base + bfd_get_signed_64 (unit->abfd, (bfd_byte *) buf));
1697     default:
1698       internal_error (__FILE__, __LINE__,
1699                       _("Invalid or unsupported encoding"));
1700     }
1701 }
1702 \f
1703
1704 static int
1705 bsearch_cie_cmp (const void *key, const void *element)
1706 {
1707   ULONGEST cie_pointer = *(ULONGEST *) key;
1708   struct dwarf2_cie *cie = *(struct dwarf2_cie **) element;
1709
1710   if (cie_pointer == cie->cie_pointer)
1711     return 0;
1712
1713   return (cie_pointer < cie->cie_pointer) ? -1 : 1;
1714 }
1715
1716 /* Find CIE with the given CIE_POINTER in CIE_TABLE.  */
1717 static struct dwarf2_cie *
1718 find_cie (struct dwarf2_cie_table *cie_table, ULONGEST cie_pointer)
1719 {
1720   struct dwarf2_cie **p_cie;
1721
1722   /* The C standard (ISO/IEC 9899:TC2) requires the BASE argument to
1723      bsearch be non-NULL.  */
1724   if (cie_table->entries == NULL)
1725     {
1726       gdb_assert (cie_table->num_entries == 0);
1727       return NULL;
1728     }
1729
1730   p_cie = bsearch (&cie_pointer, cie_table->entries, cie_table->num_entries,
1731                    sizeof (cie_table->entries[0]), bsearch_cie_cmp);
1732   if (p_cie != NULL)
1733     return *p_cie;
1734   return NULL;
1735 }
1736
1737 /* Add a pointer to new CIE to the CIE_TABLE, allocating space for it.  */
1738 static void
1739 add_cie (struct dwarf2_cie_table *cie_table, struct dwarf2_cie *cie)
1740 {
1741   const int n = cie_table->num_entries;
1742
1743   gdb_assert (n < 1
1744               || cie_table->entries[n - 1]->cie_pointer < cie->cie_pointer);
1745
1746   cie_table->entries =
1747       xrealloc (cie_table->entries, (n + 1) * sizeof (cie_table->entries[0]));
1748   cie_table->entries[n] = cie;
1749   cie_table->num_entries = n + 1;
1750 }
1751
1752 static int
1753 bsearch_fde_cmp (const void *key, const void *element)
1754 {
1755   CORE_ADDR seek_pc = *(CORE_ADDR *) key;
1756   struct dwarf2_fde *fde = *(struct dwarf2_fde **) element;
1757
1758   if (seek_pc < fde->initial_location)
1759     return -1;
1760   if (seek_pc < fde->initial_location + fde->address_range)
1761     return 0;
1762   return 1;
1763 }
1764
1765 /* Find the FDE for *PC.  Return a pointer to the FDE, and store the
1766    inital location associated with it into *PC.  */
1767
1768 static struct dwarf2_fde *
1769 dwarf2_frame_find_fde (CORE_ADDR *pc, CORE_ADDR *out_offset)
1770 {
1771   struct objfile *objfile;
1772
1773   ALL_OBJFILES (objfile)
1774     {
1775       struct dwarf2_fde_table *fde_table;
1776       struct dwarf2_fde **p_fde;
1777       CORE_ADDR offset;
1778       CORE_ADDR seek_pc;
1779
1780       fde_table = objfile_data (objfile, dwarf2_frame_objfile_data);
1781       if (fde_table == NULL)
1782         {
1783           dwarf2_build_frame_info (objfile);
1784           fde_table = objfile_data (objfile, dwarf2_frame_objfile_data);
1785         }
1786       gdb_assert (fde_table != NULL);
1787
1788       if (fde_table->num_entries == 0)
1789         continue;
1790
1791       gdb_assert (objfile->section_offsets);
1792       offset = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
1793
1794       gdb_assert (fde_table->num_entries > 0);
1795       if (*pc < offset + fde_table->entries[0]->initial_location)
1796         continue;
1797
1798       seek_pc = *pc - offset;
1799       p_fde = bsearch (&seek_pc, fde_table->entries, fde_table->num_entries,
1800                        sizeof (fde_table->entries[0]), bsearch_fde_cmp);
1801       if (p_fde != NULL)
1802         {
1803           *pc = (*p_fde)->initial_location + offset;
1804           if (out_offset)
1805             *out_offset = offset;
1806           return *p_fde;
1807         }
1808     }
1809   return NULL;
1810 }
1811
1812 /* Add a pointer to new FDE to the FDE_TABLE, allocating space for it.  */
1813 static void
1814 add_fde (struct dwarf2_fde_table *fde_table, struct dwarf2_fde *fde)
1815 {
1816   if (fde->address_range == 0)
1817     /* Discard useless FDEs.  */
1818     return;
1819
1820   fde_table->num_entries += 1;
1821   fde_table->entries =
1822       xrealloc (fde_table->entries,
1823                 fde_table->num_entries * sizeof (fde_table->entries[0]));
1824   fde_table->entries[fde_table->num_entries - 1] = fde;
1825 }
1826
1827 #define DW64_CIE_ID 0xffffffffffffffffULL
1828
1829 /* Defines the type of eh_frames that are expected to be decoded: CIE, FDE
1830    or any of them.  */
1831
1832 enum eh_frame_type
1833 {
1834   EH_CIE_TYPE_ID = 1 << 0,
1835   EH_FDE_TYPE_ID = 1 << 1,
1836   EH_CIE_OR_FDE_TYPE_ID = EH_CIE_TYPE_ID | EH_FDE_TYPE_ID
1837 };
1838
1839 static const gdb_byte *decode_frame_entry (struct comp_unit *unit,
1840                                            const gdb_byte *start,
1841                                            int eh_frame_p,
1842                                            struct dwarf2_cie_table *cie_table,
1843                                            struct dwarf2_fde_table *fde_table,
1844                                            enum eh_frame_type entry_type);
1845
1846 /* Decode the next CIE or FDE, entry_type specifies the expected type.
1847    Return NULL if invalid input, otherwise the next byte to be processed.  */
1848
1849 static const gdb_byte *
1850 decode_frame_entry_1 (struct comp_unit *unit, const gdb_byte *start,
1851                       int eh_frame_p,
1852                       struct dwarf2_cie_table *cie_table,
1853                       struct dwarf2_fde_table *fde_table,
1854                       enum eh_frame_type entry_type)
1855 {
1856   struct gdbarch *gdbarch = get_objfile_arch (unit->objfile);
1857   const gdb_byte *buf, *end;
1858   LONGEST length;
1859   unsigned int bytes_read;
1860   int dwarf64_p;
1861   ULONGEST cie_id;
1862   ULONGEST cie_pointer;
1863   int64_t sleb128;
1864   uint64_t uleb128;
1865
1866   buf = start;
1867   length = read_initial_length (unit->abfd, buf, &bytes_read);
1868   buf += bytes_read;
1869   end = buf + length;
1870
1871   /* Are we still within the section?  */
1872   if (end > unit->dwarf_frame_buffer + unit->dwarf_frame_size)
1873     return NULL;
1874
1875   if (length == 0)
1876     return end;
1877
1878   /* Distinguish between 32 and 64-bit encoded frame info.  */
1879   dwarf64_p = (bytes_read == 12);
1880
1881   /* In a .eh_frame section, zero is used to distinguish CIEs from FDEs.  */
1882   if (eh_frame_p)
1883     cie_id = 0;
1884   else if (dwarf64_p)
1885     cie_id = DW64_CIE_ID;
1886   else
1887     cie_id = DW_CIE_ID;
1888
1889   if (dwarf64_p)
1890     {
1891       cie_pointer = read_8_bytes (unit->abfd, buf);
1892       buf += 8;
1893     }
1894   else
1895     {
1896       cie_pointer = read_4_bytes (unit->abfd, buf);
1897       buf += 4;
1898     }
1899
1900   if (cie_pointer == cie_id)
1901     {
1902       /* This is a CIE.  */
1903       struct dwarf2_cie *cie;
1904       char *augmentation;
1905       unsigned int cie_version;
1906
1907       /* Check that a CIE was expected.  */
1908       if ((entry_type & EH_CIE_TYPE_ID) == 0)
1909         error (_("Found a CIE when not expecting it."));
1910
1911       /* Record the offset into the .debug_frame section of this CIE.  */
1912       cie_pointer = start - unit->dwarf_frame_buffer;
1913
1914       /* Check whether we've already read it.  */
1915       if (find_cie (cie_table, cie_pointer))
1916         return end;
1917
1918       cie = (struct dwarf2_cie *)
1919         obstack_alloc (&unit->objfile->objfile_obstack,
1920                        sizeof (struct dwarf2_cie));
1921       cie->initial_instructions = NULL;
1922       cie->cie_pointer = cie_pointer;
1923
1924       /* The encoding for FDE's in a normal .debug_frame section
1925          depends on the target address size.  */
1926       cie->encoding = DW_EH_PE_absptr;
1927
1928       /* We'll determine the final value later, but we need to
1929          initialize it conservatively.  */
1930       cie->signal_frame = 0;
1931
1932       /* Check version number.  */
1933       cie_version = read_1_byte (unit->abfd, buf);
1934       if (cie_version != 1 && cie_version != 3 && cie_version != 4)
1935         return NULL;
1936       cie->version = cie_version;
1937       buf += 1;
1938
1939       /* Interpret the interesting bits of the augmentation.  */
1940       cie->augmentation = augmentation = (char *) buf;
1941       buf += (strlen (augmentation) + 1);
1942
1943       /* Ignore armcc augmentations.  We only use them for quirks,
1944          and that doesn't happen until later.  */
1945       if (strncmp (augmentation, "armcc", 5) == 0)
1946         augmentation += strlen (augmentation);
1947
1948       /* The GCC 2.x "eh" augmentation has a pointer immediately
1949          following the augmentation string, so it must be handled
1950          first.  */
1951       if (augmentation[0] == 'e' && augmentation[1] == 'h')
1952         {
1953           /* Skip.  */
1954           buf += gdbarch_ptr_bit (gdbarch) / TARGET_CHAR_BIT;
1955           augmentation += 2;
1956         }
1957
1958       if (cie->version >= 4)
1959         {
1960           /* FIXME: check that this is the same as from the CU header.  */
1961           cie->addr_size = read_1_byte (unit->abfd, buf);
1962           ++buf;
1963           cie->segment_size = read_1_byte (unit->abfd, buf);
1964           ++buf;
1965         }
1966       else
1967         {
1968           cie->addr_size = gdbarch_dwarf2_addr_size (gdbarch);
1969           cie->segment_size = 0;
1970         }
1971       /* Address values in .eh_frame sections are defined to have the
1972          target's pointer size.  Watchout: This breaks frame info for
1973          targets with pointer size < address size, unless a .debug_frame
1974          section exists as well.  */
1975       if (eh_frame_p)
1976         cie->ptr_size = gdbarch_ptr_bit (gdbarch) / TARGET_CHAR_BIT;
1977       else
1978         cie->ptr_size = cie->addr_size;
1979
1980       buf = gdb_read_uleb128 (buf, end, &uleb128);
1981       if (buf == NULL)
1982         return NULL;
1983       cie->code_alignment_factor = uleb128;
1984
1985       buf = gdb_read_sleb128 (buf, end, &sleb128);
1986       if (buf == NULL)
1987         return NULL;
1988       cie->data_alignment_factor = sleb128;
1989
1990       if (cie_version == 1)
1991         {
1992           cie->return_address_register = read_1_byte (unit->abfd, buf);
1993           ++buf;
1994         }
1995       else
1996         {
1997           buf = gdb_read_uleb128 (buf, end, &uleb128);
1998           if (buf == NULL)
1999             return NULL;
2000           cie->return_address_register = uleb128;
2001         }
2002
2003       cie->return_address_register
2004         = dwarf2_frame_adjust_regnum (gdbarch,
2005                                       cie->return_address_register,
2006                                       eh_frame_p);
2007
2008       cie->saw_z_augmentation = (*augmentation == 'z');
2009       if (cie->saw_z_augmentation)
2010         {
2011           uint64_t length;
2012
2013           buf = gdb_read_uleb128 (buf, end, &length);
2014           if (buf == NULL)
2015             return NULL;
2016           cie->initial_instructions = buf + length;
2017           augmentation++;
2018         }
2019
2020       while (*augmentation)
2021         {
2022           /* "L" indicates a byte showing how the LSDA pointer is encoded.  */
2023           if (*augmentation == 'L')
2024             {
2025               /* Skip.  */
2026               buf++;
2027               augmentation++;
2028             }
2029
2030           /* "R" indicates a byte indicating how FDE addresses are encoded.  */
2031           else if (*augmentation == 'R')
2032             {
2033               cie->encoding = *buf++;
2034               augmentation++;
2035             }
2036
2037           /* "P" indicates a personality routine in the CIE augmentation.  */
2038           else if (*augmentation == 'P')
2039             {
2040               /* Skip.  Avoid indirection since we throw away the result.  */
2041               gdb_byte encoding = (*buf++) & ~DW_EH_PE_indirect;
2042               read_encoded_value (unit, encoding, cie->ptr_size,
2043                                   buf, &bytes_read, 0);
2044               buf += bytes_read;
2045               augmentation++;
2046             }
2047
2048           /* "S" indicates a signal frame, such that the return
2049              address must not be decremented to locate the call frame
2050              info for the previous frame; it might even be the first
2051              instruction of a function, so decrementing it would take
2052              us to a different function.  */
2053           else if (*augmentation == 'S')
2054             {
2055               cie->signal_frame = 1;
2056               augmentation++;
2057             }
2058
2059           /* Otherwise we have an unknown augmentation.  Assume that either
2060              there is no augmentation data, or we saw a 'z' prefix.  */
2061           else
2062             {
2063               if (cie->initial_instructions)
2064                 buf = cie->initial_instructions;
2065               break;
2066             }
2067         }
2068
2069       cie->initial_instructions = buf;
2070       cie->end = end;
2071       cie->unit = unit;
2072
2073       add_cie (cie_table, cie);
2074     }
2075   else
2076     {
2077       /* This is a FDE.  */
2078       struct dwarf2_fde *fde;
2079
2080       /* Check that an FDE was expected.  */
2081       if ((entry_type & EH_FDE_TYPE_ID) == 0)
2082         error (_("Found an FDE when not expecting it."));
2083
2084       /* In an .eh_frame section, the CIE pointer is the delta between the
2085          address within the FDE where the CIE pointer is stored and the
2086          address of the CIE.  Convert it to an offset into the .eh_frame
2087          section.  */
2088       if (eh_frame_p)
2089         {
2090           cie_pointer = buf - unit->dwarf_frame_buffer - cie_pointer;
2091           cie_pointer -= (dwarf64_p ? 8 : 4);
2092         }
2093
2094       /* In either case, validate the result is still within the section.  */
2095       if (cie_pointer >= unit->dwarf_frame_size)
2096         return NULL;
2097
2098       fde = (struct dwarf2_fde *)
2099         obstack_alloc (&unit->objfile->objfile_obstack,
2100                        sizeof (struct dwarf2_fde));
2101       fde->cie = find_cie (cie_table, cie_pointer);
2102       if (fde->cie == NULL)
2103         {
2104           decode_frame_entry (unit, unit->dwarf_frame_buffer + cie_pointer,
2105                               eh_frame_p, cie_table, fde_table,
2106                               EH_CIE_TYPE_ID);
2107           fde->cie = find_cie (cie_table, cie_pointer);
2108         }
2109
2110       gdb_assert (fde->cie != NULL);
2111
2112       fde->initial_location =
2113         read_encoded_value (unit, fde->cie->encoding, fde->cie->ptr_size,
2114                             buf, &bytes_read, 0);
2115       buf += bytes_read;
2116
2117       fde->address_range =
2118         read_encoded_value (unit, fde->cie->encoding & 0x0f,
2119                             fde->cie->ptr_size, buf, &bytes_read, 0);
2120       buf += bytes_read;
2121
2122       /* A 'z' augmentation in the CIE implies the presence of an
2123          augmentation field in the FDE as well.  The only thing known
2124          to be in here at present is the LSDA entry for EH.  So we
2125          can skip the whole thing.  */
2126       if (fde->cie->saw_z_augmentation)
2127         {
2128           uint64_t length;
2129
2130           buf = gdb_read_uleb128 (buf, end, &length);
2131           if (buf == NULL)
2132             return NULL;
2133           buf += length;
2134           if (buf > end)
2135             return NULL;
2136         }
2137
2138       fde->instructions = buf;
2139       fde->end = end;
2140
2141       fde->eh_frame_p = eh_frame_p;
2142
2143       add_fde (fde_table, fde);
2144     }
2145
2146   return end;
2147 }
2148
2149 /* Read a CIE or FDE in BUF and decode it. Entry_type specifies whether we
2150    expect an FDE or a CIE.  */
2151
2152 static const gdb_byte *
2153 decode_frame_entry (struct comp_unit *unit, const gdb_byte *start,
2154                     int eh_frame_p,
2155                     struct dwarf2_cie_table *cie_table,
2156                     struct dwarf2_fde_table *fde_table,
2157                     enum eh_frame_type entry_type)
2158 {
2159   enum { NONE, ALIGN4, ALIGN8, FAIL } workaround = NONE;
2160   const gdb_byte *ret;
2161   ptrdiff_t start_offset;
2162
2163   while (1)
2164     {
2165       ret = decode_frame_entry_1 (unit, start, eh_frame_p,
2166                                   cie_table, fde_table, entry_type);
2167       if (ret != NULL)
2168         break;
2169
2170       /* We have corrupt input data of some form.  */
2171
2172       /* ??? Try, weakly, to work around compiler/assembler/linker bugs
2173          and mismatches wrt padding and alignment of debug sections.  */
2174       /* Note that there is no requirement in the standard for any
2175          alignment at all in the frame unwind sections.  Testing for
2176          alignment before trying to interpret data would be incorrect.
2177
2178          However, GCC traditionally arranged for frame sections to be
2179          sized such that the FDE length and CIE fields happen to be
2180          aligned (in theory, for performance).  This, unfortunately,
2181          was done with .align directives, which had the side effect of
2182          forcing the section to be aligned by the linker.
2183
2184          This becomes a problem when you have some other producer that
2185          creates frame sections that are not as strictly aligned.  That
2186          produces a hole in the frame info that gets filled by the 
2187          linker with zeros.
2188
2189          The GCC behaviour is arguably a bug, but it's effectively now
2190          part of the ABI, so we're now stuck with it, at least at the
2191          object file level.  A smart linker may decide, in the process
2192          of compressing duplicate CIE information, that it can rewrite
2193          the entire output section without this extra padding.  */
2194
2195       start_offset = start - unit->dwarf_frame_buffer;
2196       if (workaround < ALIGN4 && (start_offset & 3) != 0)
2197         {
2198           start += 4 - (start_offset & 3);
2199           workaround = ALIGN4;
2200           continue;
2201         }
2202       if (workaround < ALIGN8 && (start_offset & 7) != 0)
2203         {
2204           start += 8 - (start_offset & 7);
2205           workaround = ALIGN8;
2206           continue;
2207         }
2208
2209       /* Nothing left to try.  Arrange to return as if we've consumed
2210          the entire input section.  Hopefully we'll get valid info from
2211          the other of .debug_frame/.eh_frame.  */
2212       workaround = FAIL;
2213       ret = unit->dwarf_frame_buffer + unit->dwarf_frame_size;
2214       break;
2215     }
2216
2217   switch (workaround)
2218     {
2219     case NONE:
2220       break;
2221
2222     case ALIGN4:
2223       complaint (&symfile_complaints, _("\
2224 Corrupt data in %s:%s; align 4 workaround apparently succeeded"),
2225                  unit->dwarf_frame_section->owner->filename,
2226                  unit->dwarf_frame_section->name);
2227       break;
2228
2229     case ALIGN8:
2230       complaint (&symfile_complaints, _("\
2231 Corrupt data in %s:%s; align 8 workaround apparently succeeded"),
2232                  unit->dwarf_frame_section->owner->filename,
2233                  unit->dwarf_frame_section->name);
2234       break;
2235
2236     default:
2237       complaint (&symfile_complaints,
2238                  _("Corrupt data in %s:%s"),
2239                  unit->dwarf_frame_section->owner->filename,
2240                  unit->dwarf_frame_section->name);
2241       break;
2242     }
2243
2244   return ret;
2245 }
2246 \f
2247 static int
2248 qsort_fde_cmp (const void *a, const void *b)
2249 {
2250   struct dwarf2_fde *aa = *(struct dwarf2_fde **)a;
2251   struct dwarf2_fde *bb = *(struct dwarf2_fde **)b;
2252
2253   if (aa->initial_location == bb->initial_location)
2254     {
2255       if (aa->address_range != bb->address_range
2256           && aa->eh_frame_p == 0 && bb->eh_frame_p == 0)
2257         /* Linker bug, e.g. gold/10400.
2258            Work around it by keeping stable sort order.  */
2259         return (a < b) ? -1 : 1;
2260       else
2261         /* Put eh_frame entries after debug_frame ones.  */
2262         return aa->eh_frame_p - bb->eh_frame_p;
2263     }
2264
2265   return (aa->initial_location < bb->initial_location) ? -1 : 1;
2266 }
2267
2268 void
2269 dwarf2_build_frame_info (struct objfile *objfile)
2270 {
2271   struct comp_unit *unit;
2272   const gdb_byte *frame_ptr;
2273   struct dwarf2_cie_table cie_table;
2274   struct dwarf2_fde_table fde_table;
2275   struct dwarf2_fde_table *fde_table2;
2276   volatile struct gdb_exception e;
2277
2278   cie_table.num_entries = 0;
2279   cie_table.entries = NULL;
2280
2281   fde_table.num_entries = 0;
2282   fde_table.entries = NULL;
2283
2284   /* Build a minimal decoding of the DWARF2 compilation unit.  */
2285   unit = (struct comp_unit *) obstack_alloc (&objfile->objfile_obstack,
2286                                              sizeof (struct comp_unit));
2287   unit->abfd = objfile->obfd;
2288   unit->objfile = objfile;
2289   unit->dbase = 0;
2290   unit->tbase = 0;
2291
2292   if (objfile->separate_debug_objfile_backlink == NULL)
2293     {
2294       /* Do not read .eh_frame from separate file as they must be also
2295          present in the main file.  */
2296       dwarf2_get_section_info (objfile, DWARF2_EH_FRAME,
2297                                &unit->dwarf_frame_section,
2298                                &unit->dwarf_frame_buffer,
2299                                &unit->dwarf_frame_size);
2300       if (unit->dwarf_frame_size)
2301         {
2302           asection *got, *txt;
2303
2304           /* FIXME: kettenis/20030602: This is the DW_EH_PE_datarel base
2305              that is used for the i386/amd64 target, which currently is
2306              the only target in GCC that supports/uses the
2307              DW_EH_PE_datarel encoding.  */
2308           got = bfd_get_section_by_name (unit->abfd, ".got");
2309           if (got)
2310             unit->dbase = got->vma;
2311
2312           /* GCC emits the DW_EH_PE_textrel encoding type on sh and ia64
2313              so far.  */
2314           txt = bfd_get_section_by_name (unit->abfd, ".text");
2315           if (txt)
2316             unit->tbase = txt->vma;
2317
2318           TRY_CATCH (e, RETURN_MASK_ERROR)
2319             {
2320               frame_ptr = unit->dwarf_frame_buffer;
2321               while (frame_ptr < unit->dwarf_frame_buffer + unit->dwarf_frame_size)
2322                 frame_ptr = decode_frame_entry (unit, frame_ptr, 1,
2323                                                 &cie_table, &fde_table,
2324                                                 EH_CIE_OR_FDE_TYPE_ID);
2325             }
2326
2327           if (e.reason < 0)
2328             {
2329               warning (_("skipping .eh_frame info of %s: %s"),
2330                        objfile_name (objfile), e.message);
2331
2332               if (fde_table.num_entries != 0)
2333                 {
2334                   xfree (fde_table.entries);
2335                   fde_table.entries = NULL;
2336                   fde_table.num_entries = 0;
2337                 }
2338               /* The cie_table is discarded by the next if.  */
2339             }
2340
2341           if (cie_table.num_entries != 0)
2342             {
2343               /* Reinit cie_table: debug_frame has different CIEs.  */
2344               xfree (cie_table.entries);
2345               cie_table.num_entries = 0;
2346               cie_table.entries = NULL;
2347             }
2348         }
2349     }
2350
2351   dwarf2_get_section_info (objfile, DWARF2_DEBUG_FRAME,
2352                            &unit->dwarf_frame_section,
2353                            &unit->dwarf_frame_buffer,
2354                            &unit->dwarf_frame_size);
2355   if (unit->dwarf_frame_size)
2356     {
2357       int num_old_fde_entries = fde_table.num_entries;
2358
2359       TRY_CATCH (e, RETURN_MASK_ERROR)
2360         {
2361           frame_ptr = unit->dwarf_frame_buffer;
2362           while (frame_ptr < unit->dwarf_frame_buffer + unit->dwarf_frame_size)
2363             frame_ptr = decode_frame_entry (unit, frame_ptr, 0,
2364                                             &cie_table, &fde_table,
2365                                             EH_CIE_OR_FDE_TYPE_ID);
2366         }
2367       if (e.reason < 0)
2368         {
2369           warning (_("skipping .debug_frame info of %s: %s"),
2370                    objfile_name (objfile), e.message);
2371
2372           if (fde_table.num_entries != 0)
2373             {
2374               fde_table.num_entries = num_old_fde_entries;
2375               if (num_old_fde_entries == 0)
2376                 {
2377                   xfree (fde_table.entries);
2378                   fde_table.entries = NULL;
2379                 }
2380               else
2381                 {
2382                   fde_table.entries = xrealloc (fde_table.entries,
2383                                                 fde_table.num_entries *
2384                                                 sizeof (fde_table.entries[0]));
2385                 }
2386             }
2387           fde_table.num_entries = num_old_fde_entries;
2388           /* The cie_table is discarded by the next if.  */
2389         }
2390     }
2391
2392   /* Discard the cie_table, it is no longer needed.  */
2393   if (cie_table.num_entries != 0)
2394     {
2395       xfree (cie_table.entries);
2396       cie_table.entries = NULL;   /* Paranoia.  */
2397       cie_table.num_entries = 0;  /* Paranoia.  */
2398     }
2399
2400   /* Copy fde_table to obstack: it is needed at runtime.  */
2401   fde_table2 = (struct dwarf2_fde_table *)
2402     obstack_alloc (&objfile->objfile_obstack, sizeof (*fde_table2));
2403
2404   if (fde_table.num_entries == 0)
2405     {
2406       fde_table2->entries = NULL;
2407       fde_table2->num_entries = 0;
2408     }
2409   else
2410     {
2411       struct dwarf2_fde *fde_prev = NULL;
2412       struct dwarf2_fde *first_non_zero_fde = NULL;
2413       int i;
2414
2415       /* Prepare FDE table for lookups.  */
2416       qsort (fde_table.entries, fde_table.num_entries,
2417              sizeof (fde_table.entries[0]), qsort_fde_cmp);
2418
2419       /* Check for leftovers from --gc-sections.  The GNU linker sets
2420          the relevant symbols to zero, but doesn't zero the FDE *end*
2421          ranges because there's no relocation there.  It's (offset,
2422          length), not (start, end).  On targets where address zero is
2423          just another valid address this can be a problem, since the
2424          FDEs appear to be non-empty in the output --- we could pick
2425          out the wrong FDE.  To work around this, when overlaps are
2426          detected, we prefer FDEs that do not start at zero.
2427
2428          Start by finding the first FDE with non-zero start.  Below
2429          we'll discard all FDEs that start at zero and overlap this
2430          one.  */
2431       for (i = 0; i < fde_table.num_entries; i++)
2432         {
2433           struct dwarf2_fde *fde = fde_table.entries[i];
2434
2435           if (fde->initial_location != 0)
2436             {
2437               first_non_zero_fde = fde;
2438               break;
2439             }
2440         }
2441
2442       /* Since we'll be doing bsearch, squeeze out identical (except
2443          for eh_frame_p) fde entries so bsearch result is predictable.
2444          Also discard leftovers from --gc-sections.  */
2445       fde_table2->num_entries = 0;
2446       for (i = 0; i < fde_table.num_entries; i++)
2447         {
2448           struct dwarf2_fde *fde = fde_table.entries[i];
2449
2450           if (fde->initial_location == 0
2451               && first_non_zero_fde != NULL
2452               && (first_non_zero_fde->initial_location
2453                   < fde->initial_location + fde->address_range))
2454             continue;
2455
2456           if (fde_prev != NULL
2457               && fde_prev->initial_location == fde->initial_location)
2458             continue;
2459
2460           obstack_grow (&objfile->objfile_obstack, &fde_table.entries[i],
2461                         sizeof (fde_table.entries[0]));
2462           ++fde_table2->num_entries;
2463           fde_prev = fde;
2464         }
2465       fde_table2->entries = obstack_finish (&objfile->objfile_obstack);
2466
2467       /* Discard the original fde_table.  */
2468       xfree (fde_table.entries);
2469     }
2470
2471   set_objfile_data (objfile, dwarf2_frame_objfile_data, fde_table2);
2472 }
2473
2474 /* Provide a prototype to silence -Wmissing-prototypes.  */
2475 void _initialize_dwarf2_frame (void);
2476
2477 void
2478 _initialize_dwarf2_frame (void)
2479 {
2480   dwarf2_frame_data = gdbarch_data_register_pre_init (dwarf2_frame_init);
2481   dwarf2_frame_objfile_data = register_objfile_data ();
2482 }