Convert frame unwinders to use the current frame and
[external/binutils.git] / gdb / frame.c
1 /* Cache and manage frames for GDB, the GNU debugger.
2
3    Copyright (C) 1986, 1987, 1989, 1991, 1994, 1995, 1996, 1998, 2000, 2001,
4    2002, 2003, 2004, 2007, 2008 Free Software Foundation, Inc.
5
6    This file is part of GDB.
7
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
20
21 #include "defs.h"
22 #include "frame.h"
23 #include "target.h"
24 #include "value.h"
25 #include "inferior.h"   /* for inferior_ptid */
26 #include "regcache.h"
27 #include "gdb_assert.h"
28 #include "gdb_string.h"
29 #include "user-regs.h"
30 #include "gdb_obstack.h"
31 #include "dummy-frame.h"
32 #include "sentinel-frame.h"
33 #include "gdbcore.h"
34 #include "annotate.h"
35 #include "language.h"
36 #include "frame-unwind.h"
37 #include "frame-base.h"
38 #include "command.h"
39 #include "gdbcmd.h"
40 #include "observer.h"
41 #include "objfiles.h"
42 #include "exceptions.h"
43
44 static struct frame_info *get_prev_frame_1 (struct frame_info *this_frame);
45
46 /* We keep a cache of stack frames, each of which is a "struct
47    frame_info".  The innermost one gets allocated (in
48    wait_for_inferior) each time the inferior stops; current_frame
49    points to it.  Additional frames get allocated (in get_prev_frame)
50    as needed, and are chained through the next and prev fields.  Any
51    time that the frame cache becomes invalid (most notably when we
52    execute something, but also if we change how we interpret the
53    frames (e.g. "set heuristic-fence-post" in mips-tdep.c, or anything
54    which reads new symbols)), we should call reinit_frame_cache.  */
55
56 struct frame_info
57 {
58   /* Level of this frame.  The inner-most (youngest) frame is at level
59      0.  As you move towards the outer-most (oldest) frame, the level
60      increases.  This is a cached value.  It could just as easily be
61      computed by counting back from the selected frame to the inner
62      most frame.  */
63   /* NOTE: cagney/2002-04-05: Perhaps a level of ``-1'' should be
64      reserved to indicate a bogus frame - one that has been created
65      just to keep GDB happy (GDB always needs a frame).  For the
66      moment leave this as speculation.  */
67   int level;
68
69   /* The frame's low-level unwinder and corresponding cache.  The
70      low-level unwinder is responsible for unwinding register values
71      for the previous frame.  The low-level unwind methods are
72      selected based on the presence, or otherwise, of register unwind
73      information such as CFI.  */
74   void *prologue_cache;
75   const struct frame_unwind *unwind;
76
77   /* Cached copy of the previous frame's resume address.  */
78   struct {
79     int p;
80     CORE_ADDR value;
81   } prev_pc;
82   
83   /* Cached copy of the previous frame's function address.  */
84   struct
85   {
86     CORE_ADDR addr;
87     int p;
88   } prev_func;
89   
90   /* This frame's ID.  */
91   struct
92   {
93     int p;
94     struct frame_id value;
95   } this_id;
96   
97   /* The frame's high-level base methods, and corresponding cache.
98      The high level base methods are selected based on the frame's
99      debug info.  */
100   const struct frame_base *base;
101   void *base_cache;
102
103   /* Pointers to the next (down, inner, younger) and previous (up,
104      outer, older) frame_info's in the frame cache.  */
105   struct frame_info *next; /* down, inner, younger */
106   int prev_p;
107   struct frame_info *prev; /* up, outer, older */
108
109   /* The reason why we could not set PREV, or UNWIND_NO_REASON if we
110      could.  Only valid when PREV_P is set.  */
111   enum unwind_stop_reason stop_reason;
112 };
113
114 /* Flag to control debugging.  */
115
116 int frame_debug;
117 static void
118 show_frame_debug (struct ui_file *file, int from_tty,
119                   struct cmd_list_element *c, const char *value)
120 {
121   fprintf_filtered (file, _("Frame debugging is %s.\n"), value);
122 }
123
124 /* Flag to indicate whether backtraces should stop at main et.al.  */
125
126 static int backtrace_past_main;
127 static void
128 show_backtrace_past_main (struct ui_file *file, int from_tty,
129                           struct cmd_list_element *c, const char *value)
130 {
131   fprintf_filtered (file, _("\
132 Whether backtraces should continue past \"main\" is %s.\n"),
133                     value);
134 }
135
136 static int backtrace_past_entry;
137 static void
138 show_backtrace_past_entry (struct ui_file *file, int from_tty,
139                            struct cmd_list_element *c, const char *value)
140 {
141   fprintf_filtered (file, _("\
142 Whether backtraces should continue past the entry point of a program is %s.\n"),
143                     value);
144 }
145
146 static int backtrace_limit = INT_MAX;
147 static void
148 show_backtrace_limit (struct ui_file *file, int from_tty,
149                       struct cmd_list_element *c, const char *value)
150 {
151   fprintf_filtered (file, _("\
152 An upper bound on the number of backtrace levels is %s.\n"),
153                     value);
154 }
155
156
157 static void
158 fprint_field (struct ui_file *file, const char *name, int p, CORE_ADDR addr)
159 {
160   if (p)
161     fprintf_unfiltered (file, "%s=0x%s", name, paddr_nz (addr));
162   else
163     fprintf_unfiltered (file, "!%s", name);
164 }
165
166 void
167 fprint_frame_id (struct ui_file *file, struct frame_id id)
168 {
169   fprintf_unfiltered (file, "{");
170   fprint_field (file, "stack", id.stack_addr_p, id.stack_addr);
171   fprintf_unfiltered (file, ",");
172   fprint_field (file, "code", id.code_addr_p, id.code_addr);
173   fprintf_unfiltered (file, ",");
174   fprint_field (file, "special", id.special_addr_p, id.special_addr);
175   fprintf_unfiltered (file, "}");
176 }
177
178 static void
179 fprint_frame_type (struct ui_file *file, enum frame_type type)
180 {
181   switch (type)
182     {
183     case NORMAL_FRAME:
184       fprintf_unfiltered (file, "NORMAL_FRAME");
185       return;
186     case DUMMY_FRAME:
187       fprintf_unfiltered (file, "DUMMY_FRAME");
188       return;
189     case SIGTRAMP_FRAME:
190       fprintf_unfiltered (file, "SIGTRAMP_FRAME");
191       return;
192     default:
193       fprintf_unfiltered (file, "<unknown type>");
194       return;
195     };
196 }
197
198 static void
199 fprint_frame (struct ui_file *file, struct frame_info *fi)
200 {
201   if (fi == NULL)
202     {
203       fprintf_unfiltered (file, "<NULL frame>");
204       return;
205     }
206   fprintf_unfiltered (file, "{");
207   fprintf_unfiltered (file, "level=%d", fi->level);
208   fprintf_unfiltered (file, ",");
209   fprintf_unfiltered (file, "type=");
210   if (fi->unwind != NULL)
211     fprint_frame_type (file, fi->unwind->type);
212   else
213     fprintf_unfiltered (file, "<unknown>");
214   fprintf_unfiltered (file, ",");
215   fprintf_unfiltered (file, "unwind=");
216   if (fi->unwind != NULL)
217     gdb_print_host_address (fi->unwind, file);
218   else
219     fprintf_unfiltered (file, "<unknown>");
220   fprintf_unfiltered (file, ",");
221   fprintf_unfiltered (file, "pc=");
222   if (fi->next != NULL && fi->next->prev_pc.p)
223     fprintf_unfiltered (file, "0x%s", paddr_nz (fi->next->prev_pc.value));
224   else
225     fprintf_unfiltered (file, "<unknown>");
226   fprintf_unfiltered (file, ",");
227   fprintf_unfiltered (file, "id=");
228   if (fi->this_id.p)
229     fprint_frame_id (file, fi->this_id.value);
230   else
231     fprintf_unfiltered (file, "<unknown>");
232   fprintf_unfiltered (file, ",");
233   fprintf_unfiltered (file, "func=");
234   if (fi->next != NULL && fi->next->prev_func.p)
235     fprintf_unfiltered (file, "0x%s", paddr_nz (fi->next->prev_func.addr));
236   else
237     fprintf_unfiltered (file, "<unknown>");
238   fprintf_unfiltered (file, "}");
239 }
240
241 /* Return a frame uniq ID that can be used to, later, re-find the
242    frame.  */
243
244 struct frame_id
245 get_frame_id (struct frame_info *fi)
246 {
247   if (fi == NULL)
248     {
249       return null_frame_id;
250     }
251   if (!fi->this_id.p)
252     {
253       if (frame_debug)
254         fprintf_unfiltered (gdb_stdlog, "{ get_frame_id (fi=%d) ",
255                             fi->level);
256       /* Find the unwinder.  */
257       if (fi->unwind == NULL)
258         fi->unwind = frame_unwind_find_by_frame (fi, &fi->prologue_cache);
259       /* Find THIS frame's ID.  */
260       fi->unwind->this_id (fi, &fi->prologue_cache, &fi->this_id.value);
261       fi->this_id.p = 1;
262       if (frame_debug)
263         {
264           fprintf_unfiltered (gdb_stdlog, "-> ");
265           fprint_frame_id (gdb_stdlog, fi->this_id.value);
266           fprintf_unfiltered (gdb_stdlog, " }\n");
267         }
268     }
269   return fi->this_id.value;
270 }
271
272 struct frame_id
273 frame_unwind_id (struct frame_info *next_frame)
274 {
275   /* Use prev_frame, and not get_prev_frame.  The latter will truncate
276      the frame chain, leading to this function unintentionally
277      returning a null_frame_id (e.g., when a caller requests the frame
278      ID of "main()"s caller.  */
279   return get_frame_id (get_prev_frame_1 (next_frame));
280 }
281
282 const struct frame_id null_frame_id; /* All zeros.  */
283
284 struct frame_id
285 frame_id_build_special (CORE_ADDR stack_addr, CORE_ADDR code_addr,
286                         CORE_ADDR special_addr)
287 {
288   struct frame_id id = null_frame_id;
289   id.stack_addr = stack_addr;
290   id.stack_addr_p = 1;
291   id.code_addr = code_addr;
292   id.code_addr_p = 1;
293   id.special_addr = special_addr;
294   id.special_addr_p = 1;
295   return id;
296 }
297
298 struct frame_id
299 frame_id_build (CORE_ADDR stack_addr, CORE_ADDR code_addr)
300 {
301   struct frame_id id = null_frame_id;
302   id.stack_addr = stack_addr;
303   id.stack_addr_p = 1;
304   id.code_addr = code_addr;
305   id.code_addr_p = 1;
306   return id;
307 }
308
309 struct frame_id
310 frame_id_build_wild (CORE_ADDR stack_addr)
311 {
312   struct frame_id id = null_frame_id;
313   id.stack_addr = stack_addr;
314   id.stack_addr_p = 1;
315   return id;
316 }
317
318 int
319 frame_id_p (struct frame_id l)
320 {
321   int p;
322   /* The frame is valid iff it has a valid stack address.  */
323   p = l.stack_addr_p;
324   if (frame_debug)
325     {
326       fprintf_unfiltered (gdb_stdlog, "{ frame_id_p (l=");
327       fprint_frame_id (gdb_stdlog, l);
328       fprintf_unfiltered (gdb_stdlog, ") -> %d }\n", p);
329     }
330   return p;
331 }
332
333 int
334 frame_id_eq (struct frame_id l, struct frame_id r)
335 {
336   int eq;
337   if (!l.stack_addr_p || !r.stack_addr_p)
338     /* Like a NaN, if either ID is invalid, the result is false.
339        Note that a frame ID is invalid iff it is the null frame ID.  */
340     eq = 0;
341   else if (l.stack_addr != r.stack_addr)
342     /* If .stack addresses are different, the frames are different.  */
343     eq = 0;
344   else if (!l.code_addr_p || !r.code_addr_p)
345     /* An invalid code addr is a wild card, always succeed.  */
346     eq = 1;
347   else if (l.code_addr != r.code_addr)
348     /* If .code addresses are different, the frames are different.  */
349     eq = 0;
350   else if (!l.special_addr_p || !r.special_addr_p)
351     /* An invalid special addr is a wild card (or unused), always succeed.  */
352     eq = 1;
353   else if (l.special_addr == r.special_addr)
354     /* Frames are equal.  */
355     eq = 1;
356   else
357     /* No luck.  */
358     eq = 0;
359   if (frame_debug)
360     {
361       fprintf_unfiltered (gdb_stdlog, "{ frame_id_eq (l=");
362       fprint_frame_id (gdb_stdlog, l);
363       fprintf_unfiltered (gdb_stdlog, ",r=");
364       fprint_frame_id (gdb_stdlog, r);
365       fprintf_unfiltered (gdb_stdlog, ") -> %d }\n", eq);
366     }
367   return eq;
368 }
369
370 int
371 frame_id_inner (struct gdbarch *gdbarch, struct frame_id l, struct frame_id r)
372 {
373   int inner;
374   if (!l.stack_addr_p || !r.stack_addr_p)
375     /* Like NaN, any operation involving an invalid ID always fails.  */
376     inner = 0;
377   else
378     /* Only return non-zero when strictly inner than.  Note that, per
379        comment in "frame.h", there is some fuzz here.  Frameless
380        functions are not strictly inner than (same .stack but
381        different .code and/or .special address).  */
382     inner = gdbarch_inner_than (gdbarch, l.stack_addr, r.stack_addr);
383   if (frame_debug)
384     {
385       fprintf_unfiltered (gdb_stdlog, "{ frame_id_inner (l=");
386       fprint_frame_id (gdb_stdlog, l);
387       fprintf_unfiltered (gdb_stdlog, ",r=");
388       fprint_frame_id (gdb_stdlog, r);
389       fprintf_unfiltered (gdb_stdlog, ") -> %d }\n", inner);
390     }
391   return inner;
392 }
393
394 struct frame_info *
395 frame_find_by_id (struct frame_id id)
396 {
397   struct frame_info *frame;
398
399   /* ZERO denotes the null frame, let the caller decide what to do
400      about it.  Should it instead return get_current_frame()?  */
401   if (!frame_id_p (id))
402     return NULL;
403
404   for (frame = get_current_frame ();
405        frame != NULL;
406        frame = get_prev_frame (frame))
407     {
408       struct frame_id this = get_frame_id (frame);
409       if (frame_id_eq (id, this))
410         /* An exact match.  */
411         return frame;
412       if (frame_id_inner (get_frame_arch (frame), id, this))
413         /* Gone to far.  */
414         return NULL;
415       /* Either we're not yet gone far enough out along the frame
416          chain (inner(this,id)), or we're comparing frameless functions
417          (same .base, different .func, no test available).  Struggle
418          on until we've definitly gone to far.  */
419     }
420   return NULL;
421 }
422
423 CORE_ADDR
424 frame_pc_unwind (struct frame_info *this_frame)
425 {
426   if (!this_frame->prev_pc.p)
427     {
428       CORE_ADDR pc;
429       if (gdbarch_unwind_pc_p (get_frame_arch (this_frame)))
430         {
431           /* The right way.  The `pure' way.  The one true way.  This
432              method depends solely on the register-unwind code to
433              determine the value of registers in THIS frame, and hence
434              the value of this frame's PC (resume address).  A typical
435              implementation is no more than:
436            
437              frame_unwind_register (this_frame, ISA_PC_REGNUM, buf);
438              return extract_unsigned_integer (buf, size of ISA_PC_REGNUM);
439
440              Note: this method is very heavily dependent on a correct
441              register-unwind implementation, it pays to fix that
442              method first; this method is frame type agnostic, since
443              it only deals with register values, it works with any
444              frame.  This is all in stark contrast to the old
445              FRAME_SAVED_PC which would try to directly handle all the
446              different ways that a PC could be unwound.  */
447           pc = gdbarch_unwind_pc (get_frame_arch (this_frame), this_frame);
448         }
449       else
450         internal_error (__FILE__, __LINE__, _("No unwind_pc method"));
451       this_frame->prev_pc.value = pc;
452       this_frame->prev_pc.p = 1;
453       if (frame_debug)
454         fprintf_unfiltered (gdb_stdlog,
455                             "{ frame_pc_unwind (this_frame=%d) -> 0x%s }\n",
456                             this_frame->level,
457                             paddr_nz (this_frame->prev_pc.value));
458     }
459   return this_frame->prev_pc.value;
460 }
461
462 CORE_ADDR
463 frame_func_unwind (struct frame_info *fi, enum frame_type this_type)
464 {
465   if (!fi->prev_func.p)
466     {
467       /* Make certain that this, and not the adjacent, function is
468          found.  */
469       CORE_ADDR addr_in_block = frame_unwind_address_in_block (fi, this_type);
470       fi->prev_func.p = 1;
471       fi->prev_func.addr = get_pc_function_start (addr_in_block);
472       if (frame_debug)
473         fprintf_unfiltered (gdb_stdlog,
474                             "{ frame_func_unwind (fi=%d) -> 0x%s }\n",
475                             fi->level, paddr_nz (fi->prev_func.addr));
476     }
477   return fi->prev_func.addr;
478 }
479
480 CORE_ADDR
481 get_frame_func (struct frame_info *fi)
482 {
483   return frame_func_unwind (fi->next, get_frame_type (fi));
484 }
485
486 static int
487 do_frame_register_read (void *src, int regnum, gdb_byte *buf)
488 {
489   return frame_register_read (src, regnum, buf);
490 }
491
492 struct regcache *
493 frame_save_as_regcache (struct frame_info *this_frame)
494 {
495   struct regcache *regcache = regcache_xmalloc (get_frame_arch (this_frame));
496   struct cleanup *cleanups = make_cleanup_regcache_xfree (regcache);
497   regcache_save (regcache, do_frame_register_read, this_frame);
498   discard_cleanups (cleanups);
499   return regcache;
500 }
501
502 void
503 frame_pop (struct frame_info *this_frame)
504 {
505   struct frame_info *prev_frame;
506   struct regcache *scratch;
507   struct cleanup *cleanups;
508
509   /* Ensure that we have a frame to pop to.  */
510   prev_frame = get_prev_frame_1 (this_frame);
511
512   if (!prev_frame)
513     error (_("Cannot pop the initial frame."));
514
515   /* Make a copy of all the register values unwound from this frame.
516      Save them in a scratch buffer so that there isn't a race between
517      trying to extract the old values from the current regcache while
518      at the same time writing new values into that same cache.  */
519   scratch = frame_save_as_regcache (prev_frame);
520   cleanups = make_cleanup_regcache_xfree (scratch);
521
522   /* FIXME: cagney/2003-03-16: It should be possible to tell the
523      target's register cache that it is about to be hit with a burst
524      register transfer and that the sequence of register writes should
525      be batched.  The pair target_prepare_to_store() and
526      target_store_registers() kind of suggest this functionality.
527      Unfortunately, they don't implement it.  Their lack of a formal
528      definition can lead to targets writing back bogus values
529      (arguably a bug in the target code mind).  */
530   /* Now copy those saved registers into the current regcache.
531      Here, regcache_cpy() calls regcache_restore().  */
532   regcache_cpy (get_current_regcache (), scratch);
533   do_cleanups (cleanups);
534
535   /* We've made right mess of GDB's local state, just discard
536      everything.  */
537   reinit_frame_cache ();
538 }
539
540 void
541 frame_register_unwind (struct frame_info *frame, int regnum,
542                        int *optimizedp, enum lval_type *lvalp,
543                        CORE_ADDR *addrp, int *realnump, gdb_byte *bufferp)
544 {
545   struct value *value;
546
547   /* Require all but BUFFERP to be valid.  A NULL BUFFERP indicates
548      that the value proper does not need to be fetched.  */
549   gdb_assert (optimizedp != NULL);
550   gdb_assert (lvalp != NULL);
551   gdb_assert (addrp != NULL);
552   gdb_assert (realnump != NULL);
553   /* gdb_assert (bufferp != NULL); */
554
555   value = frame_unwind_register_value (frame, regnum);
556
557   gdb_assert (value != NULL);
558
559   *optimizedp = value_optimized_out (value);
560   *lvalp = VALUE_LVAL (value);
561   *addrp = VALUE_ADDRESS (value);
562   *realnump = VALUE_REGNUM (value);
563
564   if (bufferp)
565     memcpy (bufferp, value_contents_all (value),
566             TYPE_LENGTH (value_type (value)));
567
568   /* Dispose of the new value.  This prevents watchpoints from
569      trying to watch the saved frame pointer.  */
570   release_value (value);
571   value_free (value);
572 }
573
574 void
575 frame_register (struct frame_info *frame, int regnum,
576                 int *optimizedp, enum lval_type *lvalp,
577                 CORE_ADDR *addrp, int *realnump, gdb_byte *bufferp)
578 {
579   /* Require all but BUFFERP to be valid.  A NULL BUFFERP indicates
580      that the value proper does not need to be fetched.  */
581   gdb_assert (optimizedp != NULL);
582   gdb_assert (lvalp != NULL);
583   gdb_assert (addrp != NULL);
584   gdb_assert (realnump != NULL);
585   /* gdb_assert (bufferp != NULL); */
586
587   /* Obtain the register value by unwinding the register from the next
588      (more inner frame).  */
589   gdb_assert (frame != NULL && frame->next != NULL);
590   frame_register_unwind (frame->next, regnum, optimizedp, lvalp, addrp,
591                          realnump, bufferp);
592 }
593
594 void
595 frame_unwind_register (struct frame_info *frame, int regnum, gdb_byte *buf)
596 {
597   int optimized;
598   CORE_ADDR addr;
599   int realnum;
600   enum lval_type lval;
601   frame_register_unwind (frame, regnum, &optimized, &lval, &addr,
602                          &realnum, buf);
603 }
604
605 void
606 get_frame_register (struct frame_info *frame,
607                     int regnum, gdb_byte *buf)
608 {
609   frame_unwind_register (frame->next, regnum, buf);
610 }
611
612 struct value *
613 frame_unwind_register_value (struct frame_info *frame, int regnum)
614 {
615   struct value *value;
616
617   gdb_assert (frame != NULL);
618
619   if (frame_debug)
620     {
621       fprintf_unfiltered (gdb_stdlog, "\
622 { frame_unwind_register_value (frame=%d,regnum=%d(%s),...) ",
623                           frame->level, regnum,
624                           frame_map_regnum_to_name (frame, regnum));
625     }
626
627   /* Find the unwinder.  */
628   if (frame->unwind == NULL)
629     frame->unwind = frame_unwind_find_by_frame (frame, &frame->prologue_cache);
630
631   /* Ask this frame to unwind its register.  */
632   value = frame->unwind->prev_register (frame, &frame->prologue_cache, regnum);
633
634   if (frame_debug)
635     {
636       fprintf_unfiltered (gdb_stdlog, "->");
637       if (value_optimized_out (value))
638         fprintf_unfiltered (gdb_stdlog, " optimized out");
639       else
640         {
641           if (VALUE_LVAL (value) == lval_register)
642             fprintf_unfiltered (gdb_stdlog, " register=%d",
643                                 VALUE_REGNUM (value));
644           else if (VALUE_LVAL (value) == lval_memory)
645             fprintf_unfiltered (gdb_stdlog, " address=0x%s",
646                                 paddr_nz (VALUE_ADDRESS (value)));
647           else
648             fprintf_unfiltered (gdb_stdlog, " computed");
649
650           if (value_lazy (value))
651             fprintf_unfiltered (gdb_stdlog, " lazy");
652           else
653             {
654               int i;
655               const gdb_byte *buf = value_contents (value);
656
657               fprintf_unfiltered (gdb_stdlog, " bytes=");
658               fprintf_unfiltered (gdb_stdlog, "[");
659               for (i = 0; i < register_size (get_frame_arch (frame), regnum); i++)
660                 fprintf_unfiltered (gdb_stdlog, "%02x", buf[i]);
661               fprintf_unfiltered (gdb_stdlog, "]");
662             }
663         }
664
665       fprintf_unfiltered (gdb_stdlog, " }\n");
666     }
667
668   return value;
669 }
670
671 struct value *
672 get_frame_register_value (struct frame_info *frame, int regnum)
673 {
674   return frame_unwind_register_value (frame->next, regnum);
675 }
676
677 LONGEST
678 frame_unwind_register_signed (struct frame_info *frame, int regnum)
679 {
680   gdb_byte buf[MAX_REGISTER_SIZE];
681   frame_unwind_register (frame, regnum, buf);
682   return extract_signed_integer (buf, register_size (get_frame_arch (frame),
683                                                      regnum));
684 }
685
686 LONGEST
687 get_frame_register_signed (struct frame_info *frame, int regnum)
688 {
689   return frame_unwind_register_signed (frame->next, regnum);
690 }
691
692 ULONGEST
693 frame_unwind_register_unsigned (struct frame_info *frame, int regnum)
694 {
695   gdb_byte buf[MAX_REGISTER_SIZE];
696   frame_unwind_register (frame, regnum, buf);
697   return extract_unsigned_integer (buf, register_size (get_frame_arch (frame),
698                                                        regnum));
699 }
700
701 ULONGEST
702 get_frame_register_unsigned (struct frame_info *frame, int regnum)
703 {
704   return frame_unwind_register_unsigned (frame->next, regnum);
705 }
706
707 void
708 put_frame_register (struct frame_info *frame, int regnum,
709                     const gdb_byte *buf)
710 {
711   struct gdbarch *gdbarch = get_frame_arch (frame);
712   int realnum;
713   int optim;
714   enum lval_type lval;
715   CORE_ADDR addr;
716   frame_register (frame, regnum, &optim, &lval, &addr, &realnum, NULL);
717   if (optim)
718     error (_("Attempt to assign to a value that was optimized out."));
719   switch (lval)
720     {
721     case lval_memory:
722       {
723         /* FIXME: write_memory doesn't yet take constant buffers.
724            Arrrg!  */
725         gdb_byte tmp[MAX_REGISTER_SIZE];
726         memcpy (tmp, buf, register_size (gdbarch, regnum));
727         write_memory (addr, tmp, register_size (gdbarch, regnum));
728         break;
729       }
730     case lval_register:
731       regcache_cooked_write (get_current_regcache (), realnum, buf);
732       break;
733     default:
734       error (_("Attempt to assign to an unmodifiable value."));
735     }
736 }
737
738 /* frame_register_read ()
739
740    Find and return the value of REGNUM for the specified stack frame.
741    The number of bytes copied is REGISTER_SIZE (REGNUM).
742
743    Returns 0 if the register value could not be found.  */
744
745 int
746 frame_register_read (struct frame_info *frame, int regnum,
747                      gdb_byte *myaddr)
748 {
749   int optimized;
750   enum lval_type lval;
751   CORE_ADDR addr;
752   int realnum;
753   frame_register (frame, regnum, &optimized, &lval, &addr, &realnum, myaddr);
754
755   return !optimized;
756 }
757
758 int
759 get_frame_register_bytes (struct frame_info *frame, int regnum,
760                           CORE_ADDR offset, int len, gdb_byte *myaddr)
761 {
762   struct gdbarch *gdbarch = get_frame_arch (frame);
763
764   /* Skip registers wholly inside of OFFSET.  */
765   while (offset >= register_size (gdbarch, regnum))
766     {
767       offset -= register_size (gdbarch, regnum);
768       regnum++;
769     }
770
771   /* Copy the data.  */
772   while (len > 0)
773     {
774       int curr_len = register_size (gdbarch, regnum) - offset;
775       if (curr_len > len)
776         curr_len = len;
777
778       if (curr_len == register_size (gdbarch, regnum))
779         {
780           if (!frame_register_read (frame, regnum, myaddr))
781             return 0;
782         }
783       else
784         {
785           gdb_byte buf[MAX_REGISTER_SIZE];
786           if (!frame_register_read (frame, regnum, buf))
787             return 0;
788           memcpy (myaddr, buf + offset, curr_len);
789         }
790
791       myaddr += curr_len;
792       len -= curr_len;
793       offset = 0;
794       regnum++;
795     }
796
797   return 1;
798 }
799
800 void
801 put_frame_register_bytes (struct frame_info *frame, int regnum,
802                           CORE_ADDR offset, int len, const gdb_byte *myaddr)
803 {
804   struct gdbarch *gdbarch = get_frame_arch (frame);
805
806   /* Skip registers wholly inside of OFFSET.  */
807   while (offset >= register_size (gdbarch, regnum))
808     {
809       offset -= register_size (gdbarch, regnum);
810       regnum++;
811     }
812
813   /* Copy the data.  */
814   while (len > 0)
815     {
816       int curr_len = register_size (gdbarch, regnum) - offset;
817       if (curr_len > len)
818         curr_len = len;
819
820       if (curr_len == register_size (gdbarch, regnum))
821         {
822           put_frame_register (frame, regnum, myaddr);
823         }
824       else
825         {
826           gdb_byte buf[MAX_REGISTER_SIZE];
827           frame_register_read (frame, regnum, buf);
828           memcpy (buf + offset, myaddr, curr_len);
829           put_frame_register (frame, regnum, buf);
830         }
831
832       myaddr += curr_len;
833       len -= curr_len;
834       offset = 0;
835       regnum++;
836     }
837 }
838
839 /* Map between a frame register number and its name.  A frame register
840    space is a superset of the cooked register space --- it also
841    includes builtin registers.  */
842
843 int
844 frame_map_name_to_regnum (struct frame_info *frame, const char *name, int len)
845 {
846   return user_reg_map_name_to_regnum (get_frame_arch (frame), name, len);
847 }
848
849 const char *
850 frame_map_regnum_to_name (struct frame_info *frame, int regnum)
851 {
852   return user_reg_map_regnum_to_name (get_frame_arch (frame), regnum);
853 }
854
855 /* Create a sentinel frame.  */
856
857 static struct frame_info *
858 create_sentinel_frame (struct regcache *regcache)
859 {
860   struct frame_info *frame = FRAME_OBSTACK_ZALLOC (struct frame_info);
861   frame->level = -1;
862   /* Explicitly initialize the sentinel frame's cache.  Provide it
863      with the underlying regcache.  In the future additional
864      information, such as the frame's thread will be added.  */
865   frame->prologue_cache = sentinel_frame_cache (regcache);
866   /* For the moment there is only one sentinel frame implementation.  */
867   frame->unwind = sentinel_frame_unwind;
868   /* Link this frame back to itself.  The frame is self referential
869      (the unwound PC is the same as the pc), so make it so.  */
870   frame->next = frame;
871   /* Make the sentinel frame's ID valid, but invalid.  That way all
872      comparisons with it should fail.  */
873   frame->this_id.p = 1;
874   frame->this_id.value = null_frame_id;
875   if (frame_debug)
876     {
877       fprintf_unfiltered (gdb_stdlog, "{ create_sentinel_frame (...) -> ");
878       fprint_frame (gdb_stdlog, frame);
879       fprintf_unfiltered (gdb_stdlog, " }\n");
880     }
881   return frame;
882 }
883
884 /* Info about the innermost stack frame (contents of FP register) */
885
886 static struct frame_info *current_frame;
887
888 /* Cache for frame addresses already read by gdb.  Valid only while
889    inferior is stopped.  Control variables for the frame cache should
890    be local to this module.  */
891
892 static struct obstack frame_cache_obstack;
893
894 void *
895 frame_obstack_zalloc (unsigned long size)
896 {
897   void *data = obstack_alloc (&frame_cache_obstack, size);
898   memset (data, 0, size);
899   return data;
900 }
901
902 /* Return the innermost (currently executing) stack frame.  This is
903    split into two functions.  The function unwind_to_current_frame()
904    is wrapped in catch exceptions so that, even when the unwind of the
905    sentinel frame fails, the function still returns a stack frame.  */
906
907 static int
908 unwind_to_current_frame (struct ui_out *ui_out, void *args)
909 {
910   struct frame_info *frame = get_prev_frame (args);
911   /* A sentinel frame can fail to unwind, e.g., because its PC value
912      lands in somewhere like start.  */
913   if (frame == NULL)
914     return 1;
915   current_frame = frame;
916   return 0;
917 }
918
919 struct frame_info *
920 get_current_frame (void)
921 {
922   /* First check, and report, the lack of registers.  Having GDB
923      report "No stack!" or "No memory" when the target doesn't even
924      have registers is very confusing.  Besides, "printcmd.exp"
925      explicitly checks that ``print $pc'' with no registers prints "No
926      registers".  */
927   if (!target_has_registers)
928     error (_("No registers."));
929   if (!target_has_stack)
930     error (_("No stack."));
931   if (!target_has_memory)
932     error (_("No memory."));
933   if (current_frame == NULL)
934     {
935       struct frame_info *sentinel_frame =
936         create_sentinel_frame (get_current_regcache ());
937       if (catch_exceptions (uiout, unwind_to_current_frame, sentinel_frame,
938                             RETURN_MASK_ERROR) != 0)
939         {
940           /* Oops! Fake a current frame?  Is this useful?  It has a PC
941              of zero, for instance.  */
942           current_frame = sentinel_frame;
943         }
944     }
945   return current_frame;
946 }
947
948 /* The "selected" stack frame is used by default for local and arg
949    access.  May be zero, for no selected frame.  */
950
951 static struct frame_info *selected_frame;
952
953 /* Return the selected frame.  Always non-NULL (unless there isn't an
954    inferior sufficient for creating a frame) in which case an error is
955    thrown.  */
956
957 struct frame_info *
958 get_selected_frame (const char *message)
959 {
960   if (selected_frame == NULL)
961     {
962       if (message != NULL && (!target_has_registers
963                               || !target_has_stack
964                               || !target_has_memory))
965         error (("%s"), message);
966       /* Hey!  Don't trust this.  It should really be re-finding the
967          last selected frame of the currently selected thread.  This,
968          though, is better than nothing.  */
969       select_frame (get_current_frame ());
970     }
971   /* There is always a frame.  */
972   gdb_assert (selected_frame != NULL);
973   return selected_frame;
974 }
975
976 /* This is a variant of get_selected_frame() which can be called when
977    the inferior does not have a frame; in that case it will return
978    NULL instead of calling error().  */
979
980 struct frame_info *
981 deprecated_safe_get_selected_frame (void)
982 {
983   if (!target_has_registers || !target_has_stack || !target_has_memory)
984     return NULL;
985   return get_selected_frame (NULL);
986 }
987
988 /* Select frame FI (or NULL - to invalidate the current frame).  */
989
990 void
991 select_frame (struct frame_info *fi)
992 {
993   struct symtab *s;
994
995   selected_frame = fi;
996   /* NOTE: cagney/2002-05-04: FI can be NULL.  This occurs when the
997      frame is being invalidated.  */
998   if (deprecated_selected_frame_level_changed_hook)
999     deprecated_selected_frame_level_changed_hook (frame_relative_level (fi));
1000
1001   /* FIXME: kseitz/2002-08-28: It would be nice to call
1002      selected_frame_level_changed_event() right here, but due to limitations
1003      in the current interfaces, we would end up flooding UIs with events
1004      because select_frame() is used extensively internally.
1005
1006      Once we have frame-parameterized frame (and frame-related) commands,
1007      the event notification can be moved here, since this function will only
1008      be called when the user's selected frame is being changed. */
1009
1010   /* Ensure that symbols for this frame are read in.  Also, determine the
1011      source language of this frame, and switch to it if desired.  */
1012   if (fi)
1013     {
1014       /* We retrieve the frame's symtab by using the frame PC.  However
1015          we cannot use the frame PC as-is, because it usually points to
1016          the instruction following the "call", which is sometimes the
1017          first instruction of another function.  So we rely on
1018          get_frame_address_in_block() which provides us with a PC which
1019          is guaranteed to be inside the frame's code block.  */
1020       s = find_pc_symtab (get_frame_address_in_block (fi));
1021       if (s
1022           && s->language != current_language->la_language
1023           && s->language != language_unknown
1024           && language_mode == language_mode_auto)
1025         {
1026           set_language (s->language);
1027         }
1028     }
1029 }
1030         
1031 /* Create an arbitrary (i.e. address specified by user) or innermost frame.
1032    Always returns a non-NULL value.  */
1033
1034 struct frame_info *
1035 create_new_frame (CORE_ADDR addr, CORE_ADDR pc)
1036 {
1037   struct frame_info *fi;
1038
1039   if (frame_debug)
1040     {
1041       fprintf_unfiltered (gdb_stdlog,
1042                           "{ create_new_frame (addr=0x%s, pc=0x%s) ",
1043                           paddr_nz (addr), paddr_nz (pc));
1044     }
1045
1046   fi = FRAME_OBSTACK_ZALLOC (struct frame_info);
1047
1048   fi->next = create_sentinel_frame (get_current_regcache ());
1049
1050   /* Select/initialize both the unwind function and the frame's type
1051      based on the PC.  */
1052   fi->unwind = frame_unwind_find_by_frame (fi, &fi->prologue_cache);
1053
1054   fi->this_id.p = 1;
1055   deprecated_update_frame_base_hack (fi, addr);
1056   deprecated_update_frame_pc_hack (fi, pc);
1057
1058   if (frame_debug)
1059     {
1060       fprintf_unfiltered (gdb_stdlog, "-> ");
1061       fprint_frame (gdb_stdlog, fi);
1062       fprintf_unfiltered (gdb_stdlog, " }\n");
1063     }
1064
1065   return fi;
1066 }
1067
1068 /* Return the frame that THIS_FRAME calls (NULL if THIS_FRAME is the
1069    innermost frame).  Be careful to not fall off the bottom of the
1070    frame chain and onto the sentinel frame.  */
1071
1072 struct frame_info *
1073 get_next_frame (struct frame_info *this_frame)
1074 {
1075   if (this_frame->level > 0)
1076     return this_frame->next;
1077   else
1078     return NULL;
1079 }
1080
1081 /* Observer for the target_changed event.  */
1082
1083 void
1084 frame_observer_target_changed (struct target_ops *target)
1085 {
1086   reinit_frame_cache ();
1087 }
1088
1089 /* Flush the entire frame cache.  */
1090
1091 void
1092 reinit_frame_cache (void)
1093 {
1094   struct frame_info *fi;
1095
1096   /* Tear down all frame caches.  */
1097   for (fi = current_frame; fi != NULL; fi = fi->prev)
1098     {
1099       if (fi->prologue_cache && fi->unwind->dealloc_cache)
1100         fi->unwind->dealloc_cache (fi, fi->prologue_cache);
1101       if (fi->base_cache && fi->base->unwind->dealloc_cache)
1102         fi->base->unwind->dealloc_cache (fi, fi->base_cache);
1103     }
1104
1105   /* Since we can't really be sure what the first object allocated was */
1106   obstack_free (&frame_cache_obstack, 0);
1107   obstack_init (&frame_cache_obstack);
1108
1109   if (current_frame != NULL)
1110     annotate_frames_invalid ();
1111
1112   current_frame = NULL;         /* Invalidate cache */
1113   select_frame (NULL);
1114   if (frame_debug)
1115     fprintf_unfiltered (gdb_stdlog, "{ reinit_frame_cache () }\n");
1116 }
1117
1118 /* Find where a register is saved (in memory or another register).
1119    The result of frame_register_unwind is just where it is saved
1120    relative to this particular frame.  */
1121
1122 static void
1123 frame_register_unwind_location (struct frame_info *this_frame, int regnum,
1124                                 int *optimizedp, enum lval_type *lvalp,
1125                                 CORE_ADDR *addrp, int *realnump)
1126 {
1127   gdb_assert (this_frame == NULL || this_frame->level >= 0);
1128
1129   while (this_frame != NULL)
1130     {
1131       frame_register_unwind (this_frame, regnum, optimizedp, lvalp,
1132                              addrp, realnump, NULL);
1133
1134       if (*optimizedp)
1135         break;
1136
1137       if (*lvalp != lval_register)
1138         break;
1139
1140       regnum = *realnump;
1141       this_frame = get_next_frame (this_frame);
1142     }
1143 }
1144
1145 /* Return a "struct frame_info" corresponding to the frame that called
1146    THIS_FRAME.  Returns NULL if there is no such frame.
1147
1148    Unlike get_prev_frame, this function always tries to unwind the
1149    frame.  */
1150
1151 static struct frame_info *
1152 get_prev_frame_1 (struct frame_info *this_frame)
1153 {
1154   struct frame_info *prev_frame;
1155   struct frame_id this_id;
1156   struct gdbarch *gdbarch;
1157
1158   gdb_assert (this_frame != NULL);
1159   gdbarch = get_frame_arch (this_frame);
1160
1161   if (frame_debug)
1162     {
1163       fprintf_unfiltered (gdb_stdlog, "{ get_prev_frame_1 (this_frame=");
1164       if (this_frame != NULL)
1165         fprintf_unfiltered (gdb_stdlog, "%d", this_frame->level);
1166       else
1167         fprintf_unfiltered (gdb_stdlog, "<NULL>");
1168       fprintf_unfiltered (gdb_stdlog, ") ");
1169     }
1170
1171   /* Only try to do the unwind once.  */
1172   if (this_frame->prev_p)
1173     {
1174       if (frame_debug)
1175         {
1176           fprintf_unfiltered (gdb_stdlog, "-> ");
1177           fprint_frame (gdb_stdlog, this_frame->prev);
1178           fprintf_unfiltered (gdb_stdlog, " // cached \n");
1179         }
1180       return this_frame->prev;
1181     }
1182   this_frame->prev_p = 1;
1183   this_frame->stop_reason = UNWIND_NO_REASON;
1184
1185   /* Check that this frame's ID was valid.  If it wasn't, don't try to
1186      unwind to the prev frame.  Be careful to not apply this test to
1187      the sentinel frame.  */
1188   this_id = get_frame_id (this_frame);
1189   if (this_frame->level >= 0 && !frame_id_p (this_id))
1190     {
1191       if (frame_debug)
1192         {
1193           fprintf_unfiltered (gdb_stdlog, "-> ");
1194           fprint_frame (gdb_stdlog, NULL);
1195           fprintf_unfiltered (gdb_stdlog, " // this ID is NULL }\n");
1196         }
1197       this_frame->stop_reason = UNWIND_NULL_ID;
1198       return NULL;
1199     }
1200
1201   /* Check that this frame's ID isn't inner to (younger, below, next)
1202      the next frame.  This happens when a frame unwind goes backwards.
1203      Exclude signal trampolines (due to sigaltstack the frame ID can
1204      go backwards) and sentinel frames (the test is meaningless).  */
1205   if (this_frame->next->level >= 0
1206       && this_frame->next->unwind->type != SIGTRAMP_FRAME
1207       && frame_id_inner (get_frame_arch (this_frame), this_id,
1208                          get_frame_id (this_frame->next)))
1209     {
1210       if (frame_debug)
1211         {
1212           fprintf_unfiltered (gdb_stdlog, "-> ");
1213           fprint_frame (gdb_stdlog, NULL);
1214           fprintf_unfiltered (gdb_stdlog, " // this frame ID is inner }\n");
1215         }
1216       this_frame->stop_reason = UNWIND_INNER_ID;
1217       return NULL;
1218     }
1219
1220   /* Check that this and the next frame are not identical.  If they
1221      are, there is most likely a stack cycle.  As with the inner-than
1222      test above, avoid comparing the inner-most and sentinel frames.  */
1223   if (this_frame->level > 0
1224       && frame_id_eq (this_id, get_frame_id (this_frame->next)))
1225     {
1226       if (frame_debug)
1227         {
1228           fprintf_unfiltered (gdb_stdlog, "-> ");
1229           fprint_frame (gdb_stdlog, NULL);
1230           fprintf_unfiltered (gdb_stdlog, " // this frame has same ID }\n");
1231         }
1232       this_frame->stop_reason = UNWIND_SAME_ID;
1233       return NULL;
1234     }
1235
1236   /* Check that this and the next frame do not unwind the PC register
1237      to the same memory location.  If they do, then even though they
1238      have different frame IDs, the new frame will be bogus; two
1239      functions can't share a register save slot for the PC.  This can
1240      happen when the prologue analyzer finds a stack adjustment, but
1241      no PC save.
1242
1243      This check does assume that the "PC register" is roughly a
1244      traditional PC, even if the gdbarch_unwind_pc method adjusts
1245      it (we do not rely on the value, only on the unwound PC being
1246      dependent on this value).  A potential improvement would be
1247      to have the frame prev_pc method and the gdbarch unwind_pc
1248      method set the same lval and location information as
1249      frame_register_unwind.  */
1250   if (this_frame->level > 0
1251       && gdbarch_pc_regnum (gdbarch) >= 0
1252       && get_frame_type (this_frame) == NORMAL_FRAME
1253       && get_frame_type (this_frame->next) == NORMAL_FRAME)
1254     {
1255       int optimized, realnum, nrealnum;
1256       enum lval_type lval, nlval;
1257       CORE_ADDR addr, naddr;
1258
1259       frame_register_unwind_location (this_frame,
1260                                       gdbarch_pc_regnum (gdbarch),
1261                                       &optimized, &lval, &addr, &realnum);
1262       frame_register_unwind_location (get_next_frame (this_frame),
1263                                       gdbarch_pc_regnum (gdbarch),
1264                                       &optimized, &nlval, &naddr, &nrealnum);
1265
1266       if ((lval == lval_memory && lval == nlval && addr == naddr)
1267           || (lval == lval_register && lval == nlval && realnum == nrealnum))
1268         {
1269           if (frame_debug)
1270             {
1271               fprintf_unfiltered (gdb_stdlog, "-> ");
1272               fprint_frame (gdb_stdlog, NULL);
1273               fprintf_unfiltered (gdb_stdlog, " // no saved PC }\n");
1274             }
1275
1276           this_frame->stop_reason = UNWIND_NO_SAVED_PC;
1277           this_frame->prev = NULL;
1278           return NULL;
1279         }
1280     }
1281
1282   /* Allocate the new frame but do not wire it in to the frame chain.
1283      Some (bad) code in INIT_FRAME_EXTRA_INFO tries to look along
1284      frame->next to pull some fancy tricks (of course such code is, by
1285      definition, recursive).  Try to prevent it.
1286
1287      There is no reason to worry about memory leaks, should the
1288      remainder of the function fail.  The allocated memory will be
1289      quickly reclaimed when the frame cache is flushed, and the `we've
1290      been here before' check above will stop repeated memory
1291      allocation calls.  */
1292   prev_frame = FRAME_OBSTACK_ZALLOC (struct frame_info);
1293   prev_frame->level = this_frame->level + 1;
1294
1295   /* Don't yet compute ->unwind (and hence ->type).  It is computed
1296      on-demand in get_frame_type, frame_register_unwind, and
1297      get_frame_id.  */
1298
1299   /* Don't yet compute the frame's ID.  It is computed on-demand by
1300      get_frame_id().  */
1301
1302   /* The unwound frame ID is validate at the start of this function,
1303      as part of the logic to decide if that frame should be further
1304      unwound, and not here while the prev frame is being created.
1305      Doing this makes it possible for the user to examine a frame that
1306      has an invalid frame ID.
1307
1308      Some very old VAX code noted: [...]  For the sake of argument,
1309      suppose that the stack is somewhat trashed (which is one reason
1310      that "info frame" exists).  So, return 0 (indicating we don't
1311      know the address of the arglist) if we don't know what frame this
1312      frame calls.  */
1313
1314   /* Link it in.  */
1315   this_frame->prev = prev_frame;
1316   prev_frame->next = this_frame;
1317
1318   if (frame_debug)
1319     {
1320       fprintf_unfiltered (gdb_stdlog, "-> ");
1321       fprint_frame (gdb_stdlog, prev_frame);
1322       fprintf_unfiltered (gdb_stdlog, " }\n");
1323     }
1324
1325   return prev_frame;
1326 }
1327
1328 /* Debug routine to print a NULL frame being returned.  */
1329
1330 static void
1331 frame_debug_got_null_frame (struct ui_file *file,
1332                             struct frame_info *this_frame,
1333                             const char *reason)
1334 {
1335   if (frame_debug)
1336     {
1337       fprintf_unfiltered (gdb_stdlog, "{ get_prev_frame (this_frame=");
1338       if (this_frame != NULL)
1339         fprintf_unfiltered (gdb_stdlog, "%d", this_frame->level);
1340       else
1341         fprintf_unfiltered (gdb_stdlog, "<NULL>");
1342       fprintf_unfiltered (gdb_stdlog, ") -> // %s}\n", reason);
1343     }
1344 }
1345
1346 /* Is this (non-sentinel) frame in the "main"() function?  */
1347
1348 static int
1349 inside_main_func (struct frame_info *this_frame)
1350 {
1351   struct minimal_symbol *msymbol;
1352   CORE_ADDR maddr;
1353
1354   if (symfile_objfile == 0)
1355     return 0;
1356   msymbol = lookup_minimal_symbol (main_name (), NULL, symfile_objfile);
1357   if (msymbol == NULL)
1358     return 0;
1359   /* Make certain that the code, and not descriptor, address is
1360      returned.  */
1361   maddr = gdbarch_convert_from_func_ptr_addr (get_frame_arch (this_frame),
1362                                               SYMBOL_VALUE_ADDRESS (msymbol),
1363                                               &current_target);
1364   return maddr == get_frame_func (this_frame);
1365 }
1366
1367 /* Test whether THIS_FRAME is inside the process entry point function.  */
1368
1369 static int
1370 inside_entry_func (struct frame_info *this_frame)
1371 {
1372   return (get_frame_func (this_frame) == entry_point_address ());
1373 }
1374
1375 /* Return a structure containing various interesting information about
1376    the frame that called THIS_FRAME.  Returns NULL if there is entier
1377    no such frame or the frame fails any of a set of target-independent
1378    condition that should terminate the frame chain (e.g., as unwinding
1379    past main()).
1380
1381    This function should not contain target-dependent tests, such as
1382    checking whether the program-counter is zero.  */
1383
1384 struct frame_info *
1385 get_prev_frame (struct frame_info *this_frame)
1386 {
1387   struct frame_info *prev_frame;
1388
1389   /* Return the inner-most frame, when the caller passes in NULL.  */
1390   /* NOTE: cagney/2002-11-09: Not sure how this would happen.  The
1391      caller should have previously obtained a valid frame using
1392      get_selected_frame() and then called this code - only possibility
1393      I can think of is code behaving badly.
1394
1395      NOTE: cagney/2003-01-10: Talk about code behaving badly.  Check
1396      block_innermost_frame().  It does the sequence: frame = NULL;
1397      while (1) { frame = get_prev_frame (frame); .... }.  Ulgh!  Why
1398      it couldn't be written better, I don't know.
1399
1400      NOTE: cagney/2003-01-11: I suspect what is happening in
1401      block_innermost_frame() is, when the target has no state
1402      (registers, memory, ...), it is still calling this function.  The
1403      assumption being that this function will return NULL indicating
1404      that a frame isn't possible, rather than checking that the target
1405      has state and then calling get_current_frame() and
1406      get_prev_frame().  This is a guess mind.  */
1407   if (this_frame == NULL)
1408     {
1409       /* NOTE: cagney/2002-11-09: There was a code segment here that
1410          would error out when CURRENT_FRAME was NULL.  The comment
1411          that went with it made the claim ...
1412
1413          ``This screws value_of_variable, which just wants a nice
1414          clean NULL return from block_innermost_frame if there are no
1415          frames.  I don't think I've ever seen this message happen
1416          otherwise.  And returning NULL here is a perfectly legitimate
1417          thing to do.''
1418
1419          Per the above, this code shouldn't even be called with a NULL
1420          THIS_FRAME.  */
1421       frame_debug_got_null_frame (gdb_stdlog, this_frame, "this_frame NULL");
1422       return current_frame;
1423     }
1424
1425   /* There is always a frame.  If this assertion fails, suspect that
1426      something should be calling get_selected_frame() or
1427      get_current_frame().  */
1428   gdb_assert (this_frame != NULL);
1429
1430   /* tausq/2004-12-07: Dummy frames are skipped because it doesn't make much
1431      sense to stop unwinding at a dummy frame.  One place where a dummy
1432      frame may have an address "inside_main_func" is on HPUX.  On HPUX, the
1433      pcsqh register (space register for the instruction at the head of the
1434      instruction queue) cannot be written directly; the only way to set it
1435      is to branch to code that is in the target space.  In order to implement
1436      frame dummies on HPUX, the called function is made to jump back to where 
1437      the inferior was when the user function was called.  If gdb was inside 
1438      the main function when we created the dummy frame, the dummy frame will 
1439      point inside the main function.  */
1440   if (this_frame->level >= 0
1441       && get_frame_type (this_frame) != DUMMY_FRAME
1442       && !backtrace_past_main
1443       && inside_main_func (this_frame))
1444     /* Don't unwind past main().  Note, this is done _before_ the
1445        frame has been marked as previously unwound.  That way if the
1446        user later decides to enable unwinds past main(), that will
1447        automatically happen.  */
1448     {
1449       frame_debug_got_null_frame (gdb_stdlog, this_frame, "inside main func");
1450       return NULL;
1451     }
1452
1453   /* If the user's backtrace limit has been exceeded, stop.  We must
1454      add two to the current level; one of those accounts for backtrace_limit
1455      being 1-based and the level being 0-based, and the other accounts for
1456      the level of the new frame instead of the level of the current
1457      frame.  */
1458   if (this_frame->level + 2 > backtrace_limit)
1459     {
1460       frame_debug_got_null_frame (gdb_stdlog, this_frame,
1461                                   "backtrace limit exceeded");
1462       return NULL;
1463     }
1464
1465   /* If we're already inside the entry function for the main objfile,
1466      then it isn't valid.  Don't apply this test to a dummy frame -
1467      dummy frame PCs typically land in the entry func.  Don't apply
1468      this test to the sentinel frame.  Sentinel frames should always
1469      be allowed to unwind.  */
1470   /* NOTE: cagney/2003-07-07: Fixed a bug in inside_main_func() -
1471      wasn't checking for "main" in the minimal symbols.  With that
1472      fixed asm-source tests now stop in "main" instead of halting the
1473      backtrace in weird and wonderful ways somewhere inside the entry
1474      file.  Suspect that tests for inside the entry file/func were
1475      added to work around that (now fixed) case.  */
1476   /* NOTE: cagney/2003-07-15: danielj (if I'm reading it right)
1477      suggested having the inside_entry_func test use the
1478      inside_main_func() msymbol trick (along with entry_point_address()
1479      I guess) to determine the address range of the start function.
1480      That should provide a far better stopper than the current
1481      heuristics.  */
1482   /* NOTE: tausq/2004-10-09: this is needed if, for example, the compiler
1483      applied tail-call optimizations to main so that a function called 
1484      from main returns directly to the caller of main.  Since we don't
1485      stop at main, we should at least stop at the entry point of the
1486      application.  */
1487   if (!backtrace_past_entry
1488       && get_frame_type (this_frame) != DUMMY_FRAME && this_frame->level >= 0
1489       && inside_entry_func (this_frame))
1490     {
1491       frame_debug_got_null_frame (gdb_stdlog, this_frame, "inside entry func");
1492       return NULL;
1493     }
1494
1495   /* Assume that the only way to get a zero PC is through something
1496      like a SIGSEGV or a dummy frame, and hence that NORMAL frames
1497      will never unwind a zero PC.  */
1498   if (this_frame->level > 0
1499       && get_frame_type (this_frame) == NORMAL_FRAME
1500       && get_frame_type (get_next_frame (this_frame)) == NORMAL_FRAME
1501       && get_frame_pc (this_frame) == 0)
1502     {
1503       frame_debug_got_null_frame (gdb_stdlog, this_frame, "zero PC");
1504       return NULL;
1505     }
1506
1507   return get_prev_frame_1 (this_frame);
1508 }
1509
1510 CORE_ADDR
1511 get_frame_pc (struct frame_info *frame)
1512 {
1513   gdb_assert (frame->next != NULL);
1514   return frame_pc_unwind (frame->next);
1515 }
1516
1517 /* Return an address that falls within NEXT_FRAME's caller's code
1518    block, assuming that the caller is a THIS_TYPE frame.  */
1519
1520 CORE_ADDR
1521 frame_unwind_address_in_block (struct frame_info *next_frame,
1522                                enum frame_type this_type)
1523 {
1524   /* A draft address.  */
1525   CORE_ADDR pc = frame_pc_unwind (next_frame);
1526
1527   /* If NEXT_FRAME was called by a signal frame or dummy frame, then
1528      we shold not adjust the unwound PC.  These frames may not call
1529      their next frame in the normal way; the operating system or GDB
1530      may have pushed their resume address manually onto the stack, so
1531      it may be the very first instruction.  Even if the resume address
1532      was not manually pushed, they expect to be returned to.  */
1533   if (this_type != NORMAL_FRAME)
1534     return pc;
1535
1536   /* If THIS frame is not inner most (i.e., NEXT isn't the sentinel),
1537      and NEXT is `normal' (i.e., not a sigtramp, dummy, ....) THIS
1538      frame's PC ends up pointing at the instruction fallowing the
1539      "call".  Adjust that PC value so that it falls on the call
1540      instruction (which, hopefully, falls within THIS frame's code
1541      block).  So far it's proved to be a very good approximation.  See
1542      get_frame_type() for why ->type can't be used.  */
1543   if (next_frame->level >= 0
1544       && get_frame_type (next_frame) == NORMAL_FRAME)
1545     --pc;
1546   return pc;
1547 }
1548
1549 CORE_ADDR
1550 get_frame_address_in_block (struct frame_info *this_frame)
1551 {
1552   return frame_unwind_address_in_block (this_frame->next,
1553                                         get_frame_type (this_frame));
1554 }
1555
1556 static int
1557 pc_notcurrent (struct frame_info *frame)
1558 {
1559   /* If FRAME is not the innermost frame, that normally means that
1560      FRAME->pc points at the return instruction (which is *after* the
1561      call instruction), and we want to get the line containing the
1562      call (because the call is where the user thinks the program is).
1563      However, if the next frame is either a SIGTRAMP_FRAME or a
1564      DUMMY_FRAME, then the next frame will contain a saved interrupt
1565      PC and such a PC indicates the current (rather than next)
1566      instruction/line, consequently, for such cases, want to get the
1567      line containing fi->pc.  */
1568   struct frame_info *next = get_next_frame (frame);
1569   int notcurrent = (next != NULL && get_frame_type (next) == NORMAL_FRAME);
1570   return notcurrent;
1571 }
1572
1573 void
1574 find_frame_sal (struct frame_info *frame, struct symtab_and_line *sal)
1575 {
1576   (*sal) = find_pc_line (get_frame_pc (frame), pc_notcurrent (frame));
1577 }
1578
1579 /* Per "frame.h", return the ``address'' of the frame.  Code should
1580    really be using get_frame_id().  */
1581 CORE_ADDR
1582 get_frame_base (struct frame_info *fi)
1583 {
1584   return get_frame_id (fi).stack_addr;
1585 }
1586
1587 /* High-level offsets into the frame.  Used by the debug info.  */
1588
1589 CORE_ADDR
1590 get_frame_base_address (struct frame_info *fi)
1591 {
1592   if (get_frame_type (fi) != NORMAL_FRAME)
1593     return 0;
1594   if (fi->base == NULL)
1595     fi->base = frame_base_find_by_frame (fi->next);
1596   /* Sneaky: If the low-level unwind and high-level base code share a
1597      common unwinder, let them share the prologue cache.  */
1598   if (fi->base->unwind == fi->unwind)
1599     return fi->base->this_base (fi, &fi->prologue_cache);
1600   return fi->base->this_base (fi, &fi->base_cache);
1601 }
1602
1603 CORE_ADDR
1604 get_frame_locals_address (struct frame_info *fi)
1605 {
1606   void **cache;
1607   if (get_frame_type (fi) != NORMAL_FRAME)
1608     return 0;
1609   /* If there isn't a frame address method, find it.  */
1610   if (fi->base == NULL)
1611     fi->base = frame_base_find_by_frame (fi->next);
1612   /* Sneaky: If the low-level unwind and high-level base code share a
1613      common unwinder, let them share the prologue cache.  */
1614   if (fi->base->unwind == fi->unwind)
1615     return fi->base->this_locals (fi, &fi->prologue_cache);
1616   return fi->base->this_locals (fi, &fi->base_cache);
1617 }
1618
1619 CORE_ADDR
1620 get_frame_args_address (struct frame_info *fi)
1621 {
1622   void **cache;
1623   if (get_frame_type (fi) != NORMAL_FRAME)
1624     return 0;
1625   /* If there isn't a frame address method, find it.  */
1626   if (fi->base == NULL)
1627     fi->base = frame_base_find_by_frame (fi->next);
1628   /* Sneaky: If the low-level unwind and high-level base code share a
1629      common unwinder, let them share the prologue cache.  */
1630   if (fi->base->unwind == fi->unwind)
1631     return fi->base->this_args (fi, &fi->prologue_cache);
1632   return fi->base->this_args (fi, &fi->base_cache);
1633 }
1634
1635 /* Level of the selected frame: 0 for innermost, 1 for its caller, ...
1636    or -1 for a NULL frame.  */
1637
1638 int
1639 frame_relative_level (struct frame_info *fi)
1640 {
1641   if (fi == NULL)
1642     return -1;
1643   else
1644     return fi->level;
1645 }
1646
1647 enum frame_type
1648 get_frame_type (struct frame_info *frame)
1649 {
1650   if (frame->unwind == NULL)
1651     /* Initialize the frame's unwinder because that's what
1652        provides the frame's type.  */
1653     frame->unwind = frame_unwind_find_by_frame (frame, &frame->prologue_cache);
1654   return frame->unwind->type;
1655 }
1656
1657 void
1658 deprecated_update_frame_pc_hack (struct frame_info *frame, CORE_ADDR pc)
1659 {
1660   if (frame_debug)
1661     fprintf_unfiltered (gdb_stdlog,
1662                         "{ deprecated_update_frame_pc_hack (frame=%d,pc=0x%s) }\n",
1663                         frame->level, paddr_nz (pc));
1664   /* NOTE: cagney/2003-03-11: Some architectures (e.g., Arm) are
1665      maintaining a locally allocated frame object.  Since such frames
1666      are not in the frame chain, it isn't possible to assume that the
1667      frame has a next.  Sigh.  */
1668   if (frame->next != NULL)
1669     {
1670       /* While we're at it, update this frame's cached PC value, found
1671          in the next frame.  Oh for the day when "struct frame_info"
1672          is opaque and this hack on hack can just go away.  */
1673       frame->next->prev_pc.value = pc;
1674       frame->next->prev_pc.p = 1;
1675     }
1676 }
1677
1678 void
1679 deprecated_update_frame_base_hack (struct frame_info *frame, CORE_ADDR base)
1680 {
1681   if (frame_debug)
1682     fprintf_unfiltered (gdb_stdlog,
1683                         "{ deprecated_update_frame_base_hack (frame=%d,base=0x%s) }\n",
1684                         frame->level, paddr_nz (base));
1685   /* See comment in "frame.h".  */
1686   frame->this_id.value.stack_addr = base;
1687 }
1688
1689 /* Memory access methods.  */
1690
1691 void
1692 get_frame_memory (struct frame_info *this_frame, CORE_ADDR addr,
1693                   gdb_byte *buf, int len)
1694 {
1695   read_memory (addr, buf, len);
1696 }
1697
1698 LONGEST
1699 get_frame_memory_signed (struct frame_info *this_frame, CORE_ADDR addr,
1700                          int len)
1701 {
1702   return read_memory_integer (addr, len);
1703 }
1704
1705 ULONGEST
1706 get_frame_memory_unsigned (struct frame_info *this_frame, CORE_ADDR addr,
1707                            int len)
1708 {
1709   return read_memory_unsigned_integer (addr, len);
1710 }
1711
1712 int
1713 safe_frame_unwind_memory (struct frame_info *this_frame,
1714                           CORE_ADDR addr, gdb_byte *buf, int len)
1715 {
1716   /* NOTE: target_read_memory returns zero on success!  */
1717   return !target_read_memory (addr, buf, len);
1718 }
1719
1720 /* Architecture method.  */
1721
1722 struct gdbarch *
1723 get_frame_arch (struct frame_info *this_frame)
1724 {
1725   return current_gdbarch;
1726 }
1727
1728 /* Stack pointer methods.  */
1729
1730 CORE_ADDR
1731 get_frame_sp (struct frame_info *this_frame)
1732 {
1733   return frame_sp_unwind (this_frame->next);
1734 }
1735
1736 CORE_ADDR
1737 frame_sp_unwind (struct frame_info *next_frame)
1738 {
1739   struct gdbarch *gdbarch = get_frame_arch (next_frame);
1740   /* Normality - an architecture that provides a way of obtaining any
1741      frame inner-most address.  */
1742   if (gdbarch_unwind_sp_p (gdbarch))
1743     return gdbarch_unwind_sp (gdbarch, next_frame);
1744   /* Now things are really are grim.  Hope that the value returned by
1745      the gdbarch_sp_regnum register is meaningful.  */
1746   if (gdbarch_sp_regnum (gdbarch) >= 0)
1747     return frame_unwind_register_unsigned (next_frame,
1748                                            gdbarch_sp_regnum (gdbarch));
1749   internal_error (__FILE__, __LINE__, _("Missing unwind SP method"));
1750 }
1751
1752 /* Return the reason why we can't unwind past FRAME.  */
1753
1754 enum unwind_stop_reason
1755 get_frame_unwind_stop_reason (struct frame_info *frame)
1756 {
1757   /* If we haven't tried to unwind past this point yet, then assume
1758      that unwinding would succeed.  */
1759   if (frame->prev_p == 0)
1760     return UNWIND_NO_REASON;
1761
1762   /* Otherwise, we set a reason when we succeeded (or failed) to
1763      unwind.  */
1764   return frame->stop_reason;
1765 }
1766
1767 /* Return a string explaining REASON.  */
1768
1769 const char *
1770 frame_stop_reason_string (enum unwind_stop_reason reason)
1771 {
1772   switch (reason)
1773     {
1774     case UNWIND_NULL_ID:
1775       return _("unwinder did not report frame ID");
1776
1777     case UNWIND_INNER_ID:
1778       return _("previous frame inner to this frame (corrupt stack?)");
1779
1780     case UNWIND_SAME_ID:
1781       return _("previous frame identical to this frame (corrupt stack?)");
1782
1783     case UNWIND_NO_SAVED_PC:
1784       return _("frame did not save the PC");
1785
1786     case UNWIND_NO_REASON:
1787     case UNWIND_FIRST_ERROR:
1788     default:
1789       internal_error (__FILE__, __LINE__,
1790                       "Invalid frame stop reason");
1791     }
1792 }
1793
1794 /* Clean up after a failed (wrong unwinder) attempt to unwind past
1795    FRAME.  */
1796
1797 static void
1798 frame_cleanup_after_sniffer (void *arg)
1799 {
1800   struct frame_info *frame = arg;
1801
1802   /* The sniffer should not allocate a prologue cache if it did not
1803      match this frame.  */
1804   gdb_assert (frame->prologue_cache == NULL);
1805
1806   /* No sniffer should extend the frame chain; sniff based on what is
1807      already certain.  */
1808   gdb_assert (!frame->prev_p);
1809
1810   /* The sniffer should not check the frame's ID; that's circular.  */
1811   gdb_assert (!frame->this_id.p);
1812
1813   /* Clear cached fields dependent on the unwinder.
1814
1815      The previous PC is independent of the unwinder, but the previous
1816      function is not (see frame_unwind_address_in_block).  */
1817   frame->prev_func.p = 0;
1818   frame->prev_func.addr = 0;
1819
1820   /* Discard the unwinder last, so that we can easily find it if an assertion
1821      in this function triggers.  */
1822   frame->unwind = NULL;
1823 }
1824
1825 /* Set FRAME's unwinder temporarily, so that we can call a sniffer.
1826    Return a cleanup which should be called if unwinding fails, and
1827    discarded if it succeeds.  */
1828
1829 struct cleanup *
1830 frame_prepare_for_sniffer (struct frame_info *frame,
1831                            const struct frame_unwind *unwind)
1832 {
1833   gdb_assert (frame->unwind == NULL);
1834   frame->unwind = unwind;
1835   return make_cleanup (frame_cleanup_after_sniffer, frame);
1836 }
1837
1838 extern initialize_file_ftype _initialize_frame; /* -Wmissing-prototypes */
1839
1840 static struct cmd_list_element *set_backtrace_cmdlist;
1841 static struct cmd_list_element *show_backtrace_cmdlist;
1842
1843 static void
1844 set_backtrace_cmd (char *args, int from_tty)
1845 {
1846   help_list (set_backtrace_cmdlist, "set backtrace ", -1, gdb_stdout);
1847 }
1848
1849 static void
1850 show_backtrace_cmd (char *args, int from_tty)
1851 {
1852   cmd_show_list (show_backtrace_cmdlist, from_tty, "");
1853 }
1854
1855 void
1856 _initialize_frame (void)
1857 {
1858   obstack_init (&frame_cache_obstack);
1859
1860   observer_attach_target_changed (frame_observer_target_changed);
1861
1862   add_prefix_cmd ("backtrace", class_maintenance, set_backtrace_cmd, _("\
1863 Set backtrace specific variables.\n\
1864 Configure backtrace variables such as the backtrace limit"),
1865                   &set_backtrace_cmdlist, "set backtrace ",
1866                   0/*allow-unknown*/, &setlist);
1867   add_prefix_cmd ("backtrace", class_maintenance, show_backtrace_cmd, _("\
1868 Show backtrace specific variables\n\
1869 Show backtrace variables such as the backtrace limit"),
1870                   &show_backtrace_cmdlist, "show backtrace ",
1871                   0/*allow-unknown*/, &showlist);
1872
1873   add_setshow_boolean_cmd ("past-main", class_obscure,
1874                            &backtrace_past_main, _("\
1875 Set whether backtraces should continue past \"main\"."), _("\
1876 Show whether backtraces should continue past \"main\"."), _("\
1877 Normally the caller of \"main\" is not of interest, so GDB will terminate\n\
1878 the backtrace at \"main\".  Set this variable if you need to see the rest\n\
1879 of the stack trace."),
1880                            NULL,
1881                            show_backtrace_past_main,
1882                            &set_backtrace_cmdlist,
1883                            &show_backtrace_cmdlist);
1884
1885   add_setshow_boolean_cmd ("past-entry", class_obscure,
1886                            &backtrace_past_entry, _("\
1887 Set whether backtraces should continue past the entry point of a program."),
1888                            _("\
1889 Show whether backtraces should continue past the entry point of a program."),
1890                            _("\
1891 Normally there are no callers beyond the entry point of a program, so GDB\n\
1892 will terminate the backtrace there.  Set this variable if you need to see \n\
1893 the rest of the stack trace."),
1894                            NULL,
1895                            show_backtrace_past_entry,
1896                            &set_backtrace_cmdlist,
1897                            &show_backtrace_cmdlist);
1898
1899   add_setshow_integer_cmd ("limit", class_obscure,
1900                            &backtrace_limit, _("\
1901 Set an upper bound on the number of backtrace levels."), _("\
1902 Show the upper bound on the number of backtrace levels."), _("\
1903 No more than the specified number of frames can be displayed or examined.\n\
1904 Zero is unlimited."),
1905                            NULL,
1906                            show_backtrace_limit,
1907                            &set_backtrace_cmdlist,
1908                            &show_backtrace_cmdlist);
1909
1910   /* Debug this files internals. */
1911   add_setshow_zinteger_cmd ("frame", class_maintenance, &frame_debug,  _("\
1912 Set frame debugging."), _("\
1913 Show frame debugging."), _("\
1914 When non-zero, frame specific internal debugging is enabled."),
1915                             NULL,
1916                             show_frame_debug,
1917                             &setdebuglist, &showdebuglist);
1918 }