]> Git Repo - binutils.git/blob - gdb/frame.c
internal_error: remove need to pass __FILE__/__LINE__
[binutils.git] / gdb / frame.c
1 /* Cache and manage frames for GDB, the GNU debugger.
2
3    Copyright (C) 1986-2022 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 "user-regs.h"
27 #include "gdbsupport/gdb_obstack.h"
28 #include "dummy-frame.h"
29 #include "sentinel-frame.h"
30 #include "gdbcore.h"
31 #include "annotate.h"
32 #include "language.h"
33 #include "frame-unwind.h"
34 #include "frame-base.h"
35 #include "command.h"
36 #include "gdbcmd.h"
37 #include "observable.h"
38 #include "objfiles.h"
39 #include "gdbthread.h"
40 #include "block.h"
41 #include "inline-frame.h"
42 #include "tracepoint.h"
43 #include "hashtab.h"
44 #include "valprint.h"
45 #include "cli/cli-option.h"
46
47 /* The sentinel frame terminates the innermost end of the frame chain.
48    If unwound, it returns the information needed to construct an
49    innermost frame.
50
51    The current frame, which is the innermost frame, can be found at
52    sentinel_frame->prev.  */
53
54 static frame_info *sentinel_frame;
55
56 /* Number of calls to reinit_frame_cache.  */
57 static unsigned int frame_cache_generation = 0;
58
59 /* See frame-info.h.  */
60 intrusive_list<frame_info_ptr> frame_info_ptr::frame_list;
61
62 /* See frame.h.  */
63
64 unsigned int
65 get_frame_cache_generation ()
66 {
67   return frame_cache_generation;
68 }
69
70 /* The values behind the global "set backtrace ..." settings.  */
71 set_backtrace_options user_set_backtrace_options;
72
73 static frame_info_ptr get_prev_frame_raw (frame_info_ptr this_frame);
74 static const char *frame_stop_reason_symbol_string (enum unwind_stop_reason reason);
75
76 /* Status of some values cached in the frame_info object.  */
77
78 enum cached_copy_status
79 {
80   /* Value is unknown.  */
81   CC_UNKNOWN,
82
83   /* We have a value.  */
84   CC_VALUE,
85
86   /* Value was not saved.  */
87   CC_NOT_SAVED,
88
89   /* Value is unavailable.  */
90   CC_UNAVAILABLE
91 };
92
93 enum class frame_id_status
94 {
95   /* Frame id is not computed.  */
96   NOT_COMPUTED = 0,
97
98   /* Frame id is being computed (compute_frame_id is active).  */
99   COMPUTING,
100
101   /* Frame id has been computed.  */
102   COMPUTED,
103 };
104
105 /* We keep a cache of stack frames, each of which is a "struct
106    frame_info".  The innermost one gets allocated (in
107    wait_for_inferior) each time the inferior stops; sentinel_frame
108    points to it.  Additional frames get allocated (in get_prev_frame)
109    as needed, and are chained through the next and prev fields.  Any
110    time that the frame cache becomes invalid (most notably when we
111    execute something, but also if we change how we interpret the
112    frames (e.g. "set heuristic-fence-post" in mips-tdep.c, or anything
113    which reads new symbols)), we should call reinit_frame_cache.  */
114
115 struct frame_info
116 {
117   /* Return a string representation of this frame.  */
118   std::string to_string () const;
119
120   /* Level of this frame.  The inner-most (youngest) frame is at level
121      0.  As you move towards the outer-most (oldest) frame, the level
122      increases.  This is a cached value.  It could just as easily be
123      computed by counting back from the selected frame to the inner
124      most frame.  */
125   /* NOTE: cagney/2002-04-05: Perhaps a level of ``-1'' should be
126      reserved to indicate a bogus frame - one that has been created
127      just to keep GDB happy (GDB always needs a frame).  For the
128      moment leave this as speculation.  */
129   int level;
130
131   /* The frame's program space.  */
132   struct program_space *pspace;
133
134   /* The frame's address space.  */
135   const address_space *aspace;
136
137   /* The frame's low-level unwinder and corresponding cache.  The
138      low-level unwinder is responsible for unwinding register values
139      for the previous frame.  The low-level unwind methods are
140      selected based on the presence, or otherwise, of register unwind
141      information such as CFI.  */
142   void *prologue_cache;
143   const struct frame_unwind *unwind;
144
145   /* Cached copy of the previous frame's architecture.  */
146   struct
147   {
148     bool p;
149     struct gdbarch *arch;
150   } prev_arch;
151
152   /* Cached copy of the previous frame's resume address.  */
153   struct {
154     cached_copy_status status;
155     /* Did VALUE require unmasking when being read.  */
156     bool masked;
157     CORE_ADDR value;
158   } prev_pc;
159
160   /* Cached copy of the previous frame's function address.  */
161   struct
162   {
163     CORE_ADDR addr;
164     cached_copy_status status;
165   } prev_func;
166
167   /* This frame's ID.  */
168   struct
169   {
170     frame_id_status p;
171     struct frame_id value;
172   } this_id;
173
174   /* The frame's high-level base methods, and corresponding cache.
175      The high level base methods are selected based on the frame's
176      debug info.  */
177   const struct frame_base *base;
178   void *base_cache;
179
180   /* Pointers to the next (down, inner, younger) and previous (up,
181      outer, older) frame_info's in the frame cache.  */
182   struct frame_info *next; /* down, inner, younger */
183   bool prev_p;
184   struct frame_info *prev; /* up, outer, older */
185
186   /* The reason why we could not set PREV, or UNWIND_NO_REASON if we
187      could.  Only valid when PREV_P is set.  */
188   enum unwind_stop_reason stop_reason;
189
190   /* A frame specific string describing the STOP_REASON in more detail.
191      Only valid when PREV_P is set, but even then may still be NULL.  */
192   const char *stop_string;
193 };
194
195 /* See frame.h.  */
196
197 void
198 set_frame_previous_pc_masked (frame_info_ptr frame)
199 {
200   frame->prev_pc.masked = true;
201 }
202
203 /* See frame.h.  */
204
205 bool
206 get_frame_pc_masked (frame_info_ptr frame)
207 {
208   gdb_assert (frame->next != nullptr);
209   gdb_assert (frame->next->prev_pc.status == CC_VALUE);
210
211   return frame->next->prev_pc.masked;
212 }
213
214 /* A frame stash used to speed up frame lookups.  Create a hash table
215    to stash frames previously accessed from the frame cache for
216    quicker subsequent retrieval.  The hash table is emptied whenever
217    the frame cache is invalidated.  */
218
219 static htab_t frame_stash;
220
221 /* Internal function to calculate a hash from the frame_id addresses,
222    using as many valid addresses as possible.  Frames below level 0
223    are not stored in the hash table.  */
224
225 static hashval_t
226 frame_addr_hash (const void *ap)
227 {
228   const frame_info *frame = (const frame_info *) ap;
229   const struct frame_id f_id = frame->this_id.value;
230   hashval_t hash = 0;
231
232   gdb_assert (f_id.stack_status != FID_STACK_INVALID
233               || f_id.code_addr_p
234               || f_id.special_addr_p);
235
236   if (f_id.stack_status == FID_STACK_VALID)
237     hash = iterative_hash (&f_id.stack_addr,
238                            sizeof (f_id.stack_addr), hash);
239   if (f_id.code_addr_p)
240     hash = iterative_hash (&f_id.code_addr,
241                            sizeof (f_id.code_addr), hash);
242   if (f_id.special_addr_p)
243     hash = iterative_hash (&f_id.special_addr,
244                            sizeof (f_id.special_addr), hash);
245
246   return hash;
247 }
248
249 /* Internal equality function for the hash table.  This function
250    defers equality operations to frame_id::operator==.  */
251
252 static int
253 frame_addr_hash_eq (const void *a, const void *b)
254 {
255   const frame_info *f_entry = (const frame_info *) a;
256   const frame_info *f_element = (const frame_info *) b;
257
258   return f_entry->this_id.value == f_element->this_id.value;
259 }
260
261 /* Internal function to create the frame_stash hash table.  100 seems
262    to be a good compromise to start the hash table at.  */
263
264 static void
265 frame_stash_create (void)
266 {
267   frame_stash = htab_create (100,
268                              frame_addr_hash,
269                              frame_addr_hash_eq,
270                              NULL);
271 }
272
273 /* Internal function to add a frame to the frame_stash hash table.
274    Returns false if a frame with the same ID was already stashed, true
275    otherwise.  */
276
277 static bool
278 frame_stash_add (frame_info *frame)
279 {
280   /* Do not try to stash the sentinel frame.  */
281   gdb_assert (frame->level >= 0);
282
283   frame_info **slot = (frame_info **) htab_find_slot (frame_stash,
284                                                       frame, INSERT);
285
286   /* If we already have a frame in the stack with the same id, we
287      either have a stack cycle (corrupted stack?), or some bug
288      elsewhere in GDB.  In any case, ignore the duplicate and return
289      an indication to the caller.  */
290   if (*slot != nullptr)
291     return false;
292
293   *slot = frame;
294   return true;
295 }
296
297 /* Internal function to search the frame stash for an entry with the
298    given frame ID.  If found, return that frame.  Otherwise return
299    NULL.  */
300
301 static frame_info_ptr 
302 frame_stash_find (struct frame_id id)
303 {
304   struct frame_info dummy;
305   frame_info *frame;
306
307   dummy.this_id.value = id;
308   frame = (frame_info *) htab_find (frame_stash, &dummy);
309   return frame_info_ptr (frame);
310 }
311
312 /* Internal function to invalidate the frame stash by removing all
313    entries in it.  This only occurs when the frame cache is
314    invalidated.  */
315
316 static void
317 frame_stash_invalidate (void)
318 {
319   htab_empty (frame_stash);
320 }
321
322 /* See frame.h  */
323 scoped_restore_selected_frame::scoped_restore_selected_frame ()
324 {
325   m_lang = current_language->la_language;
326   save_selected_frame (&m_fid, &m_level);
327 }
328
329 /* See frame.h  */
330 scoped_restore_selected_frame::~scoped_restore_selected_frame ()
331 {
332   restore_selected_frame (m_fid, m_level);
333   set_language (m_lang);
334 }
335
336 /* Flag to control debugging.  */
337
338 bool frame_debug;
339
340 static void
341 show_frame_debug (struct ui_file *file, int from_tty,
342                   struct cmd_list_element *c, const char *value)
343 {
344   gdb_printf (file, _("Frame debugging is %s.\n"), value);
345 }
346
347 /* Implementation of "show backtrace past-main".  */
348
349 static void
350 show_backtrace_past_main (struct ui_file *file, int from_tty,
351                           struct cmd_list_element *c, const char *value)
352 {
353   gdb_printf (file,
354               _("Whether backtraces should "
355                 "continue past \"main\" is %s.\n"),
356               value);
357 }
358
359 /* Implementation of "show backtrace past-entry".  */
360
361 static void
362 show_backtrace_past_entry (struct ui_file *file, int from_tty,
363                            struct cmd_list_element *c, const char *value)
364 {
365   gdb_printf (file, _("Whether backtraces should continue past the "
366                       "entry point of a program is %s.\n"),
367               value);
368 }
369
370 /* Implementation of "show backtrace limit".  */
371
372 static void
373 show_backtrace_limit (struct ui_file *file, int from_tty,
374                       struct cmd_list_element *c, const char *value)
375 {
376   gdb_printf (file,
377               _("An upper bound on the number "
378                 "of backtrace levels is %s.\n"),
379               value);
380 }
381
382 /* See frame.h.  */
383
384 std::string
385 frame_id::to_string () const
386 {
387   const struct frame_id &id = *this;
388
389   std::string res = "{";
390
391   if (id.stack_status == FID_STACK_INVALID)
392     res += "!stack";
393   else if (id.stack_status == FID_STACK_UNAVAILABLE)
394     res += "stack=<unavailable>";
395   else if (id.stack_status == FID_STACK_SENTINEL)
396     res += "stack=<sentinel>";
397   else if (id.stack_status == FID_STACK_OUTER)
398     res += "stack=<outer>";
399   else
400     res += std::string ("stack=") + hex_string (id.stack_addr);
401
402   /* Helper function to format 'N=A' if P is true, otherwise '!N'.  */
403   auto field_to_string = [] (const char *n, bool p, CORE_ADDR a) -> std::string
404   {
405     if (p)
406       return std::string (n) + "=" + core_addr_to_string (a);
407     else
408       return std::string ("!") + std::string (n);
409   };
410
411   res += (std::string (",")
412           + field_to_string ("code", id.code_addr_p, id.code_addr)
413           + std::string (",")
414           + field_to_string ("special", id.special_addr_p, id.special_addr));
415
416   if (id.artificial_depth)
417     res += ",artificial=" + std::to_string (id.artificial_depth);
418   res += "}";
419   return res;
420 }
421
422 /* Return a string representation of TYPE.  */
423
424 static const char *
425 frame_type_str (frame_type type)
426 {
427   switch (type)
428     {
429     case NORMAL_FRAME:
430       return "NORMAL_FRAME";
431
432     case DUMMY_FRAME:
433       return "DUMMY_FRAME";
434
435     case INLINE_FRAME:
436       return "INLINE_FRAME";
437
438     case TAILCALL_FRAME:
439       return "TAILCALL_FRAME";
440
441     case SIGTRAMP_FRAME:
442       return "SIGTRAMP_FRAME";
443
444     case ARCH_FRAME:
445       return "ARCH_FRAME";
446
447     case SENTINEL_FRAME:
448       return "SENTINEL_FRAME";
449
450     default:
451       return "<unknown type>";
452     };
453 }
454
455  /* See struct frame_info.  */
456
457 std::string
458 frame_info::to_string () const
459 {
460   const frame_info *fi = this;
461
462   std::string res;
463
464   res += string_printf ("{level=%d,", fi->level);
465
466   if (fi->unwind != NULL)
467     res += string_printf ("type=%s,", frame_type_str (fi->unwind->type));
468   else
469     res += "type=<unknown>,";
470
471   if (fi->unwind != NULL)
472     res += string_printf ("unwinder=\"%s\",", fi->unwind->name);
473   else
474     res += "unwinder=<unknown>,";
475
476   if (fi->next == NULL || fi->next->prev_pc.status == CC_UNKNOWN)
477     res += "pc=<unknown>,";
478   else if (fi->next->prev_pc.status == CC_VALUE)
479     res += string_printf ("pc=%s%s,", hex_string (fi->next->prev_pc.value),
480                           fi->next->prev_pc.masked ? "[PAC]" : "");
481   else if (fi->next->prev_pc.status == CC_NOT_SAVED)
482     res += "pc=<not saved>,";
483   else if (fi->next->prev_pc.status == CC_UNAVAILABLE)
484     res += "pc=<unavailable>,";
485
486   if (fi->this_id.p == frame_id_status::NOT_COMPUTED)
487     res += "id=<not computed>,";
488   else if (fi->this_id.p == frame_id_status::COMPUTING)
489     res += "id=<computing>,";
490   else
491     res += string_printf ("id=%s,", fi->this_id.value.to_string ().c_str ());
492
493   if (fi->next != NULL && fi->next->prev_func.status == CC_VALUE)
494     res += string_printf ("func=%s", hex_string (fi->next->prev_func.addr));
495   else
496     res += "func=<unknown>";
497
498   res += "}";
499
500   return res;
501 }
502
503 /* Given FRAME, return the enclosing frame as found in real frames read-in from
504    inferior memory.  Skip any previous frames which were made up by GDB.
505    Return FRAME if FRAME is a non-artificial frame.
506    Return NULL if FRAME is the start of an artificial-only chain.  */
507
508 static frame_info_ptr 
509 skip_artificial_frames (frame_info_ptr frame)
510 {
511   /* Note we use get_prev_frame_always, and not get_prev_frame.  The
512      latter will truncate the frame chain, leading to this function
513      unintentionally returning a null_frame_id (e.g., when the user
514      sets a backtrace limit).
515
516      Note that for record targets we may get a frame chain that consists
517      of artificial frames only.  */
518   while (get_frame_type (frame) == INLINE_FRAME
519          || get_frame_type (frame) == TAILCALL_FRAME)
520     {
521       frame = get_prev_frame_always (frame);
522       if (frame == NULL)
523         break;
524     }
525
526   return frame;
527 }
528
529 frame_info_ptr 
530 skip_unwritable_frames (frame_info_ptr frame)
531 {
532   while (gdbarch_code_of_frame_writable (get_frame_arch (frame), frame) == 0)
533     {
534       frame = get_prev_frame (frame);
535       if (frame == NULL)
536         break;
537     }
538
539   return frame;
540 }
541
542 /* See frame.h.  */
543
544 frame_info_ptr 
545 skip_tailcall_frames (frame_info_ptr frame)
546 {
547   while (get_frame_type (frame) == TAILCALL_FRAME)
548     {
549       /* Note that for record targets we may get a frame chain that consists of
550          tailcall frames only.  */
551       frame = get_prev_frame (frame);
552       if (frame == NULL)
553         break;
554     }
555
556   return frame;
557 }
558
559 /* Compute the frame's uniq ID that can be used to, later, re-find the
560    frame.  */
561
562 static void
563 compute_frame_id (frame_info_ptr fi)
564 {
565   FRAME_SCOPED_DEBUG_ENTER_EXIT;
566
567   gdb_assert (fi->this_id.p == frame_id_status::NOT_COMPUTED);
568
569   unsigned int entry_generation = get_frame_cache_generation ();
570
571   try
572     {
573       /* Mark this frame's id as "being computed.  */
574       fi->this_id.p = frame_id_status::COMPUTING;
575
576       frame_debug_printf ("fi=%d", fi->level);
577
578       /* Find the unwinder.  */
579       if (fi->unwind == NULL)
580         frame_unwind_find_by_frame (fi, &fi->prologue_cache);
581
582       /* Find THIS frame's ID.  */
583       /* Default to outermost if no ID is found.  */
584       fi->this_id.value = outer_frame_id;
585       fi->unwind->this_id (fi, &fi->prologue_cache, &fi->this_id.value);
586       gdb_assert (frame_id_p (fi->this_id.value));
587
588       /* Mark this frame's id as "computed".  */
589       fi->this_id.p = frame_id_status::COMPUTED;
590
591       frame_debug_printf ("  -> %s", fi->this_id.value.to_string ().c_str ());
592     }
593   catch (const gdb_exception &ex)
594     {
595       /* On error, revert the frame id status to not computed.  If the frame
596          cache generation changed, the frame object doesn't exist anymore, so
597          don't touch it.  */
598       if (get_frame_cache_generation () == entry_generation)
599         fi->this_id.p = frame_id_status::NOT_COMPUTED;
600
601       throw;
602     }
603 }
604
605 /* Return a frame uniq ID that can be used to, later, re-find the
606    frame.  */
607
608 struct frame_id
609 get_frame_id (frame_info_ptr fi)
610 {
611   if (fi == NULL)
612     return null_frame_id;
613
614   /* It's always invalid to try to get a frame's id while it is being
615      computed.  */
616   gdb_assert (fi->this_id.p != frame_id_status::COMPUTING);
617
618   if (fi->this_id.p == frame_id_status::NOT_COMPUTED)
619     {
620       /* If we haven't computed the frame id yet, then it must be that
621          this is the current frame.  Compute it now, and stash the
622          result.  The IDs of other frames are computed as soon as
623          they're created, in order to detect cycles.  See
624          get_prev_frame_if_no_cycle.  */
625       gdb_assert (fi->level == 0);
626
627       /* Compute.  */
628       compute_frame_id (fi);
629
630       /* Since this is the first frame in the chain, this should
631          always succeed.  */
632       bool stashed = frame_stash_add (fi.get ());
633       gdb_assert (stashed);
634     }
635
636   return fi->this_id.value;
637 }
638
639 struct frame_id
640 get_stack_frame_id (frame_info_ptr next_frame)
641 {
642   return get_frame_id (skip_artificial_frames (next_frame));
643 }
644
645 struct frame_id
646 frame_unwind_caller_id (frame_info_ptr next_frame)
647 {
648   frame_info_ptr this_frame;
649
650   /* Use get_prev_frame_always, and not get_prev_frame.  The latter
651      will truncate the frame chain, leading to this function
652      unintentionally returning a null_frame_id (e.g., when a caller
653      requests the frame ID of "main()"s caller.  */
654
655   next_frame = skip_artificial_frames (next_frame);
656   if (next_frame == NULL)
657     return null_frame_id;
658
659   this_frame = get_prev_frame_always (next_frame);
660   if (this_frame)
661     return get_frame_id (skip_artificial_frames (this_frame));
662   else
663     return null_frame_id;
664 }
665
666 const struct frame_id null_frame_id = { 0 }; /* All zeros.  */
667 const struct frame_id sentinel_frame_id = { 0, 0, 0, FID_STACK_SENTINEL, 0, 1, 0 };
668 const struct frame_id outer_frame_id = { 0, 0, 0, FID_STACK_OUTER, 0, 1, 0 };
669
670 struct frame_id
671 frame_id_build_special (CORE_ADDR stack_addr, CORE_ADDR code_addr,
672                         CORE_ADDR special_addr)
673 {
674   struct frame_id id = null_frame_id;
675
676   id.stack_addr = stack_addr;
677   id.stack_status = FID_STACK_VALID;
678   id.code_addr = code_addr;
679   id.code_addr_p = true;
680   id.special_addr = special_addr;
681   id.special_addr_p = true;
682   return id;
683 }
684
685 /* See frame.h.  */
686
687 struct frame_id
688 frame_id_build_unavailable_stack (CORE_ADDR code_addr)
689 {
690   struct frame_id id = null_frame_id;
691
692   id.stack_status = FID_STACK_UNAVAILABLE;
693   id.code_addr = code_addr;
694   id.code_addr_p = true;
695   return id;
696 }
697
698 /* See frame.h.  */
699
700 struct frame_id
701 frame_id_build_unavailable_stack_special (CORE_ADDR code_addr,
702                                           CORE_ADDR special_addr)
703 {
704   struct frame_id id = null_frame_id;
705
706   id.stack_status = FID_STACK_UNAVAILABLE;
707   id.code_addr = code_addr;
708   id.code_addr_p = true;
709   id.special_addr = special_addr;
710   id.special_addr_p = true;
711   return id;
712 }
713
714 struct frame_id
715 frame_id_build (CORE_ADDR stack_addr, CORE_ADDR code_addr)
716 {
717   struct frame_id id = null_frame_id;
718
719   id.stack_addr = stack_addr;
720   id.stack_status = FID_STACK_VALID;
721   id.code_addr = code_addr;
722   id.code_addr_p = true;
723   return id;
724 }
725
726 struct frame_id
727 frame_id_build_wild (CORE_ADDR stack_addr)
728 {
729   struct frame_id id = null_frame_id;
730
731   id.stack_addr = stack_addr;
732   id.stack_status = FID_STACK_VALID;
733   return id;
734 }
735
736 bool
737 frame_id_p (frame_id l)
738 {
739   /* The frame is valid iff it has a valid stack address.  */
740   bool p = l.stack_status != FID_STACK_INVALID;
741
742   frame_debug_printf ("l=%s -> %d", l.to_string ().c_str (), p);
743
744   return p;
745 }
746
747 bool
748 frame_id_artificial_p (frame_id l)
749 {
750   if (!frame_id_p (l))
751     return false;
752
753   return l.artificial_depth != 0;
754 }
755
756 bool
757 frame_id::operator== (const frame_id &r) const
758 {
759   bool eq;
760
761   if (stack_status == FID_STACK_INVALID
762       || r.stack_status == FID_STACK_INVALID)
763     /* Like a NaN, if either ID is invalid, the result is false.
764        Note that a frame ID is invalid iff it is the null frame ID.  */
765     eq = false;
766   else if (stack_status != r.stack_status || stack_addr != r.stack_addr)
767     /* If .stack addresses are different, the frames are different.  */
768     eq = false;
769   else if (code_addr_p && r.code_addr_p && code_addr != r.code_addr)
770     /* An invalid code addr is a wild card.  If .code addresses are
771        different, the frames are different.  */
772     eq = false;
773   else if (special_addr_p && r.special_addr_p
774            && special_addr != r.special_addr)
775     /* An invalid special addr is a wild card (or unused).  Otherwise
776        if special addresses are different, the frames are different.  */
777     eq = false;
778   else if (artificial_depth != r.artificial_depth)
779     /* If artificial depths are different, the frames must be different.  */
780     eq = false;
781   else
782     /* Frames are equal.  */
783     eq = true;
784
785   frame_debug_printf ("l=%s, r=%s -> %d",
786                       to_string ().c_str (), r.to_string ().c_str (), eq);
787
788   return eq;
789 }
790
791 /* Safety net to check whether frame ID L should be inner to
792    frame ID R, according to their stack addresses.
793
794    This method cannot be used to compare arbitrary frames, as the
795    ranges of valid stack addresses may be discontiguous (e.g. due
796    to sigaltstack).
797
798    However, it can be used as safety net to discover invalid frame
799    IDs in certain circumstances.  Assuming that NEXT is the immediate
800    inner frame to THIS and that NEXT and THIS are both NORMAL frames:
801
802    * The stack address of NEXT must be inner-than-or-equal to the stack
803      address of THIS.
804
805      Therefore, if frame_id_inner (THIS, NEXT) holds, some unwind
806      error has occurred.
807
808    * If NEXT and THIS have different stack addresses, no other frame
809      in the frame chain may have a stack address in between.
810
811      Therefore, if frame_id_inner (TEST, THIS) holds, but
812      frame_id_inner (TEST, NEXT) does not hold, TEST cannot refer
813      to a valid frame in the frame chain.
814
815    The sanity checks above cannot be performed when a SIGTRAMP frame
816    is involved, because signal handlers might be executed on a different
817    stack than the stack used by the routine that caused the signal
818    to be raised.  This can happen for instance when a thread exceeds
819    its maximum stack size.  In this case, certain compilers implement
820    a stack overflow strategy that cause the handler to be run on a
821    different stack.  */
822
823 static bool
824 frame_id_inner (struct gdbarch *gdbarch, struct frame_id l, struct frame_id r)
825 {
826   bool inner;
827
828   if (l.stack_status != FID_STACK_VALID || r.stack_status != FID_STACK_VALID)
829     /* Like NaN, any operation involving an invalid ID always fails.
830        Likewise if either ID has an unavailable stack address.  */
831     inner = false;
832   else if (l.artificial_depth > r.artificial_depth
833            && l.stack_addr == r.stack_addr
834            && l.code_addr_p == r.code_addr_p
835            && l.special_addr_p == r.special_addr_p
836            && l.special_addr == r.special_addr)
837     {
838       /* Same function, different inlined functions.  */
839       const struct block *lb, *rb;
840
841       gdb_assert (l.code_addr_p && r.code_addr_p);
842
843       lb = block_for_pc (l.code_addr);
844       rb = block_for_pc (r.code_addr);
845
846       if (lb == NULL || rb == NULL)
847         /* Something's gone wrong.  */
848         inner = false;
849       else
850         /* This will return true if LB and RB are the same block, or
851            if the block with the smaller depth lexically encloses the
852            block with the greater depth.  */
853         inner = contained_in (lb, rb);
854     }
855   else
856     /* Only return non-zero when strictly inner than.  Note that, per
857        comment in "frame.h", there is some fuzz here.  Frameless
858        functions are not strictly inner than (same .stack but
859        different .code and/or .special address).  */
860     inner = gdbarch_inner_than (gdbarch, l.stack_addr, r.stack_addr);
861
862   frame_debug_printf ("is l=%s inner than r=%s? %d",
863                       l.to_string ().c_str (), r.to_string ().c_str (),
864                       inner);
865
866   return inner;
867 }
868
869 frame_info_ptr 
870 frame_find_by_id (struct frame_id id)
871 {
872   frame_info_ptr frame, prev_frame;
873
874   /* ZERO denotes the null frame, let the caller decide what to do
875      about it.  Should it instead return get_current_frame()?  */
876   if (!frame_id_p (id))
877     return NULL;
878
879   /* Check for the sentinel frame.  */
880   if (id == sentinel_frame_id)
881     return frame_info_ptr (sentinel_frame);
882
883   /* Try using the frame stash first.  Finding it there removes the need
884      to perform the search by looping over all frames, which can be very
885      CPU-intensive if the number of frames is very high (the loop is O(n)
886      and get_prev_frame performs a series of checks that are relatively
887      expensive).  This optimization is particularly useful when this function
888      is called from another function (such as value_fetch_lazy, case
889      VALUE_LVAL (val) == lval_register) which already loops over all frames,
890      making the overall behavior O(n^2).  */
891   frame = frame_stash_find (id);
892   if (frame)
893     return frame;
894
895   for (frame = get_current_frame (); ; frame = prev_frame)
896     {
897       struct frame_id self = get_frame_id (frame);
898
899       if (id == self)
900         /* An exact match.  */
901         return frame;
902
903       prev_frame = get_prev_frame (frame);
904       if (!prev_frame)
905         return NULL;
906
907       /* As a safety net to avoid unnecessary backtracing while trying
908          to find an invalid ID, we check for a common situation where
909          we can detect from comparing stack addresses that no other
910          frame in the current frame chain can have this ID.  See the
911          comment at frame_id_inner for details.   */
912       if (get_frame_type (frame) == NORMAL_FRAME
913           && !frame_id_inner (get_frame_arch (frame), id, self)
914           && frame_id_inner (get_frame_arch (prev_frame), id,
915                              get_frame_id (prev_frame)))
916         return NULL;
917     }
918   return NULL;
919 }
920
921 static CORE_ADDR
922 frame_unwind_pc (frame_info_ptr this_frame)
923 {
924   if (this_frame->prev_pc.status == CC_UNKNOWN)
925     {
926       struct gdbarch *prev_gdbarch;
927       CORE_ADDR pc = 0;
928       bool pc_p = false;
929
930       /* The right way.  The `pure' way.  The one true way.  This
931          method depends solely on the register-unwind code to
932          determine the value of registers in THIS frame, and hence
933          the value of this frame's PC (resume address).  A typical
934          implementation is no more than:
935
936          frame_unwind_register (this_frame, ISA_PC_REGNUM, buf);
937          return extract_unsigned_integer (buf, size of ISA_PC_REGNUM);
938
939          Note: this method is very heavily dependent on a correct
940          register-unwind implementation, it pays to fix that
941          method first; this method is frame type agnostic, since
942          it only deals with register values, it works with any
943          frame.  This is all in stark contrast to the old
944          FRAME_SAVED_PC which would try to directly handle all the
945          different ways that a PC could be unwound.  */
946       prev_gdbarch = frame_unwind_arch (this_frame);
947
948       try
949         {
950           pc = gdbarch_unwind_pc (prev_gdbarch, this_frame);
951           pc_p = true;
952         }
953       catch (const gdb_exception_error &ex)
954         {
955           if (ex.error == NOT_AVAILABLE_ERROR)
956             {
957               this_frame->prev_pc.status = CC_UNAVAILABLE;
958
959               frame_debug_printf ("this_frame=%d -> <unavailable>",
960                                   this_frame->level);
961             }
962           else if (ex.error == OPTIMIZED_OUT_ERROR)
963             {
964               this_frame->prev_pc.status = CC_NOT_SAVED;
965
966               frame_debug_printf ("this_frame=%d -> <not saved>",
967                                   this_frame->level);
968             }
969           else
970             throw;
971         }
972
973       if (pc_p)
974         {
975           this_frame->prev_pc.value = pc;
976           this_frame->prev_pc.status = CC_VALUE;
977
978           frame_debug_printf ("this_frame=%d -> %s",
979                               this_frame->level,
980                               hex_string (this_frame->prev_pc.value));
981         }
982     }
983
984   if (this_frame->prev_pc.status == CC_VALUE)
985     return this_frame->prev_pc.value;
986   else if (this_frame->prev_pc.status == CC_UNAVAILABLE)
987     throw_error (NOT_AVAILABLE_ERROR, _("PC not available"));
988   else if (this_frame->prev_pc.status == CC_NOT_SAVED)
989     throw_error (OPTIMIZED_OUT_ERROR, _("PC not saved"));
990   else
991     internal_error ("unexpected prev_pc status: %d",
992                     (int) this_frame->prev_pc.status);
993 }
994
995 CORE_ADDR
996 frame_unwind_caller_pc (frame_info_ptr this_frame)
997 {
998   this_frame = skip_artificial_frames (this_frame);
999
1000   /* We must have a non-artificial frame.  The caller is supposed to check
1001      the result of frame_unwind_caller_id (), which returns NULL_FRAME_ID
1002      in this case.  */
1003   gdb_assert (this_frame != NULL);
1004
1005   return frame_unwind_pc (this_frame);
1006 }
1007
1008 bool
1009 get_frame_func_if_available (frame_info_ptr this_frame, CORE_ADDR *pc)
1010 {
1011   frame_info *next_frame = this_frame->next;
1012
1013   if (next_frame->prev_func.status == CC_UNKNOWN)
1014     {
1015       CORE_ADDR addr_in_block;
1016
1017       /* Make certain that this, and not the adjacent, function is
1018          found.  */
1019       if (!get_frame_address_in_block_if_available (this_frame, &addr_in_block))
1020         {
1021           next_frame->prev_func.status = CC_UNAVAILABLE;
1022
1023           frame_debug_printf ("this_frame=%d -> unavailable",
1024                               this_frame->level);
1025         }
1026       else
1027         {
1028           next_frame->prev_func.status = CC_VALUE;
1029           next_frame->prev_func.addr = get_pc_function_start (addr_in_block);
1030
1031           frame_debug_printf ("this_frame=%d -> %s",
1032                               this_frame->level,
1033                               hex_string (next_frame->prev_func.addr));
1034         }
1035     }
1036
1037   if (next_frame->prev_func.status == CC_UNAVAILABLE)
1038     {
1039       *pc = -1;
1040       return false;
1041     }
1042   else
1043     {
1044       gdb_assert (next_frame->prev_func.status == CC_VALUE);
1045
1046       *pc = next_frame->prev_func.addr;
1047       return true;
1048     }
1049 }
1050
1051 CORE_ADDR
1052 get_frame_func (frame_info_ptr this_frame)
1053 {
1054   CORE_ADDR pc;
1055
1056   if (!get_frame_func_if_available (this_frame, &pc))
1057     throw_error (NOT_AVAILABLE_ERROR, _("PC not available"));
1058
1059   return pc;
1060 }
1061
1062 std::unique_ptr<readonly_detached_regcache>
1063 frame_save_as_regcache (frame_info_ptr this_frame)
1064 {
1065   auto cooked_read = [this_frame] (int regnum, gdb_byte *buf)
1066     {
1067       if (!deprecated_frame_register_read (this_frame, regnum, buf))
1068         return REG_UNAVAILABLE;
1069       else
1070         return REG_VALID;
1071     };
1072
1073   std::unique_ptr<readonly_detached_regcache> regcache
1074     (new readonly_detached_regcache (get_frame_arch (this_frame), cooked_read));
1075
1076   return regcache;
1077 }
1078
1079 void
1080 frame_pop (frame_info_ptr this_frame)
1081 {
1082   frame_info_ptr prev_frame;
1083
1084   if (get_frame_type (this_frame) == DUMMY_FRAME)
1085     {
1086       /* Popping a dummy frame involves restoring more than just registers.
1087          dummy_frame_pop does all the work.  */
1088       dummy_frame_pop (get_frame_id (this_frame), inferior_thread ());
1089       return;
1090     }
1091
1092   /* Ensure that we have a frame to pop to.  */
1093   prev_frame = get_prev_frame_always (this_frame);
1094
1095   if (!prev_frame)
1096     error (_("Cannot pop the initial frame."));
1097
1098   /* Ignore TAILCALL_FRAME type frames, they were executed already before
1099      entering THISFRAME.  */
1100   prev_frame = skip_tailcall_frames (prev_frame);
1101
1102   if (prev_frame == NULL)
1103     error (_("Cannot find the caller frame."));
1104
1105   /* Make a copy of all the register values unwound from this frame.
1106      Save them in a scratch buffer so that there isn't a race between
1107      trying to extract the old values from the current regcache while
1108      at the same time writing new values into that same cache.  */
1109   std::unique_ptr<readonly_detached_regcache> scratch
1110     = frame_save_as_regcache (prev_frame);
1111
1112   /* FIXME: cagney/2003-03-16: It should be possible to tell the
1113      target's register cache that it is about to be hit with a burst
1114      register transfer and that the sequence of register writes should
1115      be batched.  The pair target_prepare_to_store() and
1116      target_store_registers() kind of suggest this functionality.
1117      Unfortunately, they don't implement it.  Their lack of a formal
1118      definition can lead to targets writing back bogus values
1119      (arguably a bug in the target code mind).  */
1120   /* Now copy those saved registers into the current regcache.  */
1121   get_current_regcache ()->restore (scratch.get ());
1122
1123   /* We've made right mess of GDB's local state, just discard
1124      everything.  */
1125   reinit_frame_cache ();
1126 }
1127
1128 void
1129 frame_register_unwind (frame_info_ptr next_frame, int regnum,
1130                        int *optimizedp, int *unavailablep,
1131                        enum lval_type *lvalp, CORE_ADDR *addrp,
1132                        int *realnump, gdb_byte *bufferp)
1133 {
1134   struct value *value;
1135
1136   /* Require all but BUFFERP to be valid.  A NULL BUFFERP indicates
1137      that the value proper does not need to be fetched.  */
1138   gdb_assert (optimizedp != NULL);
1139   gdb_assert (lvalp != NULL);
1140   gdb_assert (addrp != NULL);
1141   gdb_assert (realnump != NULL);
1142   /* gdb_assert (bufferp != NULL); */
1143
1144   value = frame_unwind_register_value (next_frame, regnum);
1145
1146   gdb_assert (value != NULL);
1147
1148   *optimizedp = value_optimized_out (value);
1149   *unavailablep = !value_entirely_available (value);
1150   *lvalp = VALUE_LVAL (value);
1151   *addrp = value_address (value);
1152   if (*lvalp == lval_register)
1153     *realnump = VALUE_REGNUM (value);
1154   else
1155     *realnump = -1;
1156
1157   if (bufferp)
1158     {
1159       if (!*optimizedp && !*unavailablep)
1160         memcpy (bufferp, value_contents_all (value).data (),
1161                 value_type (value)->length ());
1162       else
1163         memset (bufferp, 0, value_type (value)->length ());
1164     }
1165
1166   /* Dispose of the new value.  This prevents watchpoints from
1167      trying to watch the saved frame pointer.  */
1168   release_value (value);
1169 }
1170
1171 void
1172 frame_register (frame_info_ptr frame, int regnum,
1173                 int *optimizedp, int *unavailablep, enum lval_type *lvalp,
1174                 CORE_ADDR *addrp, int *realnump, gdb_byte *bufferp)
1175 {
1176   /* Require all but BUFFERP to be valid.  A NULL BUFFERP indicates
1177      that the value proper does not need to be fetched.  */
1178   gdb_assert (optimizedp != NULL);
1179   gdb_assert (lvalp != NULL);
1180   gdb_assert (addrp != NULL);
1181   gdb_assert (realnump != NULL);
1182   /* gdb_assert (bufferp != NULL); */
1183
1184   /* Obtain the register value by unwinding the register from the next
1185      (more inner frame).  */
1186   gdb_assert (frame != NULL && frame->next != NULL);
1187   frame_register_unwind (frame_info_ptr (frame->next), regnum, optimizedp,
1188                          unavailablep, lvalp, addrp, realnump, bufferp);
1189 }
1190
1191 void
1192 frame_unwind_register (frame_info_ptr next_frame, int regnum, gdb_byte *buf)
1193 {
1194   int optimized;
1195   int unavailable;
1196   CORE_ADDR addr;
1197   int realnum;
1198   enum lval_type lval;
1199
1200   frame_register_unwind (next_frame, regnum, &optimized, &unavailable,
1201                          &lval, &addr, &realnum, buf);
1202
1203   if (optimized)
1204     throw_error (OPTIMIZED_OUT_ERROR,
1205                  _("Register %d was not saved"), regnum);
1206   if (unavailable)
1207     throw_error (NOT_AVAILABLE_ERROR,
1208                  _("Register %d is not available"), regnum);
1209 }
1210
1211 void
1212 get_frame_register (frame_info_ptr frame,
1213                     int regnum, gdb_byte *buf)
1214 {
1215   frame_unwind_register (frame_info_ptr (frame->next), regnum, buf);
1216 }
1217
1218 struct value *
1219 frame_unwind_register_value (frame_info_ptr next_frame, int regnum)
1220 {
1221   FRAME_SCOPED_DEBUG_ENTER_EXIT;
1222
1223   gdb_assert (next_frame != NULL);
1224   gdbarch *gdbarch = frame_unwind_arch (next_frame);
1225   frame_debug_printf ("frame=%d, regnum=%d(%s)",
1226                       next_frame->level, regnum,
1227                       user_reg_map_regnum_to_name (gdbarch, regnum));
1228
1229   /* Find the unwinder.  */
1230   if (next_frame->unwind == NULL)
1231     frame_unwind_find_by_frame (next_frame, &next_frame->prologue_cache);
1232
1233   /* Ask this frame to unwind its register.  */
1234   value *value = next_frame->unwind->prev_register (next_frame,
1235                                                     &next_frame->prologue_cache,
1236                                                     regnum);
1237
1238   if (frame_debug)
1239     {
1240       string_file debug_file;
1241
1242       gdb_printf (&debug_file, "  ->");
1243       if (value_optimized_out (value))
1244         {
1245           gdb_printf (&debug_file, " ");
1246           val_print_not_saved (&debug_file);
1247         }
1248       else
1249         {
1250           if (VALUE_LVAL (value) == lval_register)
1251             gdb_printf (&debug_file, " register=%d",
1252                         VALUE_REGNUM (value));
1253           else if (VALUE_LVAL (value) == lval_memory)
1254             gdb_printf (&debug_file, " address=%s",
1255                         paddress (gdbarch,
1256                                   value_address (value)));
1257           else
1258             gdb_printf (&debug_file, " computed");
1259
1260           if (value_lazy (value))
1261             gdb_printf (&debug_file, " lazy");
1262           else
1263             {
1264               int i;
1265               gdb::array_view<const gdb_byte> buf = value_contents (value);
1266
1267               gdb_printf (&debug_file, " bytes=");
1268               gdb_printf (&debug_file, "[");
1269               for (i = 0; i < register_size (gdbarch, regnum); i++)
1270                 gdb_printf (&debug_file, "%02x", buf[i]);
1271               gdb_printf (&debug_file, "]");
1272             }
1273         }
1274
1275       frame_debug_printf ("%s", debug_file.c_str ());
1276     }
1277
1278   return value;
1279 }
1280
1281 struct value *
1282 get_frame_register_value (frame_info_ptr frame, int regnum)
1283 {
1284   return frame_unwind_register_value (frame_info_ptr (frame->next), regnum);
1285 }
1286
1287 LONGEST
1288 frame_unwind_register_signed (frame_info_ptr next_frame, int regnum)
1289 {
1290   struct gdbarch *gdbarch = frame_unwind_arch (next_frame);
1291   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
1292   struct value *value = frame_unwind_register_value (next_frame, regnum);
1293
1294   gdb_assert (value != NULL);
1295
1296   if (value_optimized_out (value))
1297     {
1298       throw_error (OPTIMIZED_OUT_ERROR,
1299                    _("Register %d was not saved"), regnum);
1300     }
1301   if (!value_entirely_available (value))
1302     {
1303       throw_error (NOT_AVAILABLE_ERROR,
1304                    _("Register %d is not available"), regnum);
1305     }
1306
1307   LONGEST r = extract_signed_integer (value_contents_all (value), byte_order);
1308
1309   release_value (value);
1310   return r;
1311 }
1312
1313 LONGEST
1314 get_frame_register_signed (frame_info_ptr frame, int regnum)
1315 {
1316   return frame_unwind_register_signed (frame_info_ptr (frame->next), regnum);
1317 }
1318
1319 ULONGEST
1320 frame_unwind_register_unsigned (frame_info_ptr next_frame, int regnum)
1321 {
1322   struct gdbarch *gdbarch = frame_unwind_arch (next_frame);
1323   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
1324   int size = register_size (gdbarch, regnum);
1325   struct value *value = frame_unwind_register_value (next_frame, regnum);
1326
1327   gdb_assert (value != NULL);
1328
1329   if (value_optimized_out (value))
1330     {
1331       throw_error (OPTIMIZED_OUT_ERROR,
1332                    _("Register %d was not saved"), regnum);
1333     }
1334   if (!value_entirely_available (value))
1335     {
1336       throw_error (NOT_AVAILABLE_ERROR,
1337                    _("Register %d is not available"), regnum);
1338     }
1339
1340   ULONGEST r = extract_unsigned_integer (value_contents_all (value).data (),
1341                                          size, byte_order);
1342
1343   release_value (value);
1344   return r;
1345 }
1346
1347 ULONGEST
1348 get_frame_register_unsigned (frame_info_ptr frame, int regnum)
1349 {
1350   return frame_unwind_register_unsigned (frame_info_ptr (frame->next), regnum);
1351 }
1352
1353 bool
1354 read_frame_register_unsigned (frame_info_ptr frame, int regnum,
1355                               ULONGEST *val)
1356 {
1357   struct value *regval = get_frame_register_value (frame, regnum);
1358
1359   if (!value_optimized_out (regval)
1360       && value_entirely_available (regval))
1361     {
1362       struct gdbarch *gdbarch = get_frame_arch (frame);
1363       enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
1364       int size = register_size (gdbarch, VALUE_REGNUM (regval));
1365
1366       *val = extract_unsigned_integer (value_contents (regval).data (), size,
1367                                        byte_order);
1368       return true;
1369     }
1370
1371   return false;
1372 }
1373
1374 void
1375 put_frame_register (frame_info_ptr frame, int regnum,
1376                     const gdb_byte *buf)
1377 {
1378   struct gdbarch *gdbarch = get_frame_arch (frame);
1379   int realnum;
1380   int optim;
1381   int unavail;
1382   enum lval_type lval;
1383   CORE_ADDR addr;
1384
1385   frame_register (frame, regnum, &optim, &unavail,
1386                   &lval, &addr, &realnum, NULL);
1387   if (optim)
1388     error (_("Attempt to assign to a register that was not saved."));
1389   switch (lval)
1390     {
1391     case lval_memory:
1392       {
1393         write_memory (addr, buf, register_size (gdbarch, regnum));
1394         break;
1395       }
1396     case lval_register:
1397       get_current_regcache ()->cooked_write (realnum, buf);
1398       break;
1399     default:
1400       error (_("Attempt to assign to an unmodifiable value."));
1401     }
1402 }
1403
1404 /* This function is deprecated.  Use get_frame_register_value instead,
1405    which provides more accurate information.
1406
1407    Find and return the value of REGNUM for the specified stack frame.
1408    The number of bytes copied is REGISTER_SIZE (REGNUM).
1409
1410    Returns 0 if the register value could not be found.  */
1411
1412 bool
1413 deprecated_frame_register_read (frame_info_ptr frame, int regnum,
1414                                 gdb_byte *myaddr)
1415 {
1416   int optimized;
1417   int unavailable;
1418   enum lval_type lval;
1419   CORE_ADDR addr;
1420   int realnum;
1421
1422   frame_register (frame, regnum, &optimized, &unavailable,
1423                   &lval, &addr, &realnum, myaddr);
1424
1425   return !optimized && !unavailable;
1426 }
1427
1428 bool
1429 get_frame_register_bytes (frame_info_ptr frame, int regnum,
1430                           CORE_ADDR offset,
1431                           gdb::array_view<gdb_byte> buffer,
1432                           int *optimizedp, int *unavailablep)
1433 {
1434   struct gdbarch *gdbarch = get_frame_arch (frame);
1435   int i;
1436   int maxsize;
1437   int numregs;
1438
1439   /* Skip registers wholly inside of OFFSET.  */
1440   while (offset >= register_size (gdbarch, regnum))
1441     {
1442       offset -= register_size (gdbarch, regnum);
1443       regnum++;
1444     }
1445
1446   /* Ensure that we will not read beyond the end of the register file.
1447      This can only ever happen if the debug information is bad.  */
1448   maxsize = -offset;
1449   numregs = gdbarch_num_cooked_regs (gdbarch);
1450   for (i = regnum; i < numregs; i++)
1451     {
1452       int thissize = register_size (gdbarch, i);
1453
1454       if (thissize == 0)
1455         break;  /* This register is not available on this architecture.  */
1456       maxsize += thissize;
1457     }
1458
1459   int len = buffer.size ();
1460   if (len > maxsize)
1461     error (_("Bad debug information detected: "
1462              "Attempt to read %d bytes from registers."), len);
1463
1464   /* Copy the data.  */
1465   while (len > 0)
1466     {
1467       int curr_len = register_size (gdbarch, regnum) - offset;
1468
1469       if (curr_len > len)
1470         curr_len = len;
1471
1472       gdb_byte *myaddr = buffer.data ();
1473
1474       if (curr_len == register_size (gdbarch, regnum))
1475         {
1476           enum lval_type lval;
1477           CORE_ADDR addr;
1478           int realnum;
1479
1480           frame_register (frame, regnum, optimizedp, unavailablep,
1481                           &lval, &addr, &realnum, myaddr);
1482           if (*optimizedp || *unavailablep)
1483             return false;
1484         }
1485       else
1486         {
1487           struct value *value
1488             = frame_unwind_register_value (frame_info_ptr (frame->next),
1489                                            regnum);
1490           gdb_assert (value != NULL);
1491           *optimizedp = value_optimized_out (value);
1492           *unavailablep = !value_entirely_available (value);
1493
1494           if (*optimizedp || *unavailablep)
1495             {
1496               release_value (value);
1497               return false;
1498             }
1499
1500           memcpy (myaddr, value_contents_all (value).data () + offset,
1501                   curr_len);
1502           release_value (value);
1503         }
1504
1505       myaddr += curr_len;
1506       len -= curr_len;
1507       offset = 0;
1508       regnum++;
1509     }
1510
1511   *optimizedp = 0;
1512   *unavailablep = 0;
1513
1514   return true;
1515 }
1516
1517 void
1518 put_frame_register_bytes (frame_info_ptr frame, int regnum,
1519                           CORE_ADDR offset,
1520                           gdb::array_view<const gdb_byte> buffer)
1521 {
1522   struct gdbarch *gdbarch = get_frame_arch (frame);
1523
1524   /* Skip registers wholly inside of OFFSET.  */
1525   while (offset >= register_size (gdbarch, regnum))
1526     {
1527       offset -= register_size (gdbarch, regnum);
1528       regnum++;
1529     }
1530
1531   int len = buffer.size ();
1532   /* Copy the data.  */
1533   while (len > 0)
1534     {
1535       int curr_len = register_size (gdbarch, regnum) - offset;
1536
1537       if (curr_len > len)
1538         curr_len = len;
1539
1540       const gdb_byte *myaddr = buffer.data ();
1541       if (curr_len == register_size (gdbarch, regnum))
1542         {
1543           put_frame_register (frame, regnum, myaddr);
1544         }
1545       else
1546         {
1547           struct value *value
1548             = frame_unwind_register_value (frame_info_ptr (frame->next),
1549                                            regnum);
1550           gdb_assert (value != NULL);
1551
1552           memcpy ((char *) value_contents_writeable (value).data () + offset,
1553                   myaddr, curr_len);
1554           put_frame_register (frame, regnum,
1555                               value_contents_raw (value).data ());
1556           release_value (value);
1557         }
1558
1559       myaddr += curr_len;
1560       len -= curr_len;
1561       offset = 0;
1562       regnum++;
1563     }
1564 }
1565
1566 /* Create a sentinel frame.  */
1567
1568 static frame_info *
1569 create_sentinel_frame (struct program_space *pspace, struct regcache *regcache)
1570 {
1571   frame_info *frame = FRAME_OBSTACK_ZALLOC (struct frame_info);
1572
1573   frame->level = -1;
1574   frame->pspace = pspace;
1575   frame->aspace = regcache->aspace ();
1576   /* Explicitly initialize the sentinel frame's cache.  Provide it
1577      with the underlying regcache.  In the future additional
1578      information, such as the frame's thread will be added.  */
1579   frame->prologue_cache = sentinel_frame_cache (regcache);
1580   /* For the moment there is only one sentinel frame implementation.  */
1581   frame->unwind = &sentinel_frame_unwind;
1582   /* Link this frame back to itself.  The frame is self referential
1583      (the unwound PC is the same as the pc), so make it so.  */
1584   frame->next = frame;
1585   /* The sentinel frame has a special ID.  */
1586   frame->this_id.p = frame_id_status::COMPUTED;
1587   frame->this_id.value = sentinel_frame_id;
1588
1589   frame_debug_printf ("  -> %s", frame->to_string ().c_str ());
1590
1591   return frame;
1592 }
1593
1594 /* Cache for frame addresses already read by gdb.  Valid only while
1595    inferior is stopped.  Control variables for the frame cache should
1596    be local to this module.  */
1597
1598 static struct obstack frame_cache_obstack;
1599
1600 void *
1601 frame_obstack_zalloc (unsigned long size)
1602 {
1603   void *data = obstack_alloc (&frame_cache_obstack, size);
1604
1605   memset (data, 0, size);
1606   return data;
1607 }
1608
1609 static frame_info_ptr get_prev_frame_always_1 (frame_info_ptr this_frame);
1610
1611 frame_info_ptr 
1612 get_current_frame (void)
1613 {
1614   frame_info_ptr current_frame;
1615
1616   /* First check, and report, the lack of registers.  Having GDB
1617      report "No stack!" or "No memory" when the target doesn't even
1618      have registers is very confusing.  Besides, "printcmd.exp"
1619      explicitly checks that ``print $pc'' with no registers prints "No
1620      registers".  */
1621   if (!target_has_registers ())
1622     error (_("No registers."));
1623   if (!target_has_stack ())
1624     error (_("No stack."));
1625   if (!target_has_memory ())
1626     error (_("No memory."));
1627   /* Traceframes are effectively a substitute for the live inferior.  */
1628   if (get_traceframe_number () < 0)
1629     validate_registers_access ();
1630
1631   if (sentinel_frame == NULL)
1632     sentinel_frame =
1633       create_sentinel_frame (current_program_space, get_current_regcache ());
1634
1635   /* Set the current frame before computing the frame id, to avoid
1636      recursion inside compute_frame_id, in case the frame's
1637      unwinder decides to do a symbol lookup (which depends on the
1638      selected frame's block).
1639
1640      This call must always succeed.  In particular, nothing inside
1641      get_prev_frame_always_1 should try to unwind from the
1642      sentinel frame, because that could fail/throw, and we always
1643      want to leave with the current frame created and linked in --
1644      we should never end up with the sentinel frame as outermost
1645      frame.  */
1646   current_frame = get_prev_frame_always_1 (frame_info_ptr (sentinel_frame));
1647   gdb_assert (current_frame != NULL);
1648
1649   return current_frame;
1650 }
1651
1652 /* The "selected" stack frame is used by default for local and arg
1653    access.
1654
1655    The "single source of truth" for the selected frame is the
1656    SELECTED_FRAME_ID / SELECTED_FRAME_LEVEL pair.
1657
1658    Frame IDs can be saved/restored across reinitializing the frame
1659    cache, while frame_info pointers can't (frame_info objects are
1660    invalidated).  If we know the corresponding frame_info object, it
1661    is cached in SELECTED_FRAME.
1662
1663    If SELECTED_FRAME_ID / SELECTED_FRAME_LEVEL are null_frame_id / -1,
1664    and the target has stack and is stopped, the selected frame is the
1665    current (innermost) frame.  This means that SELECTED_FRAME_LEVEL is
1666    never 0 and SELECTED_FRAME_ID is never the ID of the innermost
1667    frame.
1668
1669    If SELECTED_FRAME_ID / SELECTED_FRAME_LEVEL are null_frame_id / -1,
1670    and the target has no stack or is executing, then there's no
1671    selected frame.  */
1672 static frame_id selected_frame_id = null_frame_id;
1673 static int selected_frame_level = -1;
1674
1675 /* The cached frame_info object pointing to the selected frame.
1676    Looked up on demand by get_selected_frame.  */
1677 static frame_info_ptr selected_frame;
1678
1679 /* See frame.h.  */
1680
1681 void
1682 save_selected_frame (frame_id *frame_id, int *frame_level)
1683   noexcept
1684 {
1685   *frame_id = selected_frame_id;
1686   *frame_level = selected_frame_level;
1687 }
1688
1689 /* See frame.h.  */
1690
1691 void
1692 restore_selected_frame (frame_id frame_id, int frame_level)
1693   noexcept
1694 {
1695   /* save_selected_frame never returns level == 0, so we shouldn't see
1696      it here either.  */
1697   gdb_assert (frame_level != 0);
1698
1699   /* FRAME_ID can be null_frame_id only IFF frame_level is -1.  */
1700   gdb_assert ((frame_level == -1 && !frame_id_p (frame_id))
1701               || (frame_level != -1 && frame_id_p (frame_id)));
1702
1703   selected_frame_id = frame_id;
1704   selected_frame_level = frame_level;
1705
1706   /* Will be looked up later by get_selected_frame.  */
1707   selected_frame = nullptr;
1708 }
1709
1710 /* See frame.h.  */
1711
1712 void
1713 lookup_selected_frame (struct frame_id a_frame_id, int frame_level)
1714 {
1715   frame_info_ptr frame = NULL;
1716   int count;
1717
1718   /* This either means there was no selected frame, or the selected
1719      frame was the current frame.  In either case, select the current
1720      frame.  */
1721   if (frame_level == -1)
1722     {
1723       select_frame (get_current_frame ());
1724       return;
1725     }
1726
1727   /* select_frame never saves 0 in SELECTED_FRAME_LEVEL, so we
1728      shouldn't see it here.  */
1729   gdb_assert (frame_level > 0);
1730
1731   /* Restore by level first, check if the frame id is the same as
1732      expected.  If that fails, try restoring by frame id.  If that
1733      fails, nothing to do, just warn the user.  */
1734
1735   count = frame_level;
1736   frame = find_relative_frame (get_current_frame (), &count);
1737   if (count == 0
1738       && frame != NULL
1739       /* The frame ids must match - either both valid or both
1740          outer_frame_id.  The latter case is not failsafe, but since
1741          it's highly unlikely the search by level finds the wrong
1742          frame, it's 99.9(9)% of the time (for all practical purposes)
1743          safe.  */
1744       && get_frame_id (frame) == a_frame_id)
1745     {
1746       /* Cool, all is fine.  */
1747       select_frame (frame);
1748       return;
1749     }
1750
1751   frame = frame_find_by_id (a_frame_id);
1752   if (frame != NULL)
1753     {
1754       /* Cool, refound it.  */
1755       select_frame (frame);
1756       return;
1757     }
1758
1759   /* Nothing else to do, the frame layout really changed.  Select the
1760      innermost stack frame.  */
1761   select_frame (get_current_frame ());
1762
1763   /* Warn the user.  */
1764   if (frame_level > 0 && !current_uiout->is_mi_like_p ())
1765     {
1766       warning (_("Couldn't restore frame #%d in "
1767                  "current thread.  Bottom (innermost) frame selected:"),
1768                frame_level);
1769       /* For MI, we should probably have a notification about current
1770          frame change.  But this error is not very likely, so don't
1771          bother for now.  */
1772       print_stack_frame (get_selected_frame (NULL), 1, SRC_AND_LOC, 1);
1773     }
1774 }
1775
1776 bool
1777 has_stack_frames ()
1778 {
1779   if (!target_has_registers () || !target_has_stack ()
1780       || !target_has_memory ())
1781     return false;
1782
1783   /* Traceframes are effectively a substitute for the live inferior.  */
1784   if (get_traceframe_number () < 0)
1785     {
1786       /* No current inferior, no frame.  */
1787       if (inferior_ptid == null_ptid)
1788         return false;
1789
1790       thread_info *tp = inferior_thread ();
1791       /* Don't try to read from a dead thread.  */
1792       if (tp->state == THREAD_EXITED)
1793         return false;
1794
1795       /* ... or from a spinning thread.  */
1796       if (tp->executing ())
1797         return false;
1798     }
1799
1800   return true;
1801 }
1802
1803 /* See frame.h.  */
1804
1805 frame_info_ptr 
1806 get_selected_frame (const char *message)
1807 {
1808   if (selected_frame == NULL)
1809     {
1810       if (message != NULL && !has_stack_frames ())
1811         error (("%s"), message);
1812
1813       lookup_selected_frame (selected_frame_id, selected_frame_level);
1814     }
1815   /* There is always a frame.  */
1816   gdb_assert (selected_frame != NULL);
1817   return selected_frame;
1818 }
1819
1820 /* This is a variant of get_selected_frame() which can be called when
1821    the inferior does not have a frame; in that case it will return
1822    NULL instead of calling error().  */
1823
1824 frame_info_ptr 
1825 deprecated_safe_get_selected_frame (void)
1826 {
1827   if (!has_stack_frames ())
1828     return NULL;
1829   return get_selected_frame (NULL);
1830 }
1831
1832 /* Select frame FI (or NULL - to invalidate the selected frame).  */
1833
1834 void
1835 select_frame (frame_info_ptr fi)
1836 {
1837   selected_frame = fi;
1838   selected_frame_level = frame_relative_level (fi);
1839   if (selected_frame_level == 0)
1840     {
1841       /* Treat the current frame especially -- we want to always
1842          save/restore it without warning, even if the frame ID changes
1843          (see lookup_selected_frame).  E.g.:
1844
1845           // The current frame is selected, the target had just stopped.
1846           {
1847             scoped_restore_selected_frame restore_frame;
1848             some_operation_that_changes_the_stack ();
1849           }
1850           // scoped_restore_selected_frame's dtor runs, but the
1851           // original frame_id can't be found.  No matter whether it
1852           // is found or not, we still end up with the now-current
1853           // frame selected.  Warning in lookup_selected_frame in this
1854           // case seems pointless.
1855
1856          Also get_frame_id may access the target's registers/memory,
1857          and thus skipping get_frame_id optimizes the common case.
1858
1859          Saving the selected frame this way makes get_selected_frame
1860          and restore_current_frame return/re-select whatever frame is
1861          the innermost (current) then.  */
1862       selected_frame_level = -1;
1863       selected_frame_id = null_frame_id;
1864     }
1865   else
1866     selected_frame_id = get_frame_id (fi);
1867
1868   /* NOTE: cagney/2002-05-04: FI can be NULL.  This occurs when the
1869      frame is being invalidated.  */
1870
1871   /* FIXME: kseitz/2002-08-28: It would be nice to call
1872      selected_frame_level_changed_event() right here, but due to limitations
1873      in the current interfaces, we would end up flooding UIs with events
1874      because select_frame() is used extensively internally.
1875
1876      Once we have frame-parameterized frame (and frame-related) commands,
1877      the event notification can be moved here, since this function will only
1878      be called when the user's selected frame is being changed.  */
1879
1880   /* Ensure that symbols for this frame are read in.  Also, determine the
1881      source language of this frame, and switch to it if desired.  */
1882   if (fi)
1883     {
1884       CORE_ADDR pc;
1885
1886       /* We retrieve the frame's symtab by using the frame PC.
1887          However we cannot use the frame PC as-is, because it usually
1888          points to the instruction following the "call", which is
1889          sometimes the first instruction of another function.  So we
1890          rely on get_frame_address_in_block() which provides us with a
1891          PC which is guaranteed to be inside the frame's code
1892          block.  */
1893       if (get_frame_address_in_block_if_available (fi, &pc))
1894         {
1895           struct compunit_symtab *cust = find_pc_compunit_symtab (pc);
1896
1897           if (cust != NULL
1898               && compunit_language (cust) != current_language->la_language
1899               && compunit_language (cust) != language_unknown
1900               && language_mode == language_mode_auto)
1901             set_language (compunit_language (cust));
1902         }
1903     }
1904 }
1905
1906 /* Create an arbitrary (i.e. address specified by user) or innermost frame.
1907    Always returns a non-NULL value.  */
1908
1909 frame_info_ptr 
1910 create_new_frame (CORE_ADDR addr, CORE_ADDR pc)
1911 {
1912   frame_info *fi;
1913
1914   frame_debug_printf ("addr=%s, pc=%s", hex_string (addr), hex_string (pc));
1915
1916   fi = FRAME_OBSTACK_ZALLOC (struct frame_info);
1917
1918   fi->next = create_sentinel_frame (current_program_space,
1919                                     get_current_regcache ());
1920
1921   /* Set/update this frame's cached PC value, found in the next frame.
1922      Do this before looking for this frame's unwinder.  A sniffer is
1923      very likely to read this, and the corresponding unwinder is
1924      entitled to rely that the PC doesn't magically change.  */
1925   fi->next->prev_pc.value = pc;
1926   fi->next->prev_pc.status = CC_VALUE;
1927
1928   /* We currently assume that frame chain's can't cross spaces.  */
1929   fi->pspace = fi->next->pspace;
1930   fi->aspace = fi->next->aspace;
1931
1932   /* Select/initialize both the unwind function and the frame's type
1933      based on the PC.  */
1934   frame_unwind_find_by_frame (frame_info_ptr (fi), &fi->prologue_cache);
1935
1936   fi->this_id.p = frame_id_status::COMPUTED;
1937   fi->this_id.value = frame_id_build (addr, pc);
1938
1939   frame_debug_printf ("  -> %s", fi->to_string ().c_str ());
1940
1941   return frame_info_ptr (fi);
1942 }
1943
1944 /* Return the frame that THIS_FRAME calls (NULL if THIS_FRAME is the
1945    innermost frame).  Be careful to not fall off the bottom of the
1946    frame chain and onto the sentinel frame.  */
1947
1948 frame_info_ptr 
1949 get_next_frame (frame_info_ptr this_frame)
1950 {
1951   if (this_frame->level > 0)
1952     return frame_info_ptr (this_frame->next);
1953   else
1954     return NULL;
1955 }
1956
1957 /* Return the frame that THIS_FRAME calls.  If THIS_FRAME is the
1958    innermost (i.e. current) frame, return the sentinel frame.  Thus,
1959    unlike get_next_frame(), NULL will never be returned.  */
1960
1961 frame_info_ptr 
1962 get_next_frame_sentinel_okay (frame_info_ptr this_frame)
1963 {
1964   gdb_assert (this_frame != NULL);
1965
1966   /* Note that, due to the manner in which the sentinel frame is
1967      constructed, this_frame->next still works even when this_frame
1968      is the sentinel frame.  But we disallow it here anyway because
1969      calling get_next_frame_sentinel_okay() on the sentinel frame
1970      is likely a coding error.  */
1971   gdb_assert (this_frame != sentinel_frame);
1972
1973   return frame_info_ptr (this_frame->next);
1974 }
1975
1976 /* Observer for the target_changed event.  */
1977
1978 static void
1979 frame_observer_target_changed (struct target_ops *target)
1980 {
1981   reinit_frame_cache ();
1982 }
1983
1984 /* Flush the entire frame cache.  */
1985
1986 void
1987 reinit_frame_cache (void)
1988 {
1989   ++frame_cache_generation;
1990
1991   /* Tear down all frame caches.  */
1992   for (frame_info *fi = sentinel_frame; fi != NULL; fi = fi->prev)
1993     {
1994       if (fi->prologue_cache && fi->unwind->dealloc_cache)
1995         fi->unwind->dealloc_cache (fi, fi->prologue_cache);
1996       if (fi->base_cache && fi->base->unwind->dealloc_cache)
1997         fi->base->unwind->dealloc_cache (fi, fi->base_cache);
1998     }
1999
2000   /* Since we can't really be sure what the first object allocated was.  */
2001   obstack_free (&frame_cache_obstack, 0);
2002   obstack_init (&frame_cache_obstack);
2003
2004   if (sentinel_frame != NULL)
2005     annotate_frames_invalid ();
2006
2007   sentinel_frame = NULL;                /* Invalidate cache */
2008   select_frame (NULL);
2009   frame_stash_invalidate ();
2010
2011   for (frame_info_ptr &iter : frame_info_ptr::frame_list)
2012     iter.invalidate ();
2013
2014   frame_debug_printf ("generation=%d", frame_cache_generation);
2015 }
2016
2017 /* Find where a register is saved (in memory or another register).
2018    The result of frame_register_unwind is just where it is saved
2019    relative to this particular frame.  */
2020
2021 static void
2022 frame_register_unwind_location (frame_info_ptr this_frame, int regnum,
2023                                 int *optimizedp, enum lval_type *lvalp,
2024                                 CORE_ADDR *addrp, int *realnump)
2025 {
2026   gdb_assert (this_frame == NULL || this_frame->level >= 0);
2027
2028   while (this_frame != NULL)
2029     {
2030       int unavailable;
2031
2032       frame_register_unwind (this_frame, regnum, optimizedp, &unavailable,
2033                              lvalp, addrp, realnump, NULL);
2034
2035       if (*optimizedp)
2036         break;
2037
2038       if (*lvalp != lval_register)
2039         break;
2040
2041       regnum = *realnump;
2042       this_frame = get_next_frame (this_frame);
2043     }
2044 }
2045
2046 /* Get the previous raw frame, and check that it is not identical to
2047    same other frame frame already in the chain.  If it is, there is
2048    most likely a stack cycle, so we discard it, and mark THIS_FRAME as
2049    outermost, with UNWIND_SAME_ID stop reason.  Unlike the other
2050    validity tests, that compare THIS_FRAME and the next frame, we do
2051    this right after creating the previous frame, to avoid ever ending
2052    up with two frames with the same id in the frame chain.
2053
2054    There is however, one case where this cycle detection is not desirable,
2055    when asking for the previous frame of an inline frame, in this case, if
2056    the previous frame is a duplicate and we return nullptr then we will be
2057    unable to calculate the frame_id of the inline frame, this in turn
2058    causes inline_frame_this_id() to fail.  So for inline frames (and only
2059    for inline frames), the previous frame will always be returned, even when it
2060    has a duplicate frame_id.  We're not worried about cycles in the frame
2061    chain as, if the previous frame returned here has a duplicate frame_id,
2062    then the frame_id of the inline frame, calculated based off the frame_id
2063    of the previous frame, should also be a duplicate.  */
2064
2065 static frame_info_ptr 
2066 get_prev_frame_maybe_check_cycle (frame_info_ptr this_frame)
2067 {
2068   frame_info_ptr prev_frame = get_prev_frame_raw (this_frame);
2069
2070   /* Don't compute the frame id of the current frame yet.  Unwinding
2071      the sentinel frame can fail (e.g., if the thread is gone and we
2072      can't thus read its registers).  If we let the cycle detection
2073      code below try to compute a frame ID, then an error thrown from
2074      within the frame ID computation would result in the sentinel
2075      frame as outermost frame, which is bogus.  Instead, we'll compute
2076      the current frame's ID lazily in get_frame_id.  Note that there's
2077      no point in doing cycle detection when there's only one frame, so
2078      nothing is lost here.  */
2079   if (prev_frame->level == 0)
2080     return prev_frame;
2081
2082   unsigned int entry_generation = get_frame_cache_generation ();
2083
2084   try
2085     {
2086       compute_frame_id (prev_frame);
2087
2088       bool cycle_detection_p = get_frame_type (this_frame) != INLINE_FRAME;
2089
2090       /* This assert checks GDB's state with respect to calculating the
2091          frame-id of THIS_FRAME, in the case where THIS_FRAME is an inline
2092          frame.
2093
2094          If THIS_FRAME is frame #0, and is an inline frame, then we put off
2095          calculating the frame_id until we specifically make a call to
2096          get_frame_id().  As a result we can enter this function in two
2097          possible states.  If GDB asked for the previous frame of frame #0
2098          then THIS_FRAME will be frame #0 (an inline frame), and the
2099          frame_id will be in the NOT_COMPUTED state.  However, if GDB asked
2100          for the frame_id of frame #0, then, as getting the frame_id of an
2101          inline frame requires us to get the frame_id of the previous
2102          frame, we will still end up in here, and the frame_id status will
2103          be COMPUTING.
2104
2105          If, instead, THIS_FRAME is at a level greater than #0 then things
2106          are simpler.  For these frames we immediately compute the frame_id
2107          when the frame is initially created, and so, for those frames, we
2108          will always enter this function with the frame_id status of
2109          COMPUTING.  */
2110       gdb_assert (cycle_detection_p
2111                   || (this_frame->level > 0
2112                       && (this_frame->this_id.p
2113                           == frame_id_status::COMPUTING))
2114                   || (this_frame->level == 0
2115                       && (this_frame->this_id.p
2116                           != frame_id_status::COMPUTED)));
2117
2118       /* We must do the CYCLE_DETECTION_P check after attempting to add
2119          PREV_FRAME into the cache; if PREV_FRAME is unique then we do want
2120          it in the cache, but if it is a duplicate and CYCLE_DETECTION_P is
2121          false, then we don't want to unlink it.  */
2122       if (!frame_stash_add (prev_frame.get ()) && cycle_detection_p)
2123         {
2124           /* Another frame with the same id was already in the stash.  We just
2125              detected a cycle.  */
2126           frame_debug_printf ("  -> nullptr // this frame has same ID");
2127
2128           this_frame->stop_reason = UNWIND_SAME_ID;
2129           /* Unlink.  */
2130           prev_frame->next = NULL;
2131           this_frame->prev = NULL;
2132           prev_frame = NULL;
2133         }
2134     }
2135   catch (const gdb_exception &ex)
2136     {
2137       if (get_frame_cache_generation () == entry_generation)
2138         {
2139           prev_frame->next = NULL;
2140           this_frame->prev = NULL;
2141         }
2142
2143       throw;
2144     }
2145
2146   return prev_frame;
2147 }
2148
2149 /* Helper function for get_prev_frame_always, this is called inside a
2150    TRY_CATCH block.  Return the frame that called THIS_FRAME or NULL if
2151    there is no such frame.  This may throw an exception.  */
2152
2153 static frame_info_ptr 
2154 get_prev_frame_always_1 (frame_info_ptr this_frame)
2155 {
2156   FRAME_SCOPED_DEBUG_ENTER_EXIT;
2157
2158   gdb_assert (this_frame != NULL);
2159
2160   if (frame_debug)
2161     {
2162       if (this_frame != NULL)
2163         frame_debug_printf ("this_frame=%d", this_frame->level);
2164       else
2165         frame_debug_printf ("this_frame=nullptr");
2166     }
2167
2168   struct gdbarch *gdbarch = get_frame_arch (this_frame);
2169
2170   /* Only try to do the unwind once.  */
2171   if (this_frame->prev_p)
2172     {
2173       if (this_frame->prev != nullptr)
2174         frame_debug_printf ("  -> %s // cached",
2175                             this_frame->prev->to_string ().c_str ());
2176       else
2177         frame_debug_printf
2178           ("  -> nullptr // %s // cached",
2179            frame_stop_reason_symbol_string (this_frame->stop_reason));
2180       return frame_info_ptr (this_frame->prev);
2181     }
2182
2183   /* If the frame unwinder hasn't been selected yet, we must do so
2184      before setting prev_p; otherwise the check for misbehaved
2185      sniffers will think that this frame's sniffer tried to unwind
2186      further (see frame_cleanup_after_sniffer).  */
2187   if (this_frame->unwind == NULL)
2188     frame_unwind_find_by_frame (this_frame, &this_frame->prologue_cache);
2189
2190   this_frame->prev_p = true;
2191   this_frame->stop_reason = UNWIND_NO_REASON;
2192
2193   /* If we are unwinding from an inline frame, all of the below tests
2194      were already performed when we unwound from the next non-inline
2195      frame.  We must skip them, since we can not get THIS_FRAME's ID
2196      until we have unwound all the way down to the previous non-inline
2197      frame.  */
2198   if (get_frame_type (this_frame) == INLINE_FRAME)
2199     return get_prev_frame_maybe_check_cycle (this_frame);
2200
2201   /* If this_frame is the current frame, then compute and stash its
2202      frame id prior to fetching and computing the frame id of the
2203      previous frame.  Otherwise, the cycle detection code in
2204      get_prev_frame_if_no_cycle() will not work correctly.  When
2205      get_frame_id() is called later on, an assertion error will be
2206      triggered in the event of a cycle between the current frame and
2207      its previous frame.
2208
2209      Note we do this after the INLINE_FRAME check above.  That is
2210      because the inline frame's frame id computation needs to fetch
2211      the frame id of its previous real stack frame.  I.e., we need to
2212      avoid recursion in that case.  This is OK since we're sure the
2213      inline frame won't create a cycle with the real stack frame.  See
2214      inline_frame_this_id.  */
2215   if (this_frame->level == 0)
2216     get_frame_id (this_frame);
2217
2218   /* Check that this frame is unwindable.  If it isn't, don't try to
2219      unwind to the prev frame.  */
2220   this_frame->stop_reason
2221     = this_frame->unwind->stop_reason (this_frame,
2222                                        &this_frame->prologue_cache);
2223
2224   if (this_frame->stop_reason != UNWIND_NO_REASON)
2225     {
2226       frame_debug_printf
2227         ("  -> nullptr // %s",
2228          frame_stop_reason_symbol_string (this_frame->stop_reason));
2229       return NULL;
2230     }
2231
2232   /* Check that this frame's ID isn't inner to (younger, below, next)
2233      the next frame.  This happens when a frame unwind goes backwards.
2234      This check is valid only if this frame and the next frame are NORMAL.
2235      See the comment at frame_id_inner for details.  */
2236   if (get_frame_type (this_frame) == NORMAL_FRAME
2237       && this_frame->next->unwind->type == NORMAL_FRAME
2238       && frame_id_inner (get_frame_arch (frame_info_ptr (this_frame->next)),
2239                          get_frame_id (this_frame),
2240                          get_frame_id (frame_info_ptr (this_frame->next))))
2241     {
2242       CORE_ADDR this_pc_in_block;
2243       struct minimal_symbol *morestack_msym;
2244       const char *morestack_name = NULL;
2245
2246       /* gcc -fsplit-stack __morestack can continue the stack anywhere.  */
2247       this_pc_in_block = get_frame_address_in_block (this_frame);
2248       morestack_msym = lookup_minimal_symbol_by_pc (this_pc_in_block).minsym;
2249       if (morestack_msym)
2250         morestack_name = morestack_msym->linkage_name ();
2251       if (!morestack_name || strcmp (morestack_name, "__morestack") != 0)
2252         {
2253           frame_debug_printf ("  -> nullptr // this frame ID is inner");
2254           this_frame->stop_reason = UNWIND_INNER_ID;
2255           return NULL;
2256         }
2257     }
2258
2259   /* Check that this and the next frame do not unwind the PC register
2260      to the same memory location.  If they do, then even though they
2261      have different frame IDs, the new frame will be bogus; two
2262      functions can't share a register save slot for the PC.  This can
2263      happen when the prologue analyzer finds a stack adjustment, but
2264      no PC save.
2265
2266      This check does assume that the "PC register" is roughly a
2267      traditional PC, even if the gdbarch_unwind_pc method adjusts
2268      it (we do not rely on the value, only on the unwound PC being
2269      dependent on this value).  A potential improvement would be
2270      to have the frame prev_pc method and the gdbarch unwind_pc
2271      method set the same lval and location information as
2272      frame_register_unwind.  */
2273   if (this_frame->level > 0
2274       && gdbarch_pc_regnum (gdbarch) >= 0
2275       && get_frame_type (this_frame) == NORMAL_FRAME
2276       && (get_frame_type (frame_info_ptr (this_frame->next)) == NORMAL_FRAME
2277           || get_frame_type (frame_info_ptr (this_frame->next)) == INLINE_FRAME))
2278     {
2279       int optimized, realnum, nrealnum;
2280       enum lval_type lval, nlval;
2281       CORE_ADDR addr, naddr;
2282
2283       frame_register_unwind_location (this_frame,
2284                                       gdbarch_pc_regnum (gdbarch),
2285                                       &optimized, &lval, &addr, &realnum);
2286       frame_register_unwind_location (get_next_frame (this_frame),
2287                                       gdbarch_pc_regnum (gdbarch),
2288                                       &optimized, &nlval, &naddr, &nrealnum);
2289
2290       if ((lval == lval_memory && lval == nlval && addr == naddr)
2291           || (lval == lval_register && lval == nlval && realnum == nrealnum))
2292         {
2293           frame_debug_printf ("  -> nullptr // no saved PC");
2294           this_frame->stop_reason = UNWIND_NO_SAVED_PC;
2295           this_frame->prev = NULL;
2296           return NULL;
2297         }
2298     }
2299
2300   return get_prev_frame_maybe_check_cycle (this_frame);
2301 }
2302
2303 /* Return a "struct frame_info" corresponding to the frame that called
2304    THIS_FRAME.  Returns NULL if there is no such frame.
2305
2306    Unlike get_prev_frame, this function always tries to unwind the
2307    frame.  */
2308
2309 frame_info_ptr 
2310 get_prev_frame_always (frame_info_ptr this_frame)
2311 {
2312   frame_info_ptr prev_frame = NULL;
2313
2314   try
2315     {
2316       prev_frame = get_prev_frame_always_1 (this_frame);
2317     }
2318   catch (const gdb_exception_error &ex)
2319     {
2320       if (ex.error == MEMORY_ERROR)
2321         {
2322           this_frame->stop_reason = UNWIND_MEMORY_ERROR;
2323           if (ex.message != NULL)
2324             {
2325               char *stop_string;
2326               size_t size;
2327
2328               /* The error needs to live as long as the frame does.
2329                  Allocate using stack local STOP_STRING then assign the
2330                  pointer to the frame, this allows the STOP_STRING on the
2331                  frame to be of type 'const char *'.  */
2332               size = ex.message->size () + 1;
2333               stop_string = (char *) frame_obstack_zalloc (size);
2334               memcpy (stop_string, ex.what (), size);
2335               this_frame->stop_string = stop_string;
2336             }
2337           prev_frame = NULL;
2338         }
2339       else
2340         throw;
2341     }
2342
2343   return prev_frame;
2344 }
2345
2346 /* Construct a new "struct frame_info" and link it previous to
2347    this_frame.  */
2348
2349 static frame_info_ptr 
2350 get_prev_frame_raw (frame_info_ptr this_frame)
2351 {
2352   frame_info *prev_frame;
2353
2354   /* Allocate the new frame but do not wire it in to the frame chain.
2355      Some (bad) code in INIT_FRAME_EXTRA_INFO tries to look along
2356      frame->next to pull some fancy tricks (of course such code is, by
2357      definition, recursive).  Try to prevent it.
2358
2359      There is no reason to worry about memory leaks, should the
2360      remainder of the function fail.  The allocated memory will be
2361      quickly reclaimed when the frame cache is flushed, and the `we've
2362      been here before' check above will stop repeated memory
2363      allocation calls.  */
2364   prev_frame = FRAME_OBSTACK_ZALLOC (struct frame_info);
2365   prev_frame->level = this_frame->level + 1;
2366
2367   /* For now, assume we don't have frame chains crossing address
2368      spaces.  */
2369   prev_frame->pspace = this_frame->pspace;
2370   prev_frame->aspace = this_frame->aspace;
2371
2372   /* Don't yet compute ->unwind (and hence ->type).  It is computed
2373      on-demand in get_frame_type, frame_register_unwind, and
2374      get_frame_id.  */
2375
2376   /* Don't yet compute the frame's ID.  It is computed on-demand by
2377      get_frame_id().  */
2378
2379   /* The unwound frame ID is validate at the start of this function,
2380      as part of the logic to decide if that frame should be further
2381      unwound, and not here while the prev frame is being created.
2382      Doing this makes it possible for the user to examine a frame that
2383      has an invalid frame ID.
2384
2385      Some very old VAX code noted: [...]  For the sake of argument,
2386      suppose that the stack is somewhat trashed (which is one reason
2387      that "info frame" exists).  So, return 0 (indicating we don't
2388      know the address of the arglist) if we don't know what frame this
2389      frame calls.  */
2390
2391   /* Link it in.  */
2392   this_frame->prev = prev_frame;
2393   prev_frame->next = this_frame.get ();
2394
2395   frame_debug_printf ("  -> %s", prev_frame->to_string ().c_str ());
2396
2397   return frame_info_ptr (prev_frame);
2398 }
2399
2400 /* Debug routine to print a NULL frame being returned.  */
2401
2402 static void
2403 frame_debug_got_null_frame (frame_info_ptr this_frame,
2404                             const char *reason)
2405 {
2406   if (frame_debug)
2407     {
2408       if (this_frame != NULL)
2409         frame_debug_printf ("this_frame=%d -> %s", this_frame->level, reason);
2410       else
2411         frame_debug_printf ("this_frame=nullptr -> %s", reason);
2412     }
2413 }
2414
2415 /* Is this (non-sentinel) frame in the "main"() function?  */
2416
2417 static bool
2418 inside_main_func (frame_info_ptr this_frame)
2419 {
2420   if (current_program_space->symfile_object_file == nullptr)
2421     return false;
2422
2423   CORE_ADDR sym_addr;
2424   const char *name = main_name ();
2425   bound_minimal_symbol msymbol
2426     = lookup_minimal_symbol (name, NULL,
2427                              current_program_space->symfile_object_file);
2428   if (msymbol.minsym == nullptr)
2429     {
2430       /* In some language (for example Fortran) there will be no minimal
2431          symbol with the name of the main function.  In this case we should
2432          search the full symbols to see if we can find a match.  */
2433       struct block_symbol bs = lookup_symbol (name, NULL, VAR_DOMAIN, 0);
2434       if (bs.symbol == nullptr)
2435         return false;
2436
2437       const struct block *block = bs.symbol->value_block ();
2438       gdb_assert (block != nullptr);
2439       sym_addr = block->start ();
2440     }
2441   else
2442     sym_addr = msymbol.value_address ();
2443
2444   /* Convert any function descriptor addresses into the actual function
2445      code address.  */
2446   sym_addr = gdbarch_convert_from_func_ptr_addr
2447     (get_frame_arch (this_frame), sym_addr, current_inferior ()->top_target ());
2448
2449   return sym_addr == get_frame_func (this_frame);
2450 }
2451
2452 /* Test whether THIS_FRAME is inside the process entry point function.  */
2453
2454 static bool
2455 inside_entry_func (frame_info_ptr this_frame)
2456 {
2457   CORE_ADDR entry_point;
2458
2459   if (!entry_point_address_query (&entry_point))
2460     return false;
2461
2462   return get_frame_func (this_frame) == entry_point;
2463 }
2464
2465 /* Return a structure containing various interesting information about
2466    the frame that called THIS_FRAME.  Returns NULL if there is entier
2467    no such frame or the frame fails any of a set of target-independent
2468    condition that should terminate the frame chain (e.g., as unwinding
2469    past main()).
2470
2471    This function should not contain target-dependent tests, such as
2472    checking whether the program-counter is zero.  */
2473
2474 frame_info_ptr 
2475 get_prev_frame (frame_info_ptr this_frame)
2476 {
2477   FRAME_SCOPED_DEBUG_ENTER_EXIT;
2478
2479   CORE_ADDR frame_pc;
2480   int frame_pc_p;
2481
2482   /* There is always a frame.  If this assertion fails, suspect that
2483      something should be calling get_selected_frame() or
2484      get_current_frame().  */
2485   gdb_assert (this_frame != NULL);
2486
2487   frame_pc_p = get_frame_pc_if_available (this_frame, &frame_pc);
2488
2489   /* tausq/2004-12-07: Dummy frames are skipped because it doesn't make much
2490      sense to stop unwinding at a dummy frame.  One place where a dummy
2491      frame may have an address "inside_main_func" is on HPUX.  On HPUX, the
2492      pcsqh register (space register for the instruction at the head of the
2493      instruction queue) cannot be written directly; the only way to set it
2494      is to branch to code that is in the target space.  In order to implement
2495      frame dummies on HPUX, the called function is made to jump back to where
2496      the inferior was when the user function was called.  If gdb was inside
2497      the main function when we created the dummy frame, the dummy frame will
2498      point inside the main function.  */
2499   if (this_frame->level >= 0
2500       && get_frame_type (this_frame) == NORMAL_FRAME
2501       && !user_set_backtrace_options.backtrace_past_main
2502       && frame_pc_p
2503       && inside_main_func (this_frame))
2504     /* Don't unwind past main().  Note, this is done _before_ the
2505        frame has been marked as previously unwound.  That way if the
2506        user later decides to enable unwinds past main(), that will
2507        automatically happen.  */
2508     {
2509       frame_debug_got_null_frame (this_frame, "inside main func");
2510       return NULL;
2511     }
2512
2513   /* If the user's backtrace limit has been exceeded, stop.  We must
2514      add two to the current level; one of those accounts for backtrace_limit
2515      being 1-based and the level being 0-based, and the other accounts for
2516      the level of the new frame instead of the level of the current
2517      frame.  */
2518   if (this_frame->level + 2 > user_set_backtrace_options.backtrace_limit)
2519     {
2520       frame_debug_got_null_frame (this_frame, "backtrace limit exceeded");
2521       return NULL;
2522     }
2523
2524   /* If we're already inside the entry function for the main objfile,
2525      then it isn't valid.  Don't apply this test to a dummy frame -
2526      dummy frame PCs typically land in the entry func.  Don't apply
2527      this test to the sentinel frame.  Sentinel frames should always
2528      be allowed to unwind.  */
2529   /* NOTE: cagney/2003-07-07: Fixed a bug in inside_main_func() -
2530      wasn't checking for "main" in the minimal symbols.  With that
2531      fixed asm-source tests now stop in "main" instead of halting the
2532      backtrace in weird and wonderful ways somewhere inside the entry
2533      file.  Suspect that tests for inside the entry file/func were
2534      added to work around that (now fixed) case.  */
2535   /* NOTE: cagney/2003-07-15: danielj (if I'm reading it right)
2536      suggested having the inside_entry_func test use the
2537      inside_main_func() msymbol trick (along with entry_point_address()
2538      I guess) to determine the address range of the start function.
2539      That should provide a far better stopper than the current
2540      heuristics.  */
2541   /* NOTE: tausq/2004-10-09: this is needed if, for example, the compiler
2542      applied tail-call optimizations to main so that a function called
2543      from main returns directly to the caller of main.  Since we don't
2544      stop at main, we should at least stop at the entry point of the
2545      application.  */
2546   if (this_frame->level >= 0
2547       && get_frame_type (this_frame) == NORMAL_FRAME
2548       && !user_set_backtrace_options.backtrace_past_entry
2549       && frame_pc_p
2550       && inside_entry_func (this_frame))
2551     {
2552       frame_debug_got_null_frame (this_frame, "inside entry func");
2553       return NULL;
2554     }
2555
2556   /* Assume that the only way to get a zero PC is through something
2557      like a SIGSEGV or a dummy frame, and hence that NORMAL frames
2558      will never unwind a zero PC.  */
2559   if (this_frame->level > 0
2560       && (get_frame_type (this_frame) == NORMAL_FRAME
2561           || get_frame_type (this_frame) == INLINE_FRAME)
2562       && get_frame_type (get_next_frame (this_frame)) == NORMAL_FRAME
2563       && frame_pc_p && frame_pc == 0)
2564     {
2565       frame_debug_got_null_frame (this_frame, "zero PC");
2566       return NULL;
2567     }
2568
2569   return get_prev_frame_always (this_frame);
2570 }
2571
2572 CORE_ADDR
2573 get_frame_pc (frame_info_ptr frame)
2574 {
2575   gdb_assert (frame->next != NULL);
2576   return frame_unwind_pc (frame_info_ptr (frame->next));
2577 }
2578
2579 bool
2580 get_frame_pc_if_available (frame_info_ptr frame, CORE_ADDR *pc)
2581 {
2582
2583   gdb_assert (frame->next != NULL);
2584
2585   try
2586     {
2587       *pc = frame_unwind_pc (frame_info_ptr (frame->next));
2588     }
2589   catch (const gdb_exception_error &ex)
2590     {
2591       if (ex.error == NOT_AVAILABLE_ERROR)
2592         return false;
2593       else
2594         throw;
2595     }
2596
2597   return true;
2598 }
2599
2600 /* Return an address that falls within THIS_FRAME's code block.  */
2601
2602 CORE_ADDR
2603 get_frame_address_in_block (frame_info_ptr this_frame)
2604 {
2605   /* A draft address.  */
2606   CORE_ADDR pc = get_frame_pc (this_frame);
2607
2608   frame_info_ptr next_frame (this_frame->next);
2609
2610   /* Calling get_frame_pc returns the resume address for THIS_FRAME.
2611      Normally the resume address is inside the body of the function
2612      associated with THIS_FRAME, but there is a special case: when
2613      calling a function which the compiler knows will never return
2614      (for instance abort), the call may be the very last instruction
2615      in the calling function.  The resume address will point after the
2616      call and may be at the beginning of a different function
2617      entirely.
2618
2619      If THIS_FRAME is a signal frame or dummy frame, then we should
2620      not adjust the unwound PC.  For a dummy frame, GDB pushed the
2621      resume address manually onto the stack.  For a signal frame, the
2622      OS may have pushed the resume address manually and invoked the
2623      handler (e.g. GNU/Linux), or invoked the trampoline which called
2624      the signal handler - but in either case the signal handler is
2625      expected to return to the trampoline.  So in both of these
2626      cases we know that the resume address is executable and
2627      related.  So we only need to adjust the PC if THIS_FRAME
2628      is a normal function.
2629
2630      If the program has been interrupted while THIS_FRAME is current,
2631      then clearly the resume address is inside the associated
2632      function.  There are three kinds of interruption: debugger stop
2633      (next frame will be SENTINEL_FRAME), operating system
2634      signal or exception (next frame will be SIGTRAMP_FRAME),
2635      or debugger-induced function call (next frame will be
2636      DUMMY_FRAME).  So we only need to adjust the PC if
2637      NEXT_FRAME is a normal function.
2638
2639      We check the type of NEXT_FRAME first, since it is already
2640      known; frame type is determined by the unwinder, and since
2641      we have THIS_FRAME we've already selected an unwinder for
2642      NEXT_FRAME.
2643
2644      If the next frame is inlined, we need to keep going until we find
2645      the real function - for instance, if a signal handler is invoked
2646      while in an inlined function, then the code address of the
2647      "calling" normal function should not be adjusted either.  */
2648
2649   while (get_frame_type (next_frame) == INLINE_FRAME)
2650     next_frame = frame_info_ptr (next_frame->next);
2651
2652   if ((get_frame_type (next_frame) == NORMAL_FRAME
2653        || get_frame_type (next_frame) == TAILCALL_FRAME)
2654       && (get_frame_type (this_frame) == NORMAL_FRAME
2655           || get_frame_type (this_frame) == TAILCALL_FRAME
2656           || get_frame_type (this_frame) == INLINE_FRAME))
2657     return pc - 1;
2658
2659   return pc;
2660 }
2661
2662 bool
2663 get_frame_address_in_block_if_available (frame_info_ptr this_frame,
2664                                          CORE_ADDR *pc)
2665 {
2666
2667   try
2668     {
2669       *pc = get_frame_address_in_block (this_frame);
2670     }
2671   catch (const gdb_exception_error &ex)
2672     {
2673       if (ex.error == NOT_AVAILABLE_ERROR)
2674         return false;
2675       throw;
2676     }
2677
2678   return true;
2679 }
2680
2681 symtab_and_line
2682 find_frame_sal (frame_info_ptr frame)
2683 {
2684   frame_info_ptr next_frame;
2685   int notcurrent;
2686   CORE_ADDR pc;
2687
2688   if (frame_inlined_callees (frame) > 0)
2689     {
2690       struct symbol *sym;
2691
2692       /* If the current frame has some inlined callees, and we have a next
2693          frame, then that frame must be an inlined frame.  In this case
2694          this frame's sal is the "call site" of the next frame's inlined
2695          function, which can not be inferred from get_frame_pc.  */
2696       next_frame = get_next_frame (frame);
2697       if (next_frame)
2698         sym = get_frame_function (next_frame);
2699       else
2700         sym = inline_skipped_symbol (inferior_thread ());
2701
2702       /* If frame is inline, it certainly has symbols.  */
2703       gdb_assert (sym);
2704
2705       symtab_and_line sal;
2706       if (sym->line () != 0)
2707         {
2708           sal.symtab = sym->symtab ();
2709           sal.line = sym->line ();
2710         }
2711       else
2712         /* If the symbol does not have a location, we don't know where
2713            the call site is.  Do not pretend to.  This is jarring, but
2714            we can't do much better.  */
2715         sal.pc = get_frame_pc (frame);
2716
2717       sal.pspace = get_frame_program_space (frame);
2718       return sal;
2719     }
2720
2721   /* If FRAME is not the innermost frame, that normally means that
2722      FRAME->pc points at the return instruction (which is *after* the
2723      call instruction), and we want to get the line containing the
2724      call (because the call is where the user thinks the program is).
2725      However, if the next frame is either a SIGTRAMP_FRAME or a
2726      DUMMY_FRAME, then the next frame will contain a saved interrupt
2727      PC and such a PC indicates the current (rather than next)
2728      instruction/line, consequently, for such cases, want to get the
2729      line containing fi->pc.  */
2730   if (!get_frame_pc_if_available (frame, &pc))
2731     return {};
2732
2733   notcurrent = (pc != get_frame_address_in_block (frame));
2734   return find_pc_line (pc, notcurrent);
2735 }
2736
2737 /* Per "frame.h", return the ``address'' of the frame.  Code should
2738    really be using get_frame_id().  */
2739 CORE_ADDR
2740 get_frame_base (frame_info_ptr fi)
2741 {
2742   return get_frame_id (fi).stack_addr;
2743 }
2744
2745 /* High-level offsets into the frame.  Used by the debug info.  */
2746
2747 CORE_ADDR
2748 get_frame_base_address (frame_info_ptr fi)
2749 {
2750   if (get_frame_type (fi) != NORMAL_FRAME)
2751     return 0;
2752   if (fi->base == NULL)
2753     fi->base = frame_base_find_by_frame (fi);
2754   /* Sneaky: If the low-level unwind and high-level base code share a
2755      common unwinder, let them share the prologue cache.  */
2756   if (fi->base->unwind == fi->unwind)
2757     return fi->base->this_base (fi, &fi->prologue_cache);
2758   return fi->base->this_base (fi, &fi->base_cache);
2759 }
2760
2761 CORE_ADDR
2762 get_frame_locals_address (frame_info_ptr fi)
2763 {
2764   if (get_frame_type (fi) != NORMAL_FRAME)
2765     return 0;
2766   /* If there isn't a frame address method, find it.  */
2767   if (fi->base == NULL)
2768     fi->base = frame_base_find_by_frame (fi);
2769   /* Sneaky: If the low-level unwind and high-level base code share a
2770      common unwinder, let them share the prologue cache.  */
2771   if (fi->base->unwind == fi->unwind)
2772     return fi->base->this_locals (fi, &fi->prologue_cache);
2773   return fi->base->this_locals (fi, &fi->base_cache);
2774 }
2775
2776 CORE_ADDR
2777 get_frame_args_address (frame_info_ptr fi)
2778 {
2779   if (get_frame_type (fi) != NORMAL_FRAME)
2780     return 0;
2781   /* If there isn't a frame address method, find it.  */
2782   if (fi->base == NULL)
2783     fi->base = frame_base_find_by_frame (fi);
2784   /* Sneaky: If the low-level unwind and high-level base code share a
2785      common unwinder, let them share the prologue cache.  */
2786   if (fi->base->unwind == fi->unwind)
2787     return fi->base->this_args (fi, &fi->prologue_cache);
2788   return fi->base->this_args (fi, &fi->base_cache);
2789 }
2790
2791 /* Return true if the frame unwinder for frame FI is UNWINDER; false
2792    otherwise.  */
2793
2794 bool
2795 frame_unwinder_is (frame_info_ptr fi, const frame_unwind *unwinder)
2796 {
2797   if (fi->unwind == nullptr)
2798     frame_unwind_find_by_frame (fi, &fi->prologue_cache);
2799
2800   return fi->unwind == unwinder;
2801 }
2802
2803 /* Level of the selected frame: 0 for innermost, 1 for its caller, ...
2804    or -1 for a NULL frame.  */
2805
2806 int
2807 frame_relative_level (frame_info_ptr fi)
2808 {
2809   if (fi == NULL)
2810     return -1;
2811   else
2812     return fi->level;
2813 }
2814
2815 enum frame_type
2816 get_frame_type (frame_info_ptr frame)
2817 {
2818   if (frame->unwind == NULL)
2819     /* Initialize the frame's unwinder because that's what
2820        provides the frame's type.  */
2821     frame_unwind_find_by_frame (frame, &frame->prologue_cache);
2822   return frame->unwind->type;
2823 }
2824
2825 struct program_space *
2826 get_frame_program_space (frame_info_ptr frame)
2827 {
2828   return frame->pspace;
2829 }
2830
2831 struct program_space *
2832 frame_unwind_program_space (frame_info_ptr this_frame)
2833 {
2834   gdb_assert (this_frame);
2835
2836   /* This is really a placeholder to keep the API consistent --- we
2837      assume for now that we don't have frame chains crossing
2838      spaces.  */
2839   return this_frame->pspace;
2840 }
2841
2842 const address_space *
2843 get_frame_address_space (frame_info_ptr frame)
2844 {
2845   return frame->aspace;
2846 }
2847
2848 /* Memory access methods.  */
2849
2850 void
2851 get_frame_memory (frame_info_ptr this_frame, CORE_ADDR addr,
2852                   gdb::array_view<gdb_byte> buffer)
2853 {
2854   read_memory (addr, buffer.data (), buffer.size ());
2855 }
2856
2857 LONGEST
2858 get_frame_memory_signed (frame_info_ptr this_frame, CORE_ADDR addr,
2859                          int len)
2860 {
2861   struct gdbarch *gdbarch = get_frame_arch (this_frame);
2862   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
2863
2864   return read_memory_integer (addr, len, byte_order);
2865 }
2866
2867 ULONGEST
2868 get_frame_memory_unsigned (frame_info_ptr this_frame, CORE_ADDR addr,
2869                            int len)
2870 {
2871   struct gdbarch *gdbarch = get_frame_arch (this_frame);
2872   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
2873
2874   return read_memory_unsigned_integer (addr, len, byte_order);
2875 }
2876
2877 bool
2878 safe_frame_unwind_memory (frame_info_ptr this_frame,
2879                           CORE_ADDR addr, gdb::array_view<gdb_byte> buffer)
2880 {
2881   /* NOTE: target_read_memory returns zero on success!  */
2882   return target_read_memory (addr, buffer.data (), buffer.size ()) == 0;
2883 }
2884
2885 /* Architecture methods.  */
2886
2887 struct gdbarch *
2888 get_frame_arch (frame_info_ptr this_frame)
2889 {
2890   return frame_unwind_arch (frame_info_ptr (this_frame->next));
2891 }
2892
2893 struct gdbarch *
2894 frame_unwind_arch (frame_info_ptr next_frame)
2895 {
2896   if (!next_frame->prev_arch.p)
2897     {
2898       struct gdbarch *arch;
2899
2900       if (next_frame->unwind == NULL)
2901         frame_unwind_find_by_frame (next_frame, &next_frame->prologue_cache);
2902
2903       if (next_frame->unwind->prev_arch != NULL)
2904         arch = next_frame->unwind->prev_arch (next_frame,
2905                                               &next_frame->prologue_cache);
2906       else
2907         arch = get_frame_arch (next_frame);
2908
2909       next_frame->prev_arch.arch = arch;
2910       next_frame->prev_arch.p = true;
2911       frame_debug_printf ("next_frame=%d -> %s",
2912                           next_frame->level,
2913                           gdbarch_bfd_arch_info (arch)->printable_name);
2914     }
2915
2916   return next_frame->prev_arch.arch;
2917 }
2918
2919 struct gdbarch *
2920 frame_unwind_caller_arch (frame_info_ptr next_frame)
2921 {
2922   next_frame = skip_artificial_frames (next_frame);
2923
2924   /* We must have a non-artificial frame.  The caller is supposed to check
2925      the result of frame_unwind_caller_id (), which returns NULL_FRAME_ID
2926      in this case.  */
2927   gdb_assert (next_frame != NULL);
2928
2929   return frame_unwind_arch (next_frame);
2930 }
2931
2932 /* Gets the language of FRAME.  */
2933
2934 enum language
2935 get_frame_language (frame_info_ptr frame)
2936 {
2937   CORE_ADDR pc = 0;
2938   bool pc_p = false;
2939
2940   gdb_assert (frame!= NULL);
2941
2942     /* We determine the current frame language by looking up its
2943        associated symtab.  To retrieve this symtab, we use the frame
2944        PC.  However we cannot use the frame PC as is, because it
2945        usually points to the instruction following the "call", which
2946        is sometimes the first instruction of another function.  So
2947        we rely on get_frame_address_in_block(), it provides us with
2948        a PC that is guaranteed to be inside the frame's code
2949        block.  */
2950
2951   try
2952     {
2953       pc = get_frame_address_in_block (frame);
2954       pc_p = true;
2955     }
2956   catch (const gdb_exception_error &ex)
2957     {
2958       if (ex.error != NOT_AVAILABLE_ERROR)
2959         throw;
2960     }
2961
2962   if (pc_p)
2963     {
2964       struct compunit_symtab *cust = find_pc_compunit_symtab (pc);
2965
2966       if (cust != NULL)
2967         return compunit_language (cust);
2968     }
2969
2970   return language_unknown;
2971 }
2972
2973 /* Stack pointer methods.  */
2974
2975 CORE_ADDR
2976 get_frame_sp (frame_info_ptr this_frame)
2977 {
2978   struct gdbarch *gdbarch = get_frame_arch (this_frame);
2979
2980   /* NOTE drow/2008-06-28: gdbarch_unwind_sp could be converted to
2981      operate on THIS_FRAME now.  */
2982   return gdbarch_unwind_sp (gdbarch, frame_info_ptr (this_frame->next));
2983 }
2984
2985 /* Return the reason why we can't unwind past FRAME.  */
2986
2987 enum unwind_stop_reason
2988 get_frame_unwind_stop_reason (frame_info_ptr frame)
2989 {
2990   /* Fill-in STOP_REASON.  */
2991   get_prev_frame_always (frame);
2992   gdb_assert (frame->prev_p);
2993
2994   return frame->stop_reason;
2995 }
2996
2997 /* Return a string explaining REASON.  */
2998
2999 const char *
3000 unwind_stop_reason_to_string (enum unwind_stop_reason reason)
3001 {
3002   switch (reason)
3003     {
3004 #define SET(name, description) \
3005     case name: return _(description);
3006 #include "unwind_stop_reasons.def"
3007 #undef SET
3008
3009     default:
3010       internal_error ("Invalid frame stop reason");
3011     }
3012 }
3013
3014 const char *
3015 frame_stop_reason_string (frame_info_ptr fi)
3016 {
3017   gdb_assert (fi->prev_p);
3018   gdb_assert (fi->prev == NULL);
3019
3020   /* Return the specific string if we have one.  */
3021   if (fi->stop_string != NULL)
3022     return fi->stop_string;
3023
3024   /* Return the generic string if we have nothing better.  */
3025   return unwind_stop_reason_to_string (fi->stop_reason);
3026 }
3027
3028 /* Return the enum symbol name of REASON as a string, to use in debug
3029    output.  */
3030
3031 static const char *
3032 frame_stop_reason_symbol_string (enum unwind_stop_reason reason)
3033 {
3034   switch (reason)
3035     {
3036 #define SET(name, description) \
3037     case name: return #name;
3038 #include "unwind_stop_reasons.def"
3039 #undef SET
3040
3041     default:
3042       internal_error ("Invalid frame stop reason");
3043     }
3044 }
3045
3046 /* Clean up after a failed (wrong unwinder) attempt to unwind past
3047    FRAME.  */
3048
3049 void
3050 frame_cleanup_after_sniffer (frame_info_ptr frame)
3051 {
3052   /* The sniffer should not allocate a prologue cache if it did not
3053      match this frame.  */
3054   gdb_assert (frame->prologue_cache == NULL);
3055
3056   /* No sniffer should extend the frame chain; sniff based on what is
3057      already certain.  */
3058   gdb_assert (!frame->prev_p);
3059
3060   /* The sniffer should not check the frame's ID; that's circular.  */
3061   gdb_assert (frame->this_id.p != frame_id_status::COMPUTED);
3062
3063   /* Clear cached fields dependent on the unwinder.
3064
3065      The previous PC is independent of the unwinder, but the previous
3066      function is not (see get_frame_address_in_block).  */
3067   frame->prev_func.status = CC_UNKNOWN;
3068   frame->prev_func.addr = 0;
3069
3070   /* Discard the unwinder last, so that we can easily find it if an assertion
3071      in this function triggers.  */
3072   frame->unwind = NULL;
3073 }
3074
3075 /* Set FRAME's unwinder temporarily, so that we can call a sniffer.
3076    If sniffing fails, the caller should be sure to call
3077    frame_cleanup_after_sniffer.  */
3078
3079 void
3080 frame_prepare_for_sniffer (frame_info_ptr frame,
3081                            const struct frame_unwind *unwind)
3082 {
3083   gdb_assert (frame->unwind == NULL);
3084   frame->unwind = unwind;
3085 }
3086
3087 static struct cmd_list_element *set_backtrace_cmdlist;
3088 static struct cmd_list_element *show_backtrace_cmdlist;
3089
3090 /* Definition of the "set backtrace" settings that are exposed as
3091    "backtrace" command options.  */
3092
3093 using boolean_option_def
3094   = gdb::option::boolean_option_def<set_backtrace_options>;
3095
3096 const gdb::option::option_def set_backtrace_option_defs[] = {
3097
3098   boolean_option_def {
3099     "past-main",
3100     [] (set_backtrace_options *opt) { return &opt->backtrace_past_main; },
3101     show_backtrace_past_main, /* show_cmd_cb */
3102     N_("Set whether backtraces should continue past \"main\"."),
3103     N_("Show whether backtraces should continue past \"main\"."),
3104     N_("Normally the caller of \"main\" is not of interest, so GDB will terminate\n\
3105 the backtrace at \"main\".  Set this if you need to see the rest\n\
3106 of the stack trace."),
3107   },
3108
3109   boolean_option_def {
3110     "past-entry",
3111     [] (set_backtrace_options *opt) { return &opt->backtrace_past_entry; },
3112     show_backtrace_past_entry, /* show_cmd_cb */
3113     N_("Set whether backtraces should continue past the entry point of a program."),
3114     N_("Show whether backtraces should continue past the entry point of a program."),
3115     N_("Normally there are no callers beyond the entry point of a program, so GDB\n\
3116 will terminate the backtrace there.  Set this if you need to see\n\
3117 the rest of the stack trace."),
3118   },
3119 };
3120
3121 /* Implement the 'maintenance print frame-id' command.  */
3122
3123 static void
3124 maintenance_print_frame_id (const char *args, int from_tty)
3125 {
3126   frame_info_ptr frame;
3127
3128   /* Use the currently selected frame, or select a frame based on the level
3129      number passed by the user.  */
3130   if (args == nullptr)
3131     frame = get_selected_frame ("No frame selected");
3132   else
3133     {
3134       int level = value_as_long (parse_and_eval (args));
3135       frame = find_relative_frame (get_current_frame (), &level);
3136     }
3137
3138   /* Print the frame-id.  */
3139   gdb_assert (frame != nullptr);
3140   gdb_printf ("frame-id for frame #%d: %s\n",
3141               frame_relative_level (frame),
3142               get_frame_id (frame).to_string ().c_str ());
3143 }
3144
3145 void _initialize_frame ();
3146 void
3147 _initialize_frame ()
3148 {
3149   obstack_init (&frame_cache_obstack);
3150
3151   frame_stash_create ();
3152
3153   gdb::observers::target_changed.attach (frame_observer_target_changed,
3154                                          "frame");
3155
3156   add_setshow_prefix_cmd ("backtrace", class_maintenance,
3157                           _("\
3158 Set backtrace specific variables.\n\
3159 Configure backtrace variables such as the backtrace limit"),
3160                           _("\
3161 Show backtrace specific variables.\n\
3162 Show backtrace variables such as the backtrace limit."),
3163                           &set_backtrace_cmdlist, &show_backtrace_cmdlist,
3164                           &setlist, &showlist);
3165
3166   add_setshow_uinteger_cmd ("limit", class_obscure,
3167                             &user_set_backtrace_options.backtrace_limit, _("\
3168 Set an upper bound on the number of backtrace levels."), _("\
3169 Show the upper bound on the number of backtrace levels."), _("\
3170 No more than the specified number of frames can be displayed or examined.\n\
3171 Literal \"unlimited\" or zero means no limit."),
3172                             NULL,
3173                             show_backtrace_limit,
3174                             &set_backtrace_cmdlist,
3175                             &show_backtrace_cmdlist);
3176
3177   gdb::option::add_setshow_cmds_for_options
3178     (class_stack, &user_set_backtrace_options,
3179      set_backtrace_option_defs, &set_backtrace_cmdlist, &show_backtrace_cmdlist);
3180
3181   /* Debug this files internals.  */
3182   add_setshow_boolean_cmd ("frame", class_maintenance, &frame_debug,  _("\
3183 Set frame debugging."), _("\
3184 Show frame debugging."), _("\
3185 When non-zero, frame specific internal debugging is enabled."),
3186                            NULL,
3187                            show_frame_debug,
3188                            &setdebuglist, &showdebuglist);
3189
3190   add_cmd ("frame-id", class_maintenance, maintenance_print_frame_id,
3191            _("Print the current frame-id."),
3192            &maintenanceprintlist);
3193 }
This page took 0.208422 seconds and 4 git commands to generate.