2013-05-17 Phil Muldoon <pmuldoon@redhat.com>
[platform/upstream/binutils.git] / gdb / frame.c
1 /* Cache and manage frames for GDB, the GNU debugger.
2
3    Copyright (C) 1986-2013 Free Software Foundation, Inc.
4
5    This file is part of GDB.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19
20 #include "defs.h"
21 #include "frame.h"
22 #include "target.h"
23 #include "value.h"
24 #include "inferior.h"   /* for inferior_ptid */
25 #include "regcache.h"
26 #include "gdb_assert.h"
27 #include "gdb_string.h"
28 #include "user-regs.h"
29 #include "gdb_obstack.h"
30 #include "dummy-frame.h"
31 #include "sentinel-frame.h"
32 #include "gdbcore.h"
33 #include "annotate.h"
34 #include "language.h"
35 #include "frame-unwind.h"
36 #include "frame-base.h"
37 #include "command.h"
38 #include "gdbcmd.h"
39 #include "observer.h"
40 #include "objfiles.h"
41 #include "exceptions.h"
42 #include "gdbthread.h"
43 #include "block.h"
44 #include "inline-frame.h"
45 #include "tracepoint.h"
46 #include "hashtab.h"
47
48 static struct frame_info *get_prev_frame_1 (struct frame_info *this_frame);
49 static struct frame_info *get_prev_frame_raw (struct frame_info *this_frame);
50
51 /* We keep a cache of stack frames, each of which is a "struct
52    frame_info".  The innermost one gets allocated (in
53    wait_for_inferior) each time the inferior stops; current_frame
54    points to it.  Additional frames get allocated (in get_prev_frame)
55    as needed, and are chained through the next and prev fields.  Any
56    time that the frame cache becomes invalid (most notably when we
57    execute something, but also if we change how we interpret the
58    frames (e.g. "set heuristic-fence-post" in mips-tdep.c, or anything
59    which reads new symbols)), we should call reinit_frame_cache.  */
60
61 struct frame_info
62 {
63   /* Level of this frame.  The inner-most (youngest) frame is at level
64      0.  As you move towards the outer-most (oldest) frame, the level
65      increases.  This is a cached value.  It could just as easily be
66      computed by counting back from the selected frame to the inner
67      most frame.  */
68   /* NOTE: cagney/2002-04-05: Perhaps a level of ``-1'' should be
69      reserved to indicate a bogus frame - one that has been created
70      just to keep GDB happy (GDB always needs a frame).  For the
71      moment leave this as speculation.  */
72   int level;
73
74   /* The frame's program space.  */
75   struct program_space *pspace;
76
77   /* The frame's address space.  */
78   struct address_space *aspace;
79
80   /* The frame's low-level unwinder and corresponding cache.  The
81      low-level unwinder is responsible for unwinding register values
82      for the previous frame.  The low-level unwind methods are
83      selected based on the presence, or otherwise, of register unwind
84      information such as CFI.  */
85   void *prologue_cache;
86   const struct frame_unwind *unwind;
87
88   /* Cached copy of the previous frame's architecture.  */
89   struct
90   {
91     int p;
92     struct gdbarch *arch;
93   } prev_arch;
94
95   /* Cached copy of the previous frame's resume address.  */
96   struct {
97     int p;
98     CORE_ADDR value;
99   } prev_pc;
100   
101   /* Cached copy of the previous frame's function address.  */
102   struct
103   {
104     CORE_ADDR addr;
105     int p;
106   } prev_func;
107   
108   /* This frame's ID.  */
109   struct
110   {
111     int p;
112     struct frame_id value;
113   } this_id;
114   
115   /* The frame's high-level base methods, and corresponding cache.
116      The high level base methods are selected based on the frame's
117      debug info.  */
118   const struct frame_base *base;
119   void *base_cache;
120
121   /* Pointers to the next (down, inner, younger) and previous (up,
122      outer, older) frame_info's in the frame cache.  */
123   struct frame_info *next; /* down, inner, younger */
124   int prev_p;
125   struct frame_info *prev; /* up, outer, older */
126
127   /* The reason why we could not set PREV, or UNWIND_NO_REASON if we
128      could.  Only valid when PREV_P is set.  */
129   enum unwind_stop_reason stop_reason;
130 };
131
132 /* A frame stash used to speed up frame lookups.  Create a hash table
133    to stash frames previously accessed from the frame cache for
134    quicker subsequent retrieval.  The hash table is emptied whenever
135    the frame cache is invalidated.  */
136
137 static htab_t frame_stash;
138
139 /* Internal function to calculate a hash from the frame_id addresses,
140    using as many valid addresses as possible.  Frames below level 0
141    are not stored in the hash table.  */
142
143 static hashval_t
144 frame_addr_hash (const void *ap)
145 {
146   const struct frame_info *frame = ap;
147   const struct frame_id f_id = frame->this_id.value;
148   hashval_t hash = 0;
149
150   gdb_assert (f_id.stack_addr_p || f_id.code_addr_p
151               || f_id.special_addr_p);
152
153   if (f_id.stack_addr_p)
154     hash = iterative_hash (&f_id.stack_addr,
155                            sizeof (f_id.stack_addr), hash);
156   if (f_id.code_addr_p)
157     hash = iterative_hash (&f_id.code_addr,
158                            sizeof (f_id.code_addr), hash);
159   if (f_id.special_addr_p)
160     hash = iterative_hash (&f_id.special_addr,
161                            sizeof (f_id.special_addr), hash);
162
163   return hash;
164 }
165
166 /* Internal equality function for the hash table.  This function
167    defers equality operations to frame_id_eq.  */
168
169 static int
170 frame_addr_hash_eq (const void *a, const void *b)
171 {
172   const struct frame_info *f_entry = a;
173   const struct frame_info *f_element = b;
174
175   return frame_id_eq (f_entry->this_id.value,
176                       f_element->this_id.value);
177 }
178
179 /* Internal function to create the frame_stash hash table.  100 seems
180    to be a good compromise to start the hash table at.  */
181
182 static void
183 frame_stash_create (void)
184 {
185   frame_stash = htab_create (100,
186                              frame_addr_hash,
187                              frame_addr_hash_eq,
188                              NULL);
189 }
190
191 /* Internal function to add a frame to the frame_stash hash table.  Do
192    not store frames below 0 as they may not have any addresses to
193    calculate a hash.  */
194
195 static void
196 frame_stash_add (struct frame_info *frame)
197 {
198   /* Do not stash frames below level 0.  */
199   if (frame->level >= 0)
200     {
201       struct frame_info **slot;
202
203       slot = (struct frame_info **) htab_find_slot (frame_stash,
204                                                     frame,
205                                                     INSERT);
206       *slot = frame;
207     }
208 }
209
210 /* Internal function to search the frame stash for an entry with the
211    given frame ID.  If found, return that frame.  Otherwise return
212    NULL.  */
213
214 static struct frame_info *
215 frame_stash_find (struct frame_id id)
216 {
217   struct frame_info dummy;
218   struct frame_info *frame;
219
220   dummy.this_id.value = id;
221   frame = htab_find (frame_stash, &dummy);
222   return frame;
223 }
224
225 /* Internal function to invalidate the frame stash by removing all
226    entries in it.  This only occurs when the frame cache is
227    invalidated.  */
228
229 static void
230 frame_stash_invalidate (void)
231 {
232   htab_empty (frame_stash);
233 }
234
235 /* Flag to control debugging.  */
236
237 unsigned int frame_debug;
238 static void
239 show_frame_debug (struct ui_file *file, int from_tty,
240                   struct cmd_list_element *c, const char *value)
241 {
242   fprintf_filtered (file, _("Frame debugging is %s.\n"), value);
243 }
244
245 /* Flag to indicate whether backtraces should stop at main et.al.  */
246
247 static int backtrace_past_main;
248 static void
249 show_backtrace_past_main (struct ui_file *file, int from_tty,
250                           struct cmd_list_element *c, const char *value)
251 {
252   fprintf_filtered (file,
253                     _("Whether backtraces should "
254                       "continue past \"main\" is %s.\n"),
255                     value);
256 }
257
258 static int backtrace_past_entry;
259 static void
260 show_backtrace_past_entry (struct ui_file *file, int from_tty,
261                            struct cmd_list_element *c, const char *value)
262 {
263   fprintf_filtered (file, _("Whether backtraces should continue past the "
264                             "entry point of a program is %s.\n"),
265                     value);
266 }
267
268 static unsigned int backtrace_limit = UINT_MAX;
269 static void
270 show_backtrace_limit (struct ui_file *file, int from_tty,
271                       struct cmd_list_element *c, const char *value)
272 {
273   fprintf_filtered (file,
274                     _("An upper bound on the number "
275                       "of backtrace levels is %s.\n"),
276                     value);
277 }
278
279
280 static void
281 fprint_field (struct ui_file *file, const char *name, int p, CORE_ADDR addr)
282 {
283   if (p)
284     fprintf_unfiltered (file, "%s=%s", name, hex_string (addr));
285   else
286     fprintf_unfiltered (file, "!%s", name);
287 }
288
289 void
290 fprint_frame_id (struct ui_file *file, struct frame_id id)
291 {
292   fprintf_unfiltered (file, "{");
293   fprint_field (file, "stack", id.stack_addr_p, id.stack_addr);
294   fprintf_unfiltered (file, ",");
295   fprint_field (file, "code", id.code_addr_p, id.code_addr);
296   fprintf_unfiltered (file, ",");
297   fprint_field (file, "special", id.special_addr_p, id.special_addr);
298   if (id.artificial_depth)
299     fprintf_unfiltered (file, ",artificial=%d", id.artificial_depth);
300   fprintf_unfiltered (file, "}");
301 }
302
303 static void
304 fprint_frame_type (struct ui_file *file, enum frame_type type)
305 {
306   switch (type)
307     {
308     case NORMAL_FRAME:
309       fprintf_unfiltered (file, "NORMAL_FRAME");
310       return;
311     case DUMMY_FRAME:
312       fprintf_unfiltered (file, "DUMMY_FRAME");
313       return;
314     case INLINE_FRAME:
315       fprintf_unfiltered (file, "INLINE_FRAME");
316       return;
317     case SENTINEL_FRAME:
318       fprintf_unfiltered (file, "SENTINEL_FRAME");
319       return;
320     case SIGTRAMP_FRAME:
321       fprintf_unfiltered (file, "SIGTRAMP_FRAME");
322       return;
323     case ARCH_FRAME:
324       fprintf_unfiltered (file, "ARCH_FRAME");
325       return;
326     default:
327       fprintf_unfiltered (file, "<unknown type>");
328       return;
329     };
330 }
331
332 static void
333 fprint_frame (struct ui_file *file, struct frame_info *fi)
334 {
335   if (fi == NULL)
336     {
337       fprintf_unfiltered (file, "<NULL frame>");
338       return;
339     }
340   fprintf_unfiltered (file, "{");
341   fprintf_unfiltered (file, "level=%d", fi->level);
342   fprintf_unfiltered (file, ",");
343   fprintf_unfiltered (file, "type=");
344   if (fi->unwind != NULL)
345     fprint_frame_type (file, fi->unwind->type);
346   else
347     fprintf_unfiltered (file, "<unknown>");
348   fprintf_unfiltered (file, ",");
349   fprintf_unfiltered (file, "unwind=");
350   if (fi->unwind != NULL)
351     gdb_print_host_address (fi->unwind, file);
352   else
353     fprintf_unfiltered (file, "<unknown>");
354   fprintf_unfiltered (file, ",");
355   fprintf_unfiltered (file, "pc=");
356   if (fi->next != NULL && fi->next->prev_pc.p)
357     fprintf_unfiltered (file, "%s", hex_string (fi->next->prev_pc.value));
358   else
359     fprintf_unfiltered (file, "<unknown>");
360   fprintf_unfiltered (file, ",");
361   fprintf_unfiltered (file, "id=");
362   if (fi->this_id.p)
363     fprint_frame_id (file, fi->this_id.value);
364   else
365     fprintf_unfiltered (file, "<unknown>");
366   fprintf_unfiltered (file, ",");
367   fprintf_unfiltered (file, "func=");
368   if (fi->next != NULL && fi->next->prev_func.p)
369     fprintf_unfiltered (file, "%s", hex_string (fi->next->prev_func.addr));
370   else
371     fprintf_unfiltered (file, "<unknown>");
372   fprintf_unfiltered (file, "}");
373 }
374
375 /* Given FRAME, return the enclosing frame as found in real frames read-in from
376    inferior memory.  Skip any previous frames which were made up by GDB.
377    Return the original frame if no immediate previous frames exist.  */
378
379 static struct frame_info *
380 skip_artificial_frames (struct frame_info *frame)
381 {
382   while (get_frame_type (frame) == INLINE_FRAME
383          || get_frame_type (frame) == TAILCALL_FRAME)
384     frame = get_prev_frame (frame);
385
386   return frame;
387 }
388
389 /* Return a frame uniq ID that can be used to, later, re-find the
390    frame.  */
391
392 struct frame_id
393 get_frame_id (struct frame_info *fi)
394 {
395   if (fi == NULL)
396     return null_frame_id;
397
398   if (!fi->this_id.p)
399     {
400       if (frame_debug)
401         fprintf_unfiltered (gdb_stdlog, "{ get_frame_id (fi=%d) ",
402                             fi->level);
403       /* Find the unwinder.  */
404       if (fi->unwind == NULL)
405         frame_unwind_find_by_frame (fi, &fi->prologue_cache);
406       /* Find THIS frame's ID.  */
407       /* Default to outermost if no ID is found.  */
408       fi->this_id.value = outer_frame_id;
409       fi->unwind->this_id (fi, &fi->prologue_cache, &fi->this_id.value);
410       gdb_assert (frame_id_p (fi->this_id.value));
411       fi->this_id.p = 1;
412       if (frame_debug)
413         {
414           fprintf_unfiltered (gdb_stdlog, "-> ");
415           fprint_frame_id (gdb_stdlog, fi->this_id.value);
416           fprintf_unfiltered (gdb_stdlog, " }\n");
417         }
418       frame_stash_add (fi);
419     }
420
421   return fi->this_id.value;
422 }
423
424 struct frame_id
425 get_stack_frame_id (struct frame_info *next_frame)
426 {
427   return get_frame_id (skip_artificial_frames (next_frame));
428 }
429
430 struct frame_id
431 frame_unwind_caller_id (struct frame_info *next_frame)
432 {
433   struct frame_info *this_frame;
434
435   /* Use get_prev_frame_1, and not get_prev_frame.  The latter will truncate
436      the frame chain, leading to this function unintentionally
437      returning a null_frame_id (e.g., when a caller requests the frame
438      ID of "main()"s caller.  */
439
440   next_frame = skip_artificial_frames (next_frame);
441   this_frame = get_prev_frame_1 (next_frame);
442   if (this_frame)
443     return get_frame_id (skip_artificial_frames (this_frame));
444   else
445     return null_frame_id;
446 }
447
448 const struct frame_id null_frame_id; /* All zeros.  */
449 const struct frame_id outer_frame_id = { 0, 0, 0, 0, 0, 1, 0 };
450
451 struct frame_id
452 frame_id_build_special (CORE_ADDR stack_addr, CORE_ADDR code_addr,
453                         CORE_ADDR special_addr)
454 {
455   struct frame_id id = null_frame_id;
456
457   id.stack_addr = stack_addr;
458   id.stack_addr_p = 1;
459   id.code_addr = code_addr;
460   id.code_addr_p = 1;
461   id.special_addr = special_addr;
462   id.special_addr_p = 1;
463   return id;
464 }
465
466 struct frame_id
467 frame_id_build (CORE_ADDR stack_addr, CORE_ADDR code_addr)
468 {
469   struct frame_id id = null_frame_id;
470
471   id.stack_addr = stack_addr;
472   id.stack_addr_p = 1;
473   id.code_addr = code_addr;
474   id.code_addr_p = 1;
475   return id;
476 }
477
478 struct frame_id
479 frame_id_build_wild (CORE_ADDR stack_addr)
480 {
481   struct frame_id id = null_frame_id;
482
483   id.stack_addr = stack_addr;
484   id.stack_addr_p = 1;
485   return id;
486 }
487
488 int
489 frame_id_p (struct frame_id l)
490 {
491   int p;
492
493   /* The frame is valid iff it has a valid stack address.  */
494   p = l.stack_addr_p;
495   /* outer_frame_id is also valid.  */
496   if (!p && memcmp (&l, &outer_frame_id, sizeof (l)) == 0)
497     p = 1;
498   if (frame_debug)
499     {
500       fprintf_unfiltered (gdb_stdlog, "{ frame_id_p (l=");
501       fprint_frame_id (gdb_stdlog, l);
502       fprintf_unfiltered (gdb_stdlog, ") -> %d }\n", p);
503     }
504   return p;
505 }
506
507 int
508 frame_id_artificial_p (struct frame_id l)
509 {
510   if (!frame_id_p (l))
511     return 0;
512
513   return (l.artificial_depth != 0);
514 }
515
516 int
517 frame_id_eq (struct frame_id l, struct frame_id r)
518 {
519   int eq;
520
521   if (!l.stack_addr_p && l.special_addr_p
522       && !r.stack_addr_p && r.special_addr_p)
523     /* The outermost frame marker is equal to itself.  This is the
524        dodgy thing about outer_frame_id, since between execution steps
525        we might step into another function - from which we can't
526        unwind either.  More thought required to get rid of
527        outer_frame_id.  */
528     eq = 1;
529   else if (!l.stack_addr_p || !r.stack_addr_p)
530     /* Like a NaN, if either ID is invalid, the result is false.
531        Note that a frame ID is invalid iff it is the null frame ID.  */
532     eq = 0;
533   else if (l.stack_addr != r.stack_addr)
534     /* If .stack addresses are different, the frames are different.  */
535     eq = 0;
536   else if (l.code_addr_p && r.code_addr_p && l.code_addr != r.code_addr)
537     /* An invalid code addr is a wild card.  If .code addresses are
538        different, the frames are different.  */
539     eq = 0;
540   else if (l.special_addr_p && r.special_addr_p
541            && l.special_addr != r.special_addr)
542     /* An invalid special addr is a wild card (or unused).  Otherwise
543        if special addresses are different, the frames are different.  */
544     eq = 0;
545   else if (l.artificial_depth != r.artificial_depth)
546     /* If artifical depths are different, the frames must be different.  */
547     eq = 0;
548   else
549     /* Frames are equal.  */
550     eq = 1;
551
552   if (frame_debug)
553     {
554       fprintf_unfiltered (gdb_stdlog, "{ frame_id_eq (l=");
555       fprint_frame_id (gdb_stdlog, l);
556       fprintf_unfiltered (gdb_stdlog, ",r=");
557       fprint_frame_id (gdb_stdlog, r);
558       fprintf_unfiltered (gdb_stdlog, ") -> %d }\n", eq);
559     }
560   return eq;
561 }
562
563 /* Safety net to check whether frame ID L should be inner to
564    frame ID R, according to their stack addresses.
565
566    This method cannot be used to compare arbitrary frames, as the
567    ranges of valid stack addresses may be discontiguous (e.g. due
568    to sigaltstack).
569
570    However, it can be used as safety net to discover invalid frame
571    IDs in certain circumstances.  Assuming that NEXT is the immediate
572    inner frame to THIS and that NEXT and THIS are both NORMAL frames:
573
574    * The stack address of NEXT must be inner-than-or-equal to the stack
575      address of THIS.
576
577      Therefore, if frame_id_inner (THIS, NEXT) holds, some unwind
578      error has occurred.
579
580    * If NEXT and THIS have different stack addresses, no other frame
581      in the frame chain may have a stack address in between.
582
583      Therefore, if frame_id_inner (TEST, THIS) holds, but
584      frame_id_inner (TEST, NEXT) does not hold, TEST cannot refer
585      to a valid frame in the frame chain.
586
587    The sanity checks above cannot be performed when a SIGTRAMP frame
588    is involved, because signal handlers might be executed on a different
589    stack than the stack used by the routine that caused the signal
590    to be raised.  This can happen for instance when a thread exceeds
591    its maximum stack size.  In this case, certain compilers implement
592    a stack overflow strategy that cause the handler to be run on a
593    different stack.  */
594
595 static int
596 frame_id_inner (struct gdbarch *gdbarch, struct frame_id l, struct frame_id r)
597 {
598   int inner;
599
600   if (!l.stack_addr_p || !r.stack_addr_p)
601     /* Like NaN, any operation involving an invalid ID always fails.  */
602     inner = 0;
603   else if (l.artificial_depth > r.artificial_depth
604            && l.stack_addr == r.stack_addr
605            && l.code_addr_p == r.code_addr_p
606            && l.special_addr_p == r.special_addr_p
607            && l.special_addr == r.special_addr)
608     {
609       /* Same function, different inlined functions.  */
610       struct block *lb, *rb;
611
612       gdb_assert (l.code_addr_p && r.code_addr_p);
613
614       lb = block_for_pc (l.code_addr);
615       rb = block_for_pc (r.code_addr);
616
617       if (lb == NULL || rb == NULL)
618         /* Something's gone wrong.  */
619         inner = 0;
620       else
621         /* This will return true if LB and RB are the same block, or
622            if the block with the smaller depth lexically encloses the
623            block with the greater depth.  */
624         inner = contained_in (lb, rb);
625     }
626   else
627     /* Only return non-zero when strictly inner than.  Note that, per
628        comment in "frame.h", there is some fuzz here.  Frameless
629        functions are not strictly inner than (same .stack but
630        different .code and/or .special address).  */
631     inner = gdbarch_inner_than (gdbarch, l.stack_addr, r.stack_addr);
632   if (frame_debug)
633     {
634       fprintf_unfiltered (gdb_stdlog, "{ frame_id_inner (l=");
635       fprint_frame_id (gdb_stdlog, l);
636       fprintf_unfiltered (gdb_stdlog, ",r=");
637       fprint_frame_id (gdb_stdlog, r);
638       fprintf_unfiltered (gdb_stdlog, ") -> %d }\n", inner);
639     }
640   return inner;
641 }
642
643 struct frame_info *
644 frame_find_by_id (struct frame_id id)
645 {
646   struct frame_info *frame, *prev_frame;
647
648   /* ZERO denotes the null frame, let the caller decide what to do
649      about it.  Should it instead return get_current_frame()?  */
650   if (!frame_id_p (id))
651     return NULL;
652
653   /* Try using the frame stash first.  Finding it there removes the need
654      to perform the search by looping over all frames, which can be very
655      CPU-intensive if the number of frames is very high (the loop is O(n)
656      and get_prev_frame performs a series of checks that are relatively
657      expensive).  This optimization is particularly useful when this function
658      is called from another function (such as value_fetch_lazy, case
659      VALUE_LVAL (val) == lval_register) which already loops over all frames,
660      making the overall behavior O(n^2).  */
661   frame = frame_stash_find (id);
662   if (frame)
663     return frame;
664
665   for (frame = get_current_frame (); ; frame = prev_frame)
666     {
667       struct frame_id this = get_frame_id (frame);
668
669       if (frame_id_eq (id, this))
670         /* An exact match.  */
671         return frame;
672
673       prev_frame = get_prev_frame (frame);
674       if (!prev_frame)
675         return NULL;
676
677       /* As a safety net to avoid unnecessary backtracing while trying
678          to find an invalid ID, we check for a common situation where
679          we can detect from comparing stack addresses that no other
680          frame in the current frame chain can have this ID.  See the
681          comment at frame_id_inner for details.   */
682       if (get_frame_type (frame) == NORMAL_FRAME
683           && !frame_id_inner (get_frame_arch (frame), id, this)
684           && frame_id_inner (get_frame_arch (prev_frame), id,
685                              get_frame_id (prev_frame)))
686         return NULL;
687     }
688   return NULL;
689 }
690
691 static int
692 frame_unwind_pc_if_available (struct frame_info *this_frame, CORE_ADDR *pc)
693 {
694   if (!this_frame->prev_pc.p)
695     {
696       if (gdbarch_unwind_pc_p (frame_unwind_arch (this_frame)))
697         {
698           volatile struct gdb_exception ex;
699           struct gdbarch *prev_gdbarch;
700           CORE_ADDR pc = 0;
701
702           /* The right way.  The `pure' way.  The one true way.  This
703              method depends solely on the register-unwind code to
704              determine the value of registers in THIS frame, and hence
705              the value of this frame's PC (resume address).  A typical
706              implementation is no more than:
707            
708              frame_unwind_register (this_frame, ISA_PC_REGNUM, buf);
709              return extract_unsigned_integer (buf, size of ISA_PC_REGNUM);
710
711              Note: this method is very heavily dependent on a correct
712              register-unwind implementation, it pays to fix that
713              method first; this method is frame type agnostic, since
714              it only deals with register values, it works with any
715              frame.  This is all in stark contrast to the old
716              FRAME_SAVED_PC which would try to directly handle all the
717              different ways that a PC could be unwound.  */
718           prev_gdbarch = frame_unwind_arch (this_frame);
719
720           TRY_CATCH (ex, RETURN_MASK_ERROR)
721             {
722               pc = gdbarch_unwind_pc (prev_gdbarch, this_frame);
723             }
724           if (ex.reason < 0 && ex.error == NOT_AVAILABLE_ERROR)
725             {
726               this_frame->prev_pc.p = -1;
727
728               if (frame_debug)
729                 fprintf_unfiltered (gdb_stdlog,
730                                     "{ frame_unwind_pc (this_frame=%d)"
731                                     " -> <unavailable> }\n",
732                                     this_frame->level);
733             }
734           else if (ex.reason < 0)
735             {
736               throw_exception (ex);
737             }
738           else
739             {
740               this_frame->prev_pc.value = pc;
741               this_frame->prev_pc.p = 1;
742               if (frame_debug)
743                 fprintf_unfiltered (gdb_stdlog,
744                                     "{ frame_unwind_pc (this_frame=%d) "
745                                     "-> %s }\n",
746                                     this_frame->level,
747                                     hex_string (this_frame->prev_pc.value));
748             }
749         }
750       else
751         internal_error (__FILE__, __LINE__, _("No unwind_pc method"));
752     }
753   if (this_frame->prev_pc.p < 0)
754     {
755       *pc = -1;
756       return 0;
757     }
758   else
759     {
760       *pc = this_frame->prev_pc.value;
761       return 1;
762     }
763 }
764
765 static CORE_ADDR
766 frame_unwind_pc (struct frame_info *this_frame)
767 {
768   CORE_ADDR pc;
769
770   if (!frame_unwind_pc_if_available (this_frame, &pc))
771     throw_error (NOT_AVAILABLE_ERROR, _("PC not available"));
772   else
773     return pc;
774 }
775
776 CORE_ADDR
777 frame_unwind_caller_pc (struct frame_info *this_frame)
778 {
779   return frame_unwind_pc (skip_artificial_frames (this_frame));
780 }
781
782 int
783 frame_unwind_caller_pc_if_available (struct frame_info *this_frame,
784                                      CORE_ADDR *pc)
785 {
786   return frame_unwind_pc_if_available (skip_artificial_frames (this_frame), pc);
787 }
788
789 int
790 get_frame_func_if_available (struct frame_info *this_frame, CORE_ADDR *pc)
791 {
792   struct frame_info *next_frame = this_frame->next;
793
794   if (!next_frame->prev_func.p)
795     {
796       CORE_ADDR addr_in_block;
797
798       /* Make certain that this, and not the adjacent, function is
799          found.  */
800       if (!get_frame_address_in_block_if_available (this_frame, &addr_in_block))
801         {
802           next_frame->prev_func.p = -1;
803           if (frame_debug)
804             fprintf_unfiltered (gdb_stdlog,
805                                 "{ get_frame_func (this_frame=%d)"
806                                 " -> unavailable }\n",
807                                 this_frame->level);
808         }
809       else
810         {
811           next_frame->prev_func.p = 1;
812           next_frame->prev_func.addr = get_pc_function_start (addr_in_block);
813           if (frame_debug)
814             fprintf_unfiltered (gdb_stdlog,
815                                 "{ get_frame_func (this_frame=%d) -> %s }\n",
816                                 this_frame->level,
817                                 hex_string (next_frame->prev_func.addr));
818         }
819     }
820
821   if (next_frame->prev_func.p < 0)
822     {
823       *pc = -1;
824       return 0;
825     }
826   else
827     {
828       *pc = next_frame->prev_func.addr;
829       return 1;
830     }
831 }
832
833 CORE_ADDR
834 get_frame_func (struct frame_info *this_frame)
835 {
836   CORE_ADDR pc;
837
838   if (!get_frame_func_if_available (this_frame, &pc))
839     throw_error (NOT_AVAILABLE_ERROR, _("PC not available"));
840
841   return pc;
842 }
843
844 static enum register_status
845 do_frame_register_read (void *src, int regnum, gdb_byte *buf)
846 {
847   if (!deprecated_frame_register_read (src, regnum, buf))
848     return REG_UNAVAILABLE;
849   else
850     return REG_VALID;
851 }
852
853 struct regcache *
854 frame_save_as_regcache (struct frame_info *this_frame)
855 {
856   struct address_space *aspace = get_frame_address_space (this_frame);
857   struct regcache *regcache = regcache_xmalloc (get_frame_arch (this_frame),
858                                                 aspace);
859   struct cleanup *cleanups = make_cleanup_regcache_xfree (regcache);
860
861   regcache_save (regcache, do_frame_register_read, this_frame);
862   discard_cleanups (cleanups);
863   return regcache;
864 }
865
866 void
867 frame_pop (struct frame_info *this_frame)
868 {
869   struct frame_info *prev_frame;
870   struct regcache *scratch;
871   struct cleanup *cleanups;
872
873   if (get_frame_type (this_frame) == DUMMY_FRAME)
874     {
875       /* Popping a dummy frame involves restoring more than just registers.
876          dummy_frame_pop does all the work.  */
877       dummy_frame_pop (get_frame_id (this_frame));
878       return;
879     }
880
881   /* Ensure that we have a frame to pop to.  */
882   prev_frame = get_prev_frame_1 (this_frame);
883
884   if (!prev_frame)
885     error (_("Cannot pop the initial frame."));
886
887   /* Ignore TAILCALL_FRAME type frames, they were executed already before
888      entering THISFRAME.  */
889   while (get_frame_type (prev_frame) == TAILCALL_FRAME)
890     prev_frame = get_prev_frame (prev_frame);
891
892   /* Make a copy of all the register values unwound from this frame.
893      Save them in a scratch buffer so that there isn't a race between
894      trying to extract the old values from the current regcache while
895      at the same time writing new values into that same cache.  */
896   scratch = frame_save_as_regcache (prev_frame);
897   cleanups = make_cleanup_regcache_xfree (scratch);
898
899   /* FIXME: cagney/2003-03-16: It should be possible to tell the
900      target's register cache that it is about to be hit with a burst
901      register transfer and that the sequence of register writes should
902      be batched.  The pair target_prepare_to_store() and
903      target_store_registers() kind of suggest this functionality.
904      Unfortunately, they don't implement it.  Their lack of a formal
905      definition can lead to targets writing back bogus values
906      (arguably a bug in the target code mind).  */
907   /* Now copy those saved registers into the current regcache.
908      Here, regcache_cpy() calls regcache_restore().  */
909   regcache_cpy (get_current_regcache (), scratch);
910   do_cleanups (cleanups);
911
912   /* We've made right mess of GDB's local state, just discard
913      everything.  */
914   reinit_frame_cache ();
915 }
916
917 void
918 frame_register_unwind (struct frame_info *frame, int regnum,
919                        int *optimizedp, int *unavailablep,
920                        enum lval_type *lvalp, CORE_ADDR *addrp,
921                        int *realnump, gdb_byte *bufferp)
922 {
923   struct value *value;
924
925   /* Require all but BUFFERP to be valid.  A NULL BUFFERP indicates
926      that the value proper does not need to be fetched.  */
927   gdb_assert (optimizedp != NULL);
928   gdb_assert (lvalp != NULL);
929   gdb_assert (addrp != NULL);
930   gdb_assert (realnump != NULL);
931   /* gdb_assert (bufferp != NULL); */
932
933   value = frame_unwind_register_value (frame, regnum);
934
935   gdb_assert (value != NULL);
936
937   *optimizedp = value_optimized_out (value);
938   *unavailablep = !value_entirely_available (value);
939   *lvalp = VALUE_LVAL (value);
940   *addrp = value_address (value);
941   *realnump = VALUE_REGNUM (value);
942
943   if (bufferp)
944     {
945       if (!*optimizedp && !*unavailablep)
946         memcpy (bufferp, value_contents_all (value),
947                 TYPE_LENGTH (value_type (value)));
948       else
949         memset (bufferp, 0, TYPE_LENGTH (value_type (value)));
950     }
951
952   /* Dispose of the new value.  This prevents watchpoints from
953      trying to watch the saved frame pointer.  */
954   release_value (value);
955   value_free (value);
956 }
957
958 void
959 frame_register (struct frame_info *frame, int regnum,
960                 int *optimizedp, int *unavailablep, enum lval_type *lvalp,
961                 CORE_ADDR *addrp, int *realnump, gdb_byte *bufferp)
962 {
963   /* Require all but BUFFERP to be valid.  A NULL BUFFERP indicates
964      that the value proper does not need to be fetched.  */
965   gdb_assert (optimizedp != NULL);
966   gdb_assert (lvalp != NULL);
967   gdb_assert (addrp != NULL);
968   gdb_assert (realnump != NULL);
969   /* gdb_assert (bufferp != NULL); */
970
971   /* Obtain the register value by unwinding the register from the next
972      (more inner frame).  */
973   gdb_assert (frame != NULL && frame->next != NULL);
974   frame_register_unwind (frame->next, regnum, optimizedp, unavailablep,
975                          lvalp, addrp, realnump, bufferp);
976 }
977
978 void
979 frame_unwind_register (struct frame_info *frame, int regnum, gdb_byte *buf)
980 {
981   int optimized;
982   int unavailable;
983   CORE_ADDR addr;
984   int realnum;
985   enum lval_type lval;
986
987   frame_register_unwind (frame, regnum, &optimized, &unavailable,
988                          &lval, &addr, &realnum, buf);
989
990   if (optimized)
991     error (_("Register %d was optimized out"), regnum);
992   if (unavailable)
993     throw_error (NOT_AVAILABLE_ERROR,
994                  _("Register %d is not available"), regnum);
995 }
996
997 void
998 get_frame_register (struct frame_info *frame,
999                     int regnum, gdb_byte *buf)
1000 {
1001   frame_unwind_register (frame->next, regnum, buf);
1002 }
1003
1004 struct value *
1005 frame_unwind_register_value (struct frame_info *frame, int regnum)
1006 {
1007   struct gdbarch *gdbarch;
1008   struct value *value;
1009
1010   gdb_assert (frame != NULL);
1011   gdbarch = frame_unwind_arch (frame);
1012
1013   if (frame_debug)
1014     {
1015       fprintf_unfiltered (gdb_stdlog,
1016                           "{ frame_unwind_register_value "
1017                           "(frame=%d,regnum=%d(%s),...) ",
1018                           frame->level, regnum,
1019                           user_reg_map_regnum_to_name (gdbarch, regnum));
1020     }
1021
1022   /* Find the unwinder.  */
1023   if (frame->unwind == NULL)
1024     frame_unwind_find_by_frame (frame, &frame->prologue_cache);
1025
1026   /* Ask this frame to unwind its register.  */
1027   value = frame->unwind->prev_register (frame, &frame->prologue_cache, regnum);
1028
1029   if (frame_debug)
1030     {
1031       fprintf_unfiltered (gdb_stdlog, "->");
1032       if (value_optimized_out (value))
1033         fprintf_unfiltered (gdb_stdlog, " optimized out");
1034       else
1035         {
1036           if (VALUE_LVAL (value) == lval_register)
1037             fprintf_unfiltered (gdb_stdlog, " register=%d",
1038                                 VALUE_REGNUM (value));
1039           else if (VALUE_LVAL (value) == lval_memory)
1040             fprintf_unfiltered (gdb_stdlog, " address=%s",
1041                                 paddress (gdbarch,
1042                                           value_address (value)));
1043           else
1044             fprintf_unfiltered (gdb_stdlog, " computed");
1045
1046           if (value_lazy (value))
1047             fprintf_unfiltered (gdb_stdlog, " lazy");
1048           else
1049             {
1050               int i;
1051               const gdb_byte *buf = value_contents (value);
1052
1053               fprintf_unfiltered (gdb_stdlog, " bytes=");
1054               fprintf_unfiltered (gdb_stdlog, "[");
1055               for (i = 0; i < register_size (gdbarch, regnum); i++)
1056                 fprintf_unfiltered (gdb_stdlog, "%02x", buf[i]);
1057               fprintf_unfiltered (gdb_stdlog, "]");
1058             }
1059         }
1060
1061       fprintf_unfiltered (gdb_stdlog, " }\n");
1062     }
1063
1064   return value;
1065 }
1066
1067 struct value *
1068 get_frame_register_value (struct frame_info *frame, int regnum)
1069 {
1070   return frame_unwind_register_value (frame->next, regnum);
1071 }
1072
1073 LONGEST
1074 frame_unwind_register_signed (struct frame_info *frame, int regnum)
1075 {
1076   struct gdbarch *gdbarch = frame_unwind_arch (frame);
1077   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
1078   int size = register_size (gdbarch, regnum);
1079   gdb_byte buf[MAX_REGISTER_SIZE];
1080
1081   frame_unwind_register (frame, regnum, buf);
1082   return extract_signed_integer (buf, size, byte_order);
1083 }
1084
1085 LONGEST
1086 get_frame_register_signed (struct frame_info *frame, int regnum)
1087 {
1088   return frame_unwind_register_signed (frame->next, regnum);
1089 }
1090
1091 ULONGEST
1092 frame_unwind_register_unsigned (struct frame_info *frame, int regnum)
1093 {
1094   struct gdbarch *gdbarch = frame_unwind_arch (frame);
1095   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
1096   int size = register_size (gdbarch, regnum);
1097   gdb_byte buf[MAX_REGISTER_SIZE];
1098
1099   frame_unwind_register (frame, regnum, buf);
1100   return extract_unsigned_integer (buf, size, byte_order);
1101 }
1102
1103 ULONGEST
1104 get_frame_register_unsigned (struct frame_info *frame, int regnum)
1105 {
1106   return frame_unwind_register_unsigned (frame->next, regnum);
1107 }
1108
1109 int
1110 read_frame_register_unsigned (struct frame_info *frame, int regnum,
1111                               ULONGEST *val)
1112 {
1113   struct value *regval = get_frame_register_value (frame, regnum);
1114
1115   if (!value_optimized_out (regval)
1116       && value_entirely_available (regval))
1117     {
1118       struct gdbarch *gdbarch = get_frame_arch (frame);
1119       enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
1120       int size = register_size (gdbarch, VALUE_REGNUM (regval));
1121
1122       *val = extract_unsigned_integer (value_contents (regval), size, byte_order);
1123       return 1;
1124     }
1125
1126   return 0;
1127 }
1128
1129 void
1130 put_frame_register (struct frame_info *frame, int regnum,
1131                     const gdb_byte *buf)
1132 {
1133   struct gdbarch *gdbarch = get_frame_arch (frame);
1134   int realnum;
1135   int optim;
1136   int unavail;
1137   enum lval_type lval;
1138   CORE_ADDR addr;
1139
1140   frame_register (frame, regnum, &optim, &unavail,
1141                   &lval, &addr, &realnum, NULL);
1142   if (optim)
1143     error (_("Attempt to assign to a value that was optimized out."));
1144   switch (lval)
1145     {
1146     case lval_memory:
1147       {
1148         write_memory (addr, buf, register_size (gdbarch, regnum));
1149         break;
1150       }
1151     case lval_register:
1152       regcache_cooked_write (get_current_regcache (), realnum, buf);
1153       break;
1154     default:
1155       error (_("Attempt to assign to an unmodifiable value."));
1156     }
1157 }
1158
1159 /* This function is deprecated.  Use get_frame_register_value instead,
1160    which provides more accurate information.
1161
1162    Find and return the value of REGNUM for the specified stack frame.
1163    The number of bytes copied is REGISTER_SIZE (REGNUM).
1164
1165    Returns 0 if the register value could not be found.  */
1166
1167 int
1168 deprecated_frame_register_read (struct frame_info *frame, int regnum,
1169                      gdb_byte *myaddr)
1170 {
1171   int optimized;
1172   int unavailable;
1173   enum lval_type lval;
1174   CORE_ADDR addr;
1175   int realnum;
1176
1177   frame_register (frame, regnum, &optimized, &unavailable,
1178                   &lval, &addr, &realnum, myaddr);
1179
1180   return !optimized && !unavailable;
1181 }
1182
1183 int
1184 get_frame_register_bytes (struct frame_info *frame, int regnum,
1185                           CORE_ADDR offset, int len, gdb_byte *myaddr,
1186                           int *optimizedp, int *unavailablep)
1187 {
1188   struct gdbarch *gdbarch = get_frame_arch (frame);
1189   int i;
1190   int maxsize;
1191   int numregs;
1192
1193   /* Skip registers wholly inside of OFFSET.  */
1194   while (offset >= register_size (gdbarch, regnum))
1195     {
1196       offset -= register_size (gdbarch, regnum);
1197       regnum++;
1198     }
1199
1200   /* Ensure that we will not read beyond the end of the register file.
1201      This can only ever happen if the debug information is bad.  */
1202   maxsize = -offset;
1203   numregs = gdbarch_num_regs (gdbarch) + gdbarch_num_pseudo_regs (gdbarch);
1204   for (i = regnum; i < numregs; i++)
1205     {
1206       int thissize = register_size (gdbarch, i);
1207
1208       if (thissize == 0)
1209         break;  /* This register is not available on this architecture.  */
1210       maxsize += thissize;
1211     }
1212   if (len > maxsize)
1213     error (_("Bad debug information detected: "
1214              "Attempt to read %d bytes from registers."), len);
1215
1216   /* Copy the data.  */
1217   while (len > 0)
1218     {
1219       int curr_len = register_size (gdbarch, regnum) - offset;
1220
1221       if (curr_len > len)
1222         curr_len = len;
1223
1224       if (curr_len == register_size (gdbarch, regnum))
1225         {
1226           enum lval_type lval;
1227           CORE_ADDR addr;
1228           int realnum;
1229
1230           frame_register (frame, regnum, optimizedp, unavailablep,
1231                           &lval, &addr, &realnum, myaddr);
1232           if (*optimizedp || *unavailablep)
1233             return 0;
1234         }
1235       else
1236         {
1237           gdb_byte buf[MAX_REGISTER_SIZE];
1238           enum lval_type lval;
1239           CORE_ADDR addr;
1240           int realnum;
1241
1242           frame_register (frame, regnum, optimizedp, unavailablep,
1243                           &lval, &addr, &realnum, buf);
1244           if (*optimizedp || *unavailablep)
1245             return 0;
1246           memcpy (myaddr, buf + offset, curr_len);
1247         }
1248
1249       myaddr += curr_len;
1250       len -= curr_len;
1251       offset = 0;
1252       regnum++;
1253     }
1254
1255   *optimizedp = 0;
1256   *unavailablep = 0;
1257   return 1;
1258 }
1259
1260 void
1261 put_frame_register_bytes (struct frame_info *frame, int regnum,
1262                           CORE_ADDR offset, int len, const gdb_byte *myaddr)
1263 {
1264   struct gdbarch *gdbarch = get_frame_arch (frame);
1265
1266   /* Skip registers wholly inside of OFFSET.  */
1267   while (offset >= register_size (gdbarch, regnum))
1268     {
1269       offset -= register_size (gdbarch, regnum);
1270       regnum++;
1271     }
1272
1273   /* Copy the data.  */
1274   while (len > 0)
1275     {
1276       int curr_len = register_size (gdbarch, regnum) - offset;
1277
1278       if (curr_len > len)
1279         curr_len = len;
1280
1281       if (curr_len == register_size (gdbarch, regnum))
1282         {
1283           put_frame_register (frame, regnum, myaddr);
1284         }
1285       else
1286         {
1287           gdb_byte buf[MAX_REGISTER_SIZE];
1288
1289           deprecated_frame_register_read (frame, regnum, buf);
1290           memcpy (buf + offset, myaddr, curr_len);
1291           put_frame_register (frame, regnum, buf);
1292         }
1293
1294       myaddr += curr_len;
1295       len -= curr_len;
1296       offset = 0;
1297       regnum++;
1298     }
1299 }
1300
1301 /* Create a sentinel frame.  */
1302
1303 static struct frame_info *
1304 create_sentinel_frame (struct program_space *pspace, struct regcache *regcache)
1305 {
1306   struct frame_info *frame = FRAME_OBSTACK_ZALLOC (struct frame_info);
1307
1308   frame->level = -1;
1309   frame->pspace = pspace;
1310   frame->aspace = get_regcache_aspace (regcache);
1311   /* Explicitly initialize the sentinel frame's cache.  Provide it
1312      with the underlying regcache.  In the future additional
1313      information, such as the frame's thread will be added.  */
1314   frame->prologue_cache = sentinel_frame_cache (regcache);
1315   /* For the moment there is only one sentinel frame implementation.  */
1316   frame->unwind = &sentinel_frame_unwind;
1317   /* Link this frame back to itself.  The frame is self referential
1318      (the unwound PC is the same as the pc), so make it so.  */
1319   frame->next = frame;
1320   /* Make the sentinel frame's ID valid, but invalid.  That way all
1321      comparisons with it should fail.  */
1322   frame->this_id.p = 1;
1323   frame->this_id.value = null_frame_id;
1324   if (frame_debug)
1325     {
1326       fprintf_unfiltered (gdb_stdlog, "{ create_sentinel_frame (...) -> ");
1327       fprint_frame (gdb_stdlog, frame);
1328       fprintf_unfiltered (gdb_stdlog, " }\n");
1329     }
1330   return frame;
1331 }
1332
1333 /* Info about the innermost stack frame (contents of FP register).  */
1334
1335 static struct frame_info *current_frame;
1336
1337 /* Cache for frame addresses already read by gdb.  Valid only while
1338    inferior is stopped.  Control variables for the frame cache should
1339    be local to this module.  */
1340
1341 static struct obstack frame_cache_obstack;
1342
1343 void *
1344 frame_obstack_zalloc (unsigned long size)
1345 {
1346   void *data = obstack_alloc (&frame_cache_obstack, size);
1347
1348   memset (data, 0, size);
1349   return data;
1350 }
1351
1352 /* Return the innermost (currently executing) stack frame.  This is
1353    split into two functions.  The function unwind_to_current_frame()
1354    is wrapped in catch exceptions so that, even when the unwind of the
1355    sentinel frame fails, the function still returns a stack frame.  */
1356
1357 static int
1358 unwind_to_current_frame (struct ui_out *ui_out, void *args)
1359 {
1360   struct frame_info *frame = get_prev_frame (args);
1361
1362   /* A sentinel frame can fail to unwind, e.g., because its PC value
1363      lands in somewhere like start.  */
1364   if (frame == NULL)
1365     return 1;
1366   current_frame = frame;
1367   return 0;
1368 }
1369
1370 struct frame_info *
1371 get_current_frame (void)
1372 {
1373   /* First check, and report, the lack of registers.  Having GDB
1374      report "No stack!" or "No memory" when the target doesn't even
1375      have registers is very confusing.  Besides, "printcmd.exp"
1376      explicitly checks that ``print $pc'' with no registers prints "No
1377      registers".  */
1378   if (!target_has_registers)
1379     error (_("No registers."));
1380   if (!target_has_stack)
1381     error (_("No stack."));
1382   if (!target_has_memory)
1383     error (_("No memory."));
1384   /* Traceframes are effectively a substitute for the live inferior.  */
1385   if (get_traceframe_number () < 0)
1386     {
1387       if (ptid_equal (inferior_ptid, null_ptid))
1388         error (_("No selected thread."));
1389       if (is_exited (inferior_ptid))
1390         error (_("Invalid selected thread."));
1391       if (is_executing (inferior_ptid))
1392         error (_("Target is executing."));
1393     }
1394
1395   if (current_frame == NULL)
1396     {
1397       struct frame_info *sentinel_frame =
1398         create_sentinel_frame (current_program_space, get_current_regcache ());
1399       if (catch_exceptions (current_uiout, unwind_to_current_frame,
1400                             sentinel_frame, RETURN_MASK_ERROR) != 0)
1401         {
1402           /* Oops! Fake a current frame?  Is this useful?  It has a PC
1403              of zero, for instance.  */
1404           current_frame = sentinel_frame;
1405         }
1406     }
1407   return current_frame;
1408 }
1409
1410 /* The "selected" stack frame is used by default for local and arg
1411    access.  May be zero, for no selected frame.  */
1412
1413 static struct frame_info *selected_frame;
1414
1415 int
1416 has_stack_frames (void)
1417 {
1418   if (!target_has_registers || !target_has_stack || !target_has_memory)
1419     return 0;
1420
1421   /* Traceframes are effectively a substitute for the live inferior.  */
1422   if (get_traceframe_number () < 0)
1423     {
1424       /* No current inferior, no frame.  */
1425       if (ptid_equal (inferior_ptid, null_ptid))
1426         return 0;
1427
1428       /* Don't try to read from a dead thread.  */
1429       if (is_exited (inferior_ptid))
1430         return 0;
1431
1432       /* ... or from a spinning thread.  */
1433       if (is_executing (inferior_ptid))
1434         return 0;
1435     }
1436
1437   return 1;
1438 }
1439
1440 /* Return the selected frame.  Always non-NULL (unless there isn't an
1441    inferior sufficient for creating a frame) in which case an error is
1442    thrown.  */
1443
1444 struct frame_info *
1445 get_selected_frame (const char *message)
1446 {
1447   if (selected_frame == NULL)
1448     {
1449       if (message != NULL && !has_stack_frames ())
1450         error (("%s"), message);
1451       /* Hey!  Don't trust this.  It should really be re-finding the
1452          last selected frame of the currently selected thread.  This,
1453          though, is better than nothing.  */
1454       select_frame (get_current_frame ());
1455     }
1456   /* There is always a frame.  */
1457   gdb_assert (selected_frame != NULL);
1458   return selected_frame;
1459 }
1460
1461 /* If there is a selected frame, return it.  Otherwise, return NULL.  */
1462
1463 struct frame_info *
1464 get_selected_frame_if_set (void)
1465 {
1466   return selected_frame;
1467 }
1468
1469 /* This is a variant of get_selected_frame() which can be called when
1470    the inferior does not have a frame; in that case it will return
1471    NULL instead of calling error().  */
1472
1473 struct frame_info *
1474 deprecated_safe_get_selected_frame (void)
1475 {
1476   if (!has_stack_frames ())
1477     return NULL;
1478   return get_selected_frame (NULL);
1479 }
1480
1481 /* Select frame FI (or NULL - to invalidate the current frame).  */
1482
1483 void
1484 select_frame (struct frame_info *fi)
1485 {
1486   selected_frame = fi;
1487   /* NOTE: cagney/2002-05-04: FI can be NULL.  This occurs when the
1488      frame is being invalidated.  */
1489   if (deprecated_selected_frame_level_changed_hook)
1490     deprecated_selected_frame_level_changed_hook (frame_relative_level (fi));
1491
1492   /* FIXME: kseitz/2002-08-28: It would be nice to call
1493      selected_frame_level_changed_event() right here, but due to limitations
1494      in the current interfaces, we would end up flooding UIs with events
1495      because select_frame() is used extensively internally.
1496
1497      Once we have frame-parameterized frame (and frame-related) commands,
1498      the event notification can be moved here, since this function will only
1499      be called when the user's selected frame is being changed.  */
1500
1501   /* Ensure that symbols for this frame are read in.  Also, determine the
1502      source language of this frame, and switch to it if desired.  */
1503   if (fi)
1504     {
1505       CORE_ADDR pc;
1506
1507       /* We retrieve the frame's symtab by using the frame PC.
1508          However we cannot use the frame PC as-is, because it usually
1509          points to the instruction following the "call", which is
1510          sometimes the first instruction of another function.  So we
1511          rely on get_frame_address_in_block() which provides us with a
1512          PC which is guaranteed to be inside the frame's code
1513          block.  */
1514       if (get_frame_address_in_block_if_available (fi, &pc))
1515         {
1516           struct symtab *s = find_pc_symtab (pc);
1517
1518           if (s
1519               && s->language != current_language->la_language
1520               && s->language != language_unknown
1521               && language_mode == language_mode_auto)
1522             set_language (s->language);
1523         }
1524     }
1525 }
1526
1527 /* Create an arbitrary (i.e. address specified by user) or innermost frame.
1528    Always returns a non-NULL value.  */
1529
1530 struct frame_info *
1531 create_new_frame (CORE_ADDR addr, CORE_ADDR pc)
1532 {
1533   struct frame_info *fi;
1534
1535   if (frame_debug)
1536     {
1537       fprintf_unfiltered (gdb_stdlog,
1538                           "{ create_new_frame (addr=%s, pc=%s) ",
1539                           hex_string (addr), hex_string (pc));
1540     }
1541
1542   fi = FRAME_OBSTACK_ZALLOC (struct frame_info);
1543
1544   fi->next = create_sentinel_frame (current_program_space,
1545                                     get_current_regcache ());
1546
1547   /* Set/update this frame's cached PC value, found in the next frame.
1548      Do this before looking for this frame's unwinder.  A sniffer is
1549      very likely to read this, and the corresponding unwinder is
1550      entitled to rely that the PC doesn't magically change.  */
1551   fi->next->prev_pc.value = pc;
1552   fi->next->prev_pc.p = 1;
1553
1554   /* We currently assume that frame chain's can't cross spaces.  */
1555   fi->pspace = fi->next->pspace;
1556   fi->aspace = fi->next->aspace;
1557
1558   /* Select/initialize both the unwind function and the frame's type
1559      based on the PC.  */
1560   frame_unwind_find_by_frame (fi, &fi->prologue_cache);
1561
1562   fi->this_id.p = 1;
1563   fi->this_id.value = frame_id_build (addr, pc);
1564
1565   if (frame_debug)
1566     {
1567       fprintf_unfiltered (gdb_stdlog, "-> ");
1568       fprint_frame (gdb_stdlog, fi);
1569       fprintf_unfiltered (gdb_stdlog, " }\n");
1570     }
1571
1572   return fi;
1573 }
1574
1575 /* Return the frame that THIS_FRAME calls (NULL if THIS_FRAME is the
1576    innermost frame).  Be careful to not fall off the bottom of the
1577    frame chain and onto the sentinel frame.  */
1578
1579 struct frame_info *
1580 get_next_frame (struct frame_info *this_frame)
1581 {
1582   if (this_frame->level > 0)
1583     return this_frame->next;
1584   else
1585     return NULL;
1586 }
1587
1588 /* Observer for the target_changed event.  */
1589
1590 static void
1591 frame_observer_target_changed (struct target_ops *target)
1592 {
1593   reinit_frame_cache ();
1594 }
1595
1596 /* Flush the entire frame cache.  */
1597
1598 void
1599 reinit_frame_cache (void)
1600 {
1601   struct frame_info *fi;
1602
1603   /* Tear down all frame caches.  */
1604   for (fi = current_frame; fi != NULL; fi = fi->prev)
1605     {
1606       if (fi->prologue_cache && fi->unwind->dealloc_cache)
1607         fi->unwind->dealloc_cache (fi, fi->prologue_cache);
1608       if (fi->base_cache && fi->base->unwind->dealloc_cache)
1609         fi->base->unwind->dealloc_cache (fi, fi->base_cache);
1610     }
1611
1612   /* Since we can't really be sure what the first object allocated was.  */
1613   obstack_free (&frame_cache_obstack, 0);
1614   obstack_init (&frame_cache_obstack);
1615
1616   if (current_frame != NULL)
1617     annotate_frames_invalid ();
1618
1619   current_frame = NULL;         /* Invalidate cache */
1620   select_frame (NULL);
1621   frame_stash_invalidate ();
1622   if (frame_debug)
1623     fprintf_unfiltered (gdb_stdlog, "{ reinit_frame_cache () }\n");
1624 }
1625
1626 /* Find where a register is saved (in memory or another register).
1627    The result of frame_register_unwind is just where it is saved
1628    relative to this particular frame.  */
1629
1630 static void
1631 frame_register_unwind_location (struct frame_info *this_frame, int regnum,
1632                                 int *optimizedp, enum lval_type *lvalp,
1633                                 CORE_ADDR *addrp, int *realnump)
1634 {
1635   gdb_assert (this_frame == NULL || this_frame->level >= 0);
1636
1637   while (this_frame != NULL)
1638     {
1639       int unavailable;
1640
1641       frame_register_unwind (this_frame, regnum, optimizedp, &unavailable,
1642                              lvalp, addrp, realnump, NULL);
1643
1644       if (*optimizedp)
1645         break;
1646
1647       if (*lvalp != lval_register)
1648         break;
1649
1650       regnum = *realnump;
1651       this_frame = get_next_frame (this_frame);
1652     }
1653 }
1654
1655 /* Return a "struct frame_info" corresponding to the frame that called
1656    THIS_FRAME.  Returns NULL if there is no such frame.
1657
1658    Unlike get_prev_frame, this function always tries to unwind the
1659    frame.  */
1660
1661 static struct frame_info *
1662 get_prev_frame_1 (struct frame_info *this_frame)
1663 {
1664   struct frame_id this_id;
1665   struct gdbarch *gdbarch;
1666
1667   gdb_assert (this_frame != NULL);
1668   gdbarch = get_frame_arch (this_frame);
1669
1670   if (frame_debug)
1671     {
1672       fprintf_unfiltered (gdb_stdlog, "{ get_prev_frame_1 (this_frame=");
1673       if (this_frame != NULL)
1674         fprintf_unfiltered (gdb_stdlog, "%d", this_frame->level);
1675       else
1676         fprintf_unfiltered (gdb_stdlog, "<NULL>");
1677       fprintf_unfiltered (gdb_stdlog, ") ");
1678     }
1679
1680   /* Only try to do the unwind once.  */
1681   if (this_frame->prev_p)
1682     {
1683       if (frame_debug)
1684         {
1685           fprintf_unfiltered (gdb_stdlog, "-> ");
1686           fprint_frame (gdb_stdlog, this_frame->prev);
1687           fprintf_unfiltered (gdb_stdlog, " // cached \n");
1688         }
1689       return this_frame->prev;
1690     }
1691
1692   /* If the frame unwinder hasn't been selected yet, we must do so
1693      before setting prev_p; otherwise the check for misbehaved
1694      sniffers will think that this frame's sniffer tried to unwind
1695      further (see frame_cleanup_after_sniffer).  */
1696   if (this_frame->unwind == NULL)
1697     frame_unwind_find_by_frame (this_frame, &this_frame->prologue_cache);
1698
1699   this_frame->prev_p = 1;
1700   this_frame->stop_reason = UNWIND_NO_REASON;
1701
1702   /* If we are unwinding from an inline frame, all of the below tests
1703      were already performed when we unwound from the next non-inline
1704      frame.  We must skip them, since we can not get THIS_FRAME's ID
1705      until we have unwound all the way down to the previous non-inline
1706      frame.  */
1707   if (get_frame_type (this_frame) == INLINE_FRAME)
1708     return get_prev_frame_raw (this_frame);
1709
1710   /* Check that this frame is unwindable.  If it isn't, don't try to
1711      unwind to the prev frame.  */
1712   this_frame->stop_reason
1713     = this_frame->unwind->stop_reason (this_frame,
1714                                        &this_frame->prologue_cache);
1715
1716   if (this_frame->stop_reason != UNWIND_NO_REASON)
1717     return NULL;
1718
1719   /* Check that this frame's ID was valid.  If it wasn't, don't try to
1720      unwind to the prev frame.  Be careful to not apply this test to
1721      the sentinel frame.  */
1722   this_id = get_frame_id (this_frame);
1723   if (this_frame->level >= 0 && frame_id_eq (this_id, outer_frame_id))
1724     {
1725       if (frame_debug)
1726         {
1727           fprintf_unfiltered (gdb_stdlog, "-> ");
1728           fprint_frame (gdb_stdlog, NULL);
1729           fprintf_unfiltered (gdb_stdlog, " // this ID is NULL }\n");
1730         }
1731       this_frame->stop_reason = UNWIND_NULL_ID;
1732       return NULL;
1733     }
1734
1735   /* Check that this frame's ID isn't inner to (younger, below, next)
1736      the next frame.  This happens when a frame unwind goes backwards.
1737      This check is valid only if this frame and the next frame are NORMAL.
1738      See the comment at frame_id_inner for details.  */
1739   if (get_frame_type (this_frame) == NORMAL_FRAME
1740       && this_frame->next->unwind->type == NORMAL_FRAME
1741       && frame_id_inner (get_frame_arch (this_frame->next), this_id,
1742                          get_frame_id (this_frame->next)))
1743     {
1744       CORE_ADDR this_pc_in_block;
1745       struct minimal_symbol *morestack_msym;
1746       const char *morestack_name = NULL;
1747       
1748       /* gcc -fsplit-stack __morestack can continue the stack anywhere.  */
1749       this_pc_in_block = get_frame_address_in_block (this_frame);
1750       morestack_msym = lookup_minimal_symbol_by_pc (this_pc_in_block).minsym;
1751       if (morestack_msym)
1752         morestack_name = SYMBOL_LINKAGE_NAME (morestack_msym);
1753       if (!morestack_name || strcmp (morestack_name, "__morestack") != 0)
1754         {
1755           if (frame_debug)
1756             {
1757               fprintf_unfiltered (gdb_stdlog, "-> ");
1758               fprint_frame (gdb_stdlog, NULL);
1759               fprintf_unfiltered (gdb_stdlog,
1760                                   " // this frame ID is inner }\n");
1761             }
1762           this_frame->stop_reason = UNWIND_INNER_ID;
1763           return NULL;
1764         }
1765     }
1766
1767   /* Check that this and the next frame are not identical.  If they
1768      are, there is most likely a stack cycle.  As with the inner-than
1769      test above, avoid comparing the inner-most and sentinel frames.  */
1770   if (this_frame->level > 0
1771       && frame_id_eq (this_id, get_frame_id (this_frame->next)))
1772     {
1773       if (frame_debug)
1774         {
1775           fprintf_unfiltered (gdb_stdlog, "-> ");
1776           fprint_frame (gdb_stdlog, NULL);
1777           fprintf_unfiltered (gdb_stdlog, " // this frame has same ID }\n");
1778         }
1779       this_frame->stop_reason = UNWIND_SAME_ID;
1780       return NULL;
1781     }
1782
1783   /* Check that this and the next frame do not unwind the PC register
1784      to the same memory location.  If they do, then even though they
1785      have different frame IDs, the new frame will be bogus; two
1786      functions can't share a register save slot for the PC.  This can
1787      happen when the prologue analyzer finds a stack adjustment, but
1788      no PC save.
1789
1790      This check does assume that the "PC register" is roughly a
1791      traditional PC, even if the gdbarch_unwind_pc method adjusts
1792      it (we do not rely on the value, only on the unwound PC being
1793      dependent on this value).  A potential improvement would be
1794      to have the frame prev_pc method and the gdbarch unwind_pc
1795      method set the same lval and location information as
1796      frame_register_unwind.  */
1797   if (this_frame->level > 0
1798       && gdbarch_pc_regnum (gdbarch) >= 0
1799       && get_frame_type (this_frame) == NORMAL_FRAME
1800       && (get_frame_type (this_frame->next) == NORMAL_FRAME
1801           || get_frame_type (this_frame->next) == INLINE_FRAME))
1802     {
1803       int optimized, realnum, nrealnum;
1804       enum lval_type lval, nlval;
1805       CORE_ADDR addr, naddr;
1806
1807       frame_register_unwind_location (this_frame,
1808                                       gdbarch_pc_regnum (gdbarch),
1809                                       &optimized, &lval, &addr, &realnum);
1810       frame_register_unwind_location (get_next_frame (this_frame),
1811                                       gdbarch_pc_regnum (gdbarch),
1812                                       &optimized, &nlval, &naddr, &nrealnum);
1813
1814       if ((lval == lval_memory && lval == nlval && addr == naddr)
1815           || (lval == lval_register && lval == nlval && realnum == nrealnum))
1816         {
1817           if (frame_debug)
1818             {
1819               fprintf_unfiltered (gdb_stdlog, "-> ");
1820               fprint_frame (gdb_stdlog, NULL);
1821               fprintf_unfiltered (gdb_stdlog, " // no saved PC }\n");
1822             }
1823
1824           this_frame->stop_reason = UNWIND_NO_SAVED_PC;
1825           this_frame->prev = NULL;
1826           return NULL;
1827         }
1828     }
1829
1830   return get_prev_frame_raw (this_frame);
1831 }
1832
1833 /* Construct a new "struct frame_info" and link it previous to
1834    this_frame.  */
1835
1836 static struct frame_info *
1837 get_prev_frame_raw (struct frame_info *this_frame)
1838 {
1839   struct frame_info *prev_frame;
1840
1841   /* Allocate the new frame but do not wire it in to the frame chain.
1842      Some (bad) code in INIT_FRAME_EXTRA_INFO tries to look along
1843      frame->next to pull some fancy tricks (of course such code is, by
1844      definition, recursive).  Try to prevent it.
1845
1846      There is no reason to worry about memory leaks, should the
1847      remainder of the function fail.  The allocated memory will be
1848      quickly reclaimed when the frame cache is flushed, and the `we've
1849      been here before' check above will stop repeated memory
1850      allocation calls.  */
1851   prev_frame = FRAME_OBSTACK_ZALLOC (struct frame_info);
1852   prev_frame->level = this_frame->level + 1;
1853
1854   /* For now, assume we don't have frame chains crossing address
1855      spaces.  */
1856   prev_frame->pspace = this_frame->pspace;
1857   prev_frame->aspace = this_frame->aspace;
1858
1859   /* Don't yet compute ->unwind (and hence ->type).  It is computed
1860      on-demand in get_frame_type, frame_register_unwind, and
1861      get_frame_id.  */
1862
1863   /* Don't yet compute the frame's ID.  It is computed on-demand by
1864      get_frame_id().  */
1865
1866   /* The unwound frame ID is validate at the start of this function,
1867      as part of the logic to decide if that frame should be further
1868      unwound, and not here while the prev frame is being created.
1869      Doing this makes it possible for the user to examine a frame that
1870      has an invalid frame ID.
1871
1872      Some very old VAX code noted: [...]  For the sake of argument,
1873      suppose that the stack is somewhat trashed (which is one reason
1874      that "info frame" exists).  So, return 0 (indicating we don't
1875      know the address of the arglist) if we don't know what frame this
1876      frame calls.  */
1877
1878   /* Link it in.  */
1879   this_frame->prev = prev_frame;
1880   prev_frame->next = this_frame;
1881
1882   if (frame_debug)
1883     {
1884       fprintf_unfiltered (gdb_stdlog, "-> ");
1885       fprint_frame (gdb_stdlog, prev_frame);
1886       fprintf_unfiltered (gdb_stdlog, " }\n");
1887     }
1888
1889   return prev_frame;
1890 }
1891
1892 /* Debug routine to print a NULL frame being returned.  */
1893
1894 static void
1895 frame_debug_got_null_frame (struct frame_info *this_frame,
1896                             const char *reason)
1897 {
1898   if (frame_debug)
1899     {
1900       fprintf_unfiltered (gdb_stdlog, "{ get_prev_frame (this_frame=");
1901       if (this_frame != NULL)
1902         fprintf_unfiltered (gdb_stdlog, "%d", this_frame->level);
1903       else
1904         fprintf_unfiltered (gdb_stdlog, "<NULL>");
1905       fprintf_unfiltered (gdb_stdlog, ") -> // %s}\n", reason);
1906     }
1907 }
1908
1909 /* Is this (non-sentinel) frame in the "main"() function?  */
1910
1911 static int
1912 inside_main_func (struct frame_info *this_frame)
1913 {
1914   struct minimal_symbol *msymbol;
1915   CORE_ADDR maddr;
1916
1917   if (symfile_objfile == 0)
1918     return 0;
1919   msymbol = lookup_minimal_symbol (main_name (), NULL, symfile_objfile);
1920   if (msymbol == NULL)
1921     return 0;
1922   /* Make certain that the code, and not descriptor, address is
1923      returned.  */
1924   maddr = gdbarch_convert_from_func_ptr_addr (get_frame_arch (this_frame),
1925                                               SYMBOL_VALUE_ADDRESS (msymbol),
1926                                               &current_target);
1927   return maddr == get_frame_func (this_frame);
1928 }
1929
1930 /* Test whether THIS_FRAME is inside the process entry point function.  */
1931
1932 static int
1933 inside_entry_func (struct frame_info *this_frame)
1934 {
1935   CORE_ADDR entry_point;
1936
1937   if (!entry_point_address_query (&entry_point))
1938     return 0;
1939
1940   return get_frame_func (this_frame) == entry_point;
1941 }
1942
1943 /* Return a structure containing various interesting information about
1944    the frame that called THIS_FRAME.  Returns NULL if there is entier
1945    no such frame or the frame fails any of a set of target-independent
1946    condition that should terminate the frame chain (e.g., as unwinding
1947    past main()).
1948
1949    This function should not contain target-dependent tests, such as
1950    checking whether the program-counter is zero.  */
1951
1952 struct frame_info *
1953 get_prev_frame (struct frame_info *this_frame)
1954 {
1955   CORE_ADDR frame_pc;
1956   int frame_pc_p;
1957
1958   /* There is always a frame.  If this assertion fails, suspect that
1959      something should be calling get_selected_frame() or
1960      get_current_frame().  */
1961   gdb_assert (this_frame != NULL);
1962   frame_pc_p = get_frame_pc_if_available (this_frame, &frame_pc);
1963
1964   /* tausq/2004-12-07: Dummy frames are skipped because it doesn't make much
1965      sense to stop unwinding at a dummy frame.  One place where a dummy
1966      frame may have an address "inside_main_func" is on HPUX.  On HPUX, the
1967      pcsqh register (space register for the instruction at the head of the
1968      instruction queue) cannot be written directly; the only way to set it
1969      is to branch to code that is in the target space.  In order to implement
1970      frame dummies on HPUX, the called function is made to jump back to where 
1971      the inferior was when the user function was called.  If gdb was inside 
1972      the main function when we created the dummy frame, the dummy frame will 
1973      point inside the main function.  */
1974   if (this_frame->level >= 0
1975       && get_frame_type (this_frame) == NORMAL_FRAME
1976       && !backtrace_past_main
1977       && frame_pc_p
1978       && inside_main_func (this_frame))
1979     /* Don't unwind past main().  Note, this is done _before_ the
1980        frame has been marked as previously unwound.  That way if the
1981        user later decides to enable unwinds past main(), that will
1982        automatically happen.  */
1983     {
1984       frame_debug_got_null_frame (this_frame, "inside main func");
1985       return NULL;
1986     }
1987
1988   /* If the user's backtrace limit has been exceeded, stop.  We must
1989      add two to the current level; one of those accounts for backtrace_limit
1990      being 1-based and the level being 0-based, and the other accounts for
1991      the level of the new frame instead of the level of the current
1992      frame.  */
1993   if (this_frame->level + 2 > backtrace_limit)
1994     {
1995       frame_debug_got_null_frame (this_frame, "backtrace limit exceeded");
1996       return NULL;
1997     }
1998
1999   /* If we're already inside the entry function for the main objfile,
2000      then it isn't valid.  Don't apply this test to a dummy frame -
2001      dummy frame PCs typically land in the entry func.  Don't apply
2002      this test to the sentinel frame.  Sentinel frames should always
2003      be allowed to unwind.  */
2004   /* NOTE: cagney/2003-07-07: Fixed a bug in inside_main_func() -
2005      wasn't checking for "main" in the minimal symbols.  With that
2006      fixed asm-source tests now stop in "main" instead of halting the
2007      backtrace in weird and wonderful ways somewhere inside the entry
2008      file.  Suspect that tests for inside the entry file/func were
2009      added to work around that (now fixed) case.  */
2010   /* NOTE: cagney/2003-07-15: danielj (if I'm reading it right)
2011      suggested having the inside_entry_func test use the
2012      inside_main_func() msymbol trick (along with entry_point_address()
2013      I guess) to determine the address range of the start function.
2014      That should provide a far better stopper than the current
2015      heuristics.  */
2016   /* NOTE: tausq/2004-10-09: this is needed if, for example, the compiler
2017      applied tail-call optimizations to main so that a function called 
2018      from main returns directly to the caller of main.  Since we don't
2019      stop at main, we should at least stop at the entry point of the
2020      application.  */
2021   if (this_frame->level >= 0
2022       && get_frame_type (this_frame) == NORMAL_FRAME
2023       && !backtrace_past_entry
2024       && frame_pc_p
2025       && inside_entry_func (this_frame))
2026     {
2027       frame_debug_got_null_frame (this_frame, "inside entry func");
2028       return NULL;
2029     }
2030
2031   /* Assume that the only way to get a zero PC is through something
2032      like a SIGSEGV or a dummy frame, and hence that NORMAL frames
2033      will never unwind a zero PC.  */
2034   if (this_frame->level > 0
2035       && (get_frame_type (this_frame) == NORMAL_FRAME
2036           || get_frame_type (this_frame) == INLINE_FRAME)
2037       && get_frame_type (get_next_frame (this_frame)) == NORMAL_FRAME
2038       && frame_pc_p && frame_pc == 0)
2039     {
2040       frame_debug_got_null_frame (this_frame, "zero PC");
2041       return NULL;
2042     }
2043
2044   return get_prev_frame_1 (this_frame);
2045 }
2046
2047 CORE_ADDR
2048 get_frame_pc (struct frame_info *frame)
2049 {
2050   gdb_assert (frame->next != NULL);
2051   return frame_unwind_pc (frame->next);
2052 }
2053
2054 int
2055 get_frame_pc_if_available (struct frame_info *frame, CORE_ADDR *pc)
2056 {
2057   volatile struct gdb_exception ex;
2058
2059   gdb_assert (frame->next != NULL);
2060
2061   TRY_CATCH (ex, RETURN_MASK_ERROR)
2062     {
2063       *pc = frame_unwind_pc (frame->next);
2064     }
2065   if (ex.reason < 0)
2066     {
2067       if (ex.error == NOT_AVAILABLE_ERROR)
2068         return 0;
2069       else
2070         throw_exception (ex);
2071     }
2072
2073   return 1;
2074 }
2075
2076 /* Return an address that falls within THIS_FRAME's code block.  */
2077
2078 CORE_ADDR
2079 get_frame_address_in_block (struct frame_info *this_frame)
2080 {
2081   /* A draft address.  */
2082   CORE_ADDR pc = get_frame_pc (this_frame);
2083
2084   struct frame_info *next_frame = this_frame->next;
2085
2086   /* Calling get_frame_pc returns the resume address for THIS_FRAME.
2087      Normally the resume address is inside the body of the function
2088      associated with THIS_FRAME, but there is a special case: when
2089      calling a function which the compiler knows will never return
2090      (for instance abort), the call may be the very last instruction
2091      in the calling function.  The resume address will point after the
2092      call and may be at the beginning of a different function
2093      entirely.
2094
2095      If THIS_FRAME is a signal frame or dummy frame, then we should
2096      not adjust the unwound PC.  For a dummy frame, GDB pushed the
2097      resume address manually onto the stack.  For a signal frame, the
2098      OS may have pushed the resume address manually and invoked the
2099      handler (e.g. GNU/Linux), or invoked the trampoline which called
2100      the signal handler - but in either case the signal handler is
2101      expected to return to the trampoline.  So in both of these
2102      cases we know that the resume address is executable and
2103      related.  So we only need to adjust the PC if THIS_FRAME
2104      is a normal function.
2105
2106      If the program has been interrupted while THIS_FRAME is current,
2107      then clearly the resume address is inside the associated
2108      function.  There are three kinds of interruption: debugger stop
2109      (next frame will be SENTINEL_FRAME), operating system
2110      signal or exception (next frame will be SIGTRAMP_FRAME),
2111      or debugger-induced function call (next frame will be
2112      DUMMY_FRAME).  So we only need to adjust the PC if
2113      NEXT_FRAME is a normal function.
2114
2115      We check the type of NEXT_FRAME first, since it is already
2116      known; frame type is determined by the unwinder, and since
2117      we have THIS_FRAME we've already selected an unwinder for
2118      NEXT_FRAME.
2119
2120      If the next frame is inlined, we need to keep going until we find
2121      the real function - for instance, if a signal handler is invoked
2122      while in an inlined function, then the code address of the
2123      "calling" normal function should not be adjusted either.  */
2124
2125   while (get_frame_type (next_frame) == INLINE_FRAME)
2126     next_frame = next_frame->next;
2127
2128   if ((get_frame_type (next_frame) == NORMAL_FRAME
2129        || get_frame_type (next_frame) == TAILCALL_FRAME)
2130       && (get_frame_type (this_frame) == NORMAL_FRAME
2131           || get_frame_type (this_frame) == TAILCALL_FRAME
2132           || get_frame_type (this_frame) == INLINE_FRAME))
2133     return pc - 1;
2134
2135   return pc;
2136 }
2137
2138 int
2139 get_frame_address_in_block_if_available (struct frame_info *this_frame,
2140                                          CORE_ADDR *pc)
2141 {
2142   volatile struct gdb_exception ex;
2143
2144   TRY_CATCH (ex, RETURN_MASK_ERROR)
2145     {
2146       *pc = get_frame_address_in_block (this_frame);
2147     }
2148   if (ex.reason < 0 && ex.error == NOT_AVAILABLE_ERROR)
2149     return 0;
2150   else if (ex.reason < 0)
2151     throw_exception (ex);
2152   else
2153     return 1;
2154 }
2155
2156 void
2157 find_frame_sal (struct frame_info *frame, struct symtab_and_line *sal)
2158 {
2159   struct frame_info *next_frame;
2160   int notcurrent;
2161   CORE_ADDR pc;
2162
2163   /* If the next frame represents an inlined function call, this frame's
2164      sal is the "call site" of that inlined function, which can not
2165      be inferred from get_frame_pc.  */
2166   next_frame = get_next_frame (frame);
2167   if (frame_inlined_callees (frame) > 0)
2168     {
2169       struct symbol *sym;
2170
2171       if (next_frame)
2172         sym = get_frame_function (next_frame);
2173       else
2174         sym = inline_skipped_symbol (inferior_ptid);
2175
2176       /* If frame is inline, it certainly has symbols.  */
2177       gdb_assert (sym);
2178       init_sal (sal);
2179       if (SYMBOL_LINE (sym) != 0)
2180         {
2181           sal->symtab = SYMBOL_SYMTAB (sym);
2182           sal->line = SYMBOL_LINE (sym);
2183         }
2184       else
2185         /* If the symbol does not have a location, we don't know where
2186            the call site is.  Do not pretend to.  This is jarring, but
2187            we can't do much better.  */
2188         sal->pc = get_frame_pc (frame);
2189
2190       sal->pspace = get_frame_program_space (frame);
2191
2192       return;
2193     }
2194
2195   /* If FRAME is not the innermost frame, that normally means that
2196      FRAME->pc points at the return instruction (which is *after* the
2197      call instruction), and we want to get the line containing the
2198      call (because the call is where the user thinks the program is).
2199      However, if the next frame is either a SIGTRAMP_FRAME or a
2200      DUMMY_FRAME, then the next frame will contain a saved interrupt
2201      PC and such a PC indicates the current (rather than next)
2202      instruction/line, consequently, for such cases, want to get the
2203      line containing fi->pc.  */
2204   if (!get_frame_pc_if_available (frame, &pc))
2205     {
2206       init_sal (sal);
2207       return;
2208     }
2209
2210   notcurrent = (pc != get_frame_address_in_block (frame));
2211   (*sal) = find_pc_line (pc, notcurrent);
2212 }
2213
2214 /* Per "frame.h", return the ``address'' of the frame.  Code should
2215    really be using get_frame_id().  */
2216 CORE_ADDR
2217 get_frame_base (struct frame_info *fi)
2218 {
2219   return get_frame_id (fi).stack_addr;
2220 }
2221
2222 /* High-level offsets into the frame.  Used by the debug info.  */
2223
2224 CORE_ADDR
2225 get_frame_base_address (struct frame_info *fi)
2226 {
2227   if (get_frame_type (fi) != NORMAL_FRAME)
2228     return 0;
2229   if (fi->base == NULL)
2230     fi->base = frame_base_find_by_frame (fi);
2231   /* Sneaky: If the low-level unwind and high-level base code share a
2232      common unwinder, let them share the prologue cache.  */
2233   if (fi->base->unwind == fi->unwind)
2234     return fi->base->this_base (fi, &fi->prologue_cache);
2235   return fi->base->this_base (fi, &fi->base_cache);
2236 }
2237
2238 CORE_ADDR
2239 get_frame_locals_address (struct frame_info *fi)
2240 {
2241   if (get_frame_type (fi) != NORMAL_FRAME)
2242     return 0;
2243   /* If there isn't a frame address method, find it.  */
2244   if (fi->base == NULL)
2245     fi->base = frame_base_find_by_frame (fi);
2246   /* Sneaky: If the low-level unwind and high-level base code share a
2247      common unwinder, let them share the prologue cache.  */
2248   if (fi->base->unwind == fi->unwind)
2249     return fi->base->this_locals (fi, &fi->prologue_cache);
2250   return fi->base->this_locals (fi, &fi->base_cache);
2251 }
2252
2253 CORE_ADDR
2254 get_frame_args_address (struct frame_info *fi)
2255 {
2256   if (get_frame_type (fi) != NORMAL_FRAME)
2257     return 0;
2258   /* If there isn't a frame address method, find it.  */
2259   if (fi->base == NULL)
2260     fi->base = frame_base_find_by_frame (fi);
2261   /* Sneaky: If the low-level unwind and high-level base code share a
2262      common unwinder, let them share the prologue cache.  */
2263   if (fi->base->unwind == fi->unwind)
2264     return fi->base->this_args (fi, &fi->prologue_cache);
2265   return fi->base->this_args (fi, &fi->base_cache);
2266 }
2267
2268 /* Return true if the frame unwinder for frame FI is UNWINDER; false
2269    otherwise.  */
2270
2271 int
2272 frame_unwinder_is (struct frame_info *fi, const struct frame_unwind *unwinder)
2273 {
2274   if (fi->unwind == NULL)
2275     frame_unwind_find_by_frame (fi, &fi->prologue_cache);
2276   return fi->unwind == unwinder;
2277 }
2278
2279 /* Level of the selected frame: 0 for innermost, 1 for its caller, ...
2280    or -1 for a NULL frame.  */
2281
2282 int
2283 frame_relative_level (struct frame_info *fi)
2284 {
2285   if (fi == NULL)
2286     return -1;
2287   else
2288     return fi->level;
2289 }
2290
2291 enum frame_type
2292 get_frame_type (struct frame_info *frame)
2293 {
2294   if (frame->unwind == NULL)
2295     /* Initialize the frame's unwinder because that's what
2296        provides the frame's type.  */
2297     frame_unwind_find_by_frame (frame, &frame->prologue_cache);
2298   return frame->unwind->type;
2299 }
2300
2301 struct program_space *
2302 get_frame_program_space (struct frame_info *frame)
2303 {
2304   return frame->pspace;
2305 }
2306
2307 struct program_space *
2308 frame_unwind_program_space (struct frame_info *this_frame)
2309 {
2310   gdb_assert (this_frame);
2311
2312   /* This is really a placeholder to keep the API consistent --- we
2313      assume for now that we don't have frame chains crossing
2314      spaces.  */
2315   return this_frame->pspace;
2316 }
2317
2318 struct address_space *
2319 get_frame_address_space (struct frame_info *frame)
2320 {
2321   return frame->aspace;
2322 }
2323
2324 /* Memory access methods.  */
2325
2326 void
2327 get_frame_memory (struct frame_info *this_frame, CORE_ADDR addr,
2328                   gdb_byte *buf, int len)
2329 {
2330   read_memory (addr, buf, len);
2331 }
2332
2333 LONGEST
2334 get_frame_memory_signed (struct frame_info *this_frame, CORE_ADDR addr,
2335                          int len)
2336 {
2337   struct gdbarch *gdbarch = get_frame_arch (this_frame);
2338   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
2339
2340   return read_memory_integer (addr, len, byte_order);
2341 }
2342
2343 ULONGEST
2344 get_frame_memory_unsigned (struct frame_info *this_frame, CORE_ADDR addr,
2345                            int len)
2346 {
2347   struct gdbarch *gdbarch = get_frame_arch (this_frame);
2348   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
2349
2350   return read_memory_unsigned_integer (addr, len, byte_order);
2351 }
2352
2353 int
2354 safe_frame_unwind_memory (struct frame_info *this_frame,
2355                           CORE_ADDR addr, gdb_byte *buf, int len)
2356 {
2357   /* NOTE: target_read_memory returns zero on success!  */
2358   return !target_read_memory (addr, buf, len);
2359 }
2360
2361 /* Architecture methods.  */
2362
2363 struct gdbarch *
2364 get_frame_arch (struct frame_info *this_frame)
2365 {
2366   return frame_unwind_arch (this_frame->next);
2367 }
2368
2369 struct gdbarch *
2370 frame_unwind_arch (struct frame_info *next_frame)
2371 {
2372   if (!next_frame->prev_arch.p)
2373     {
2374       struct gdbarch *arch;
2375
2376       if (next_frame->unwind == NULL)
2377         frame_unwind_find_by_frame (next_frame, &next_frame->prologue_cache);
2378
2379       if (next_frame->unwind->prev_arch != NULL)
2380         arch = next_frame->unwind->prev_arch (next_frame,
2381                                               &next_frame->prologue_cache);
2382       else
2383         arch = get_frame_arch (next_frame);
2384
2385       next_frame->prev_arch.arch = arch;
2386       next_frame->prev_arch.p = 1;
2387       if (frame_debug)
2388         fprintf_unfiltered (gdb_stdlog,
2389                             "{ frame_unwind_arch (next_frame=%d) -> %s }\n",
2390                             next_frame->level,
2391                             gdbarch_bfd_arch_info (arch)->printable_name);
2392     }
2393
2394   return next_frame->prev_arch.arch;
2395 }
2396
2397 struct gdbarch *
2398 frame_unwind_caller_arch (struct frame_info *next_frame)
2399 {
2400   return frame_unwind_arch (skip_artificial_frames (next_frame));
2401 }
2402
2403 /* Stack pointer methods.  */
2404
2405 CORE_ADDR
2406 get_frame_sp (struct frame_info *this_frame)
2407 {
2408   struct gdbarch *gdbarch = get_frame_arch (this_frame);
2409
2410   /* Normality - an architecture that provides a way of obtaining any
2411      frame inner-most address.  */
2412   if (gdbarch_unwind_sp_p (gdbarch))
2413     /* NOTE drow/2008-06-28: gdbarch_unwind_sp could be converted to
2414        operate on THIS_FRAME now.  */
2415     return gdbarch_unwind_sp (gdbarch, this_frame->next);
2416   /* Now things are really are grim.  Hope that the value returned by
2417      the gdbarch_sp_regnum register is meaningful.  */
2418   if (gdbarch_sp_regnum (gdbarch) >= 0)
2419     return get_frame_register_unsigned (this_frame,
2420                                         gdbarch_sp_regnum (gdbarch));
2421   internal_error (__FILE__, __LINE__, _("Missing unwind SP method"));
2422 }
2423
2424 /* Return the reason why we can't unwind past FRAME.  */
2425
2426 enum unwind_stop_reason
2427 get_frame_unwind_stop_reason (struct frame_info *frame)
2428 {
2429   /* If we haven't tried to unwind past this point yet, then assume
2430      that unwinding would succeed.  */
2431   if (frame->prev_p == 0)
2432     return UNWIND_NO_REASON;
2433
2434   /* Otherwise, we set a reason when we succeeded (or failed) to
2435      unwind.  */
2436   return frame->stop_reason;
2437 }
2438
2439 /* Return a string explaining REASON.  */
2440
2441 const char *
2442 frame_stop_reason_string (enum unwind_stop_reason reason)
2443 {
2444   switch (reason)
2445     {
2446 #define SET(name, description) \
2447     case name: return _(description);
2448 #include "unwind_stop_reasons.def"
2449 #undef SET
2450
2451     default:
2452       internal_error (__FILE__, __LINE__,
2453                       "Invalid frame stop reason");
2454     }
2455 }
2456
2457 /* Clean up after a failed (wrong unwinder) attempt to unwind past
2458    FRAME.  */
2459
2460 static void
2461 frame_cleanup_after_sniffer (void *arg)
2462 {
2463   struct frame_info *frame = arg;
2464
2465   /* The sniffer should not allocate a prologue cache if it did not
2466      match this frame.  */
2467   gdb_assert (frame->prologue_cache == NULL);
2468
2469   /* No sniffer should extend the frame chain; sniff based on what is
2470      already certain.  */
2471   gdb_assert (!frame->prev_p);
2472
2473   /* The sniffer should not check the frame's ID; that's circular.  */
2474   gdb_assert (!frame->this_id.p);
2475
2476   /* Clear cached fields dependent on the unwinder.
2477
2478      The previous PC is independent of the unwinder, but the previous
2479      function is not (see get_frame_address_in_block).  */
2480   frame->prev_func.p = 0;
2481   frame->prev_func.addr = 0;
2482
2483   /* Discard the unwinder last, so that we can easily find it if an assertion
2484      in this function triggers.  */
2485   frame->unwind = NULL;
2486 }
2487
2488 /* Set FRAME's unwinder temporarily, so that we can call a sniffer.
2489    Return a cleanup which should be called if unwinding fails, and
2490    discarded if it succeeds.  */
2491
2492 struct cleanup *
2493 frame_prepare_for_sniffer (struct frame_info *frame,
2494                            const struct frame_unwind *unwind)
2495 {
2496   gdb_assert (frame->unwind == NULL);
2497   frame->unwind = unwind;
2498   return make_cleanup (frame_cleanup_after_sniffer, frame);
2499 }
2500
2501 extern initialize_file_ftype _initialize_frame; /* -Wmissing-prototypes */
2502
2503 static struct cmd_list_element *set_backtrace_cmdlist;
2504 static struct cmd_list_element *show_backtrace_cmdlist;
2505
2506 static void
2507 set_backtrace_cmd (char *args, int from_tty)
2508 {
2509   help_list (set_backtrace_cmdlist, "set backtrace ", -1, gdb_stdout);
2510 }
2511
2512 static void
2513 show_backtrace_cmd (char *args, int from_tty)
2514 {
2515   cmd_show_list (show_backtrace_cmdlist, from_tty, "");
2516 }
2517
2518 void
2519 _initialize_frame (void)
2520 {
2521   obstack_init (&frame_cache_obstack);
2522
2523   frame_stash_create ();
2524
2525   observer_attach_target_changed (frame_observer_target_changed);
2526
2527   add_prefix_cmd ("backtrace", class_maintenance, set_backtrace_cmd, _("\
2528 Set backtrace specific variables.\n\
2529 Configure backtrace variables such as the backtrace limit"),
2530                   &set_backtrace_cmdlist, "set backtrace ",
2531                   0/*allow-unknown*/, &setlist);
2532   add_prefix_cmd ("backtrace", class_maintenance, show_backtrace_cmd, _("\
2533 Show backtrace specific variables\n\
2534 Show backtrace variables such as the backtrace limit"),
2535                   &show_backtrace_cmdlist, "show backtrace ",
2536                   0/*allow-unknown*/, &showlist);
2537
2538   add_setshow_boolean_cmd ("past-main", class_obscure,
2539                            &backtrace_past_main, _("\
2540 Set whether backtraces should continue past \"main\"."), _("\
2541 Show whether backtraces should continue past \"main\"."), _("\
2542 Normally the caller of \"main\" is not of interest, so GDB will terminate\n\
2543 the backtrace at \"main\".  Set this variable if you need to see the rest\n\
2544 of the stack trace."),
2545                            NULL,
2546                            show_backtrace_past_main,
2547                            &set_backtrace_cmdlist,
2548                            &show_backtrace_cmdlist);
2549
2550   add_setshow_boolean_cmd ("past-entry", class_obscure,
2551                            &backtrace_past_entry, _("\
2552 Set whether backtraces should continue past the entry point of a program."),
2553                            _("\
2554 Show whether backtraces should continue past the entry point of a program."),
2555                            _("\
2556 Normally there are no callers beyond the entry point of a program, so GDB\n\
2557 will terminate the backtrace there.  Set this variable if you need to see\n\
2558 the rest of the stack trace."),
2559                            NULL,
2560                            show_backtrace_past_entry,
2561                            &set_backtrace_cmdlist,
2562                            &show_backtrace_cmdlist);
2563
2564   add_setshow_uinteger_cmd ("limit", class_obscure,
2565                             &backtrace_limit, _("\
2566 Set an upper bound on the number of backtrace levels."), _("\
2567 Show the upper bound on the number of backtrace levels."), _("\
2568 No more than the specified number of frames can be displayed or examined.\n\
2569 Literal \"unlimited\" or zero means no limit."),
2570                             NULL,
2571                             show_backtrace_limit,
2572                             &set_backtrace_cmdlist,
2573                             &show_backtrace_cmdlist);
2574
2575   /* Debug this files internals.  */
2576   add_setshow_zuinteger_cmd ("frame", class_maintenance, &frame_debug,  _("\
2577 Set frame debugging."), _("\
2578 Show frame debugging."), _("\
2579 When non-zero, frame specific internal debugging is enabled."),
2580                              NULL,
2581                              show_frame_debug,
2582                              &setdebuglist, &showdebuglist);
2583 }