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