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