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