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