1 /* Print and select stack 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 "value.h"
22 #include "symtab.h"
23 #include "gdbtypes.h"
24 #include "expression.h"
25 #include "language.h"
26 #include "frame.h"
27 #include "gdbcmd.h"
28 #include "gdbcore.h"
29 #include "target.h"
30 #include "source.h"
31 #include "breakpoint.h"
32 #include "demangle.h"
33 #include "inferior.h"
34 #include "annotate.h"
35 #include "ui-out.h"
36 #include "block.h"
37 #include "stack.h"
38 #include "dictionary.h"
39 #include "reggroups.h"
40 #include "regcache.h"
41 #include "solib.h"
42 #include "valprint.h"
43 #include "gdbthread.h"
44 #include "cp-support.h"
45 #include "disasm.h"
46 #include "inline-frame.h"
47 #include "linespec.h"
48 #include "cli/cli-utils.h"
49 #include "objfiles.h"
50 #include "annotate.h"
51 
52 #include "symfile.h"
53 #include "extension.h"
54 #include "observable.h"
55 #include "gdbsupport/def-vector.h"
56 #include "cli/cli-option.h"
57 #include "cli/cli-style.h"
58 
59 /* The possible choices of "set print frame-arguments", and the value
60    of this setting.  */
61 
62 const char print_frame_arguments_all[] = "all";
63 const char print_frame_arguments_scalars[] = "scalars";
64 const char print_frame_arguments_none[] = "none";
65 const char print_frame_arguments_presence[] = "presence";
66 
67 static const char *const print_frame_arguments_choices[] =
68 {
69   print_frame_arguments_all,
70   print_frame_arguments_scalars,
71   print_frame_arguments_none,
72   print_frame_arguments_presence,
73   NULL
74 };
75 
76 /* The possible choices of "set print frame-info", and the value
77    of this setting.  */
78 
79 const char print_frame_info_auto[] = "auto";
80 const char print_frame_info_source_line[] = "source-line";
81 const char print_frame_info_location[] = "location";
82 const char print_frame_info_source_and_location[] = "source-and-location";
83 const char print_frame_info_location_and_address[] = "location-and-address";
84 const char print_frame_info_short_location[] = "short-location";
85 
86 static const char *const print_frame_info_choices[] =
87 {
88   print_frame_info_auto,
89   print_frame_info_source_line,
90   print_frame_info_location,
91   print_frame_info_source_and_location,
92   print_frame_info_location_and_address,
93   print_frame_info_short_location,
94   NULL
95 };
96 
97 /* print_frame_info_print_what[i] maps a choice to the corresponding
98    print_what enum.  */
99 static const gdb::optional<enum print_what> print_frame_info_print_what[] =
100   {{}, /* Empty value for "auto".  */
101    SRC_LINE, LOCATION, SRC_AND_LOC, LOC_AND_ADDRESS, SHORT_LOCATION};
102 
103 /* The possible choices of "set print entry-values", and the value
104    of this setting.  */
105 
106 const char print_entry_values_no[] = "no";
107 const char print_entry_values_only[] = "only";
108 const char print_entry_values_preferred[] = "preferred";
109 const char print_entry_values_if_needed[] = "if-needed";
110 const char print_entry_values_both[] = "both";
111 const char print_entry_values_compact[] = "compact";
112 const char print_entry_values_default[] = "default";
113 static const char *const print_entry_values_choices[] =
114 {
115   print_entry_values_no,
116   print_entry_values_only,
117   print_entry_values_preferred,
118   print_entry_values_if_needed,
119   print_entry_values_both,
120   print_entry_values_compact,
121   print_entry_values_default,
122   NULL
123 };
124 
125 /* See frame.h.  */
126 frame_print_options user_frame_print_options;
127 
128 /* Option definitions for some frame-related "set print ..."
129    settings.  */
130 
131 using boolean_option_def
132   = gdb::option::boolean_option_def<frame_print_options>;
133 using enum_option_def
134   = gdb::option::enum_option_def<frame_print_options>;
135 
136 static const gdb::option::option_def frame_print_option_defs[] = {
137 
138   enum_option_def {
139     "entry-values",
140     print_entry_values_choices,
141     [] (frame_print_options *opt) { return &opt->print_entry_values; },
142     NULL, /* show_cmd_cb */
143     N_("Set printing of function arguments at function entry."),
144     N_("Show printing of function arguments at function entry."),
145     N_("GDB can sometimes determine the values of function arguments at entry,\n\
146 in addition to their current values.  This option tells GDB whether\n\
147 to print the current value, the value at entry (marked as val@entry),\n\
148 or both.  Note that one or both of these values may be <optimized out>."),
149   },
150 
151   enum_option_def {
152     "frame-arguments",
153     print_frame_arguments_choices,
154     [] (frame_print_options *opt) { return &opt->print_frame_arguments; },
155     NULL, /* show_cmd_cb */
156     N_("Set printing of non-scalar frame arguments."),
157     N_("Show printing of non-scalar frame arguments."),
158     NULL /* help_doc */
159   },
160 
161   boolean_option_def {
162     "raw-frame-arguments",
163     [] (frame_print_options *opt) { return &opt->print_raw_frame_arguments; },
164     NULL, /* show_cmd_cb */
165     N_("Set whether to print frame arguments in raw form."),
166     N_("Show whether to print frame arguments in raw form."),
167     N_("If set, frame arguments are printed in raw form, bypassing any\n\
168 pretty-printers for that value.")
169   },
170 
171   enum_option_def {
172     "frame-info",
173     print_frame_info_choices,
174     [] (frame_print_options *opt) { return &opt->print_frame_info; },
175     NULL, /* show_cmd_cb */
176     N_("Set printing of frame information."),
177     N_("Show printing of frame information."),
178     NULL /* help_doc */
179   }
180 
181 };
182 
183 /* Options for the "backtrace" command.  */
184 
185 struct backtrace_cmd_options
186 {
187   bool full = false;
188   bool no_filters = false;
189   bool hide = false;
190 };
191 
192 using bt_flag_option_def
193   = gdb::option::flag_option_def<backtrace_cmd_options>;
194 
195 static const gdb::option::option_def backtrace_command_option_defs[] = {
196   bt_flag_option_def {
197     "full",
198     [] (backtrace_cmd_options *opt) { return &opt->full; },
199     N_("Print values of local variables.")
200   },
201 
202   bt_flag_option_def {
203     "no-filters",
204     [] (backtrace_cmd_options *opt) { return &opt->no_filters; },
205     N_("Prohibit frame filters from executing on a backtrace."),
206   },
207 
208   bt_flag_option_def {
209     "hide",
210     [] (backtrace_cmd_options *opt) { return &opt->hide; },
211     N_("Causes Python frame filter elided frames to not be printed."),
212   },
213 };
214 
215 /* Prototypes for local functions.  */
216 
217 static void print_frame_local_vars (struct frame_info *frame,
218 				    bool quiet,
219 				    const char *regexp, const char *t_regexp,
220 				    int num_tabs, struct ui_file *stream);
221 
222 static void print_frame (const frame_print_options &opts,
223 			 frame_info *frame, int print_level,
224 			 enum print_what print_what,  int print_args,
225 			 struct symtab_and_line sal);
226 
227 static struct frame_info *find_frame_for_function (const char *);
228 static struct frame_info *find_frame_for_address (CORE_ADDR);
229 
230 /* Zero means do things normally; we are interacting directly with the
231    user.  One means print the full filename and linenumber when a
232    frame is printed, and do so in a format emacs18/emacs19.22 can
233    parse.  Two means print similar annotations, but in many more
234    cases and in a slightly different syntax.  */
235 
236 int annotation_level = 0;
237 
238 /* Class used to manage tracking the last symtab we displayed.  */
239 
240 class last_displayed_symtab_info_type
241 {
242 public:
243   /* True if the cached information is valid.  */
is_valid()244   bool is_valid () const
245   { return m_valid; }
246 
247   /* Return the cached program_space.  If the cache is invalid nullptr is
248      returned.  */
pspace()249   struct program_space *pspace () const
250   { return m_pspace; }
251 
252   /* Return the cached CORE_ADDR address.  If the cache is invalid 0 is
253      returned.  */
address()254   CORE_ADDR address () const
255   { return m_address; }
256 
257   /* Return the cached symtab.  If the cache is invalid nullptr is
258      returned.  */
symtab()259   struct symtab *symtab () const
260   { return m_symtab; }
261 
262   /* Return the cached line number.  If the cache is invalid 0 is
263      returned.  */
line()264   int line () const
265   { return m_line; }
266 
267   /* Invalidate the cache, reset all the members to their default value.  */
invalidate()268   void invalidate ()
269   {
270     m_valid = false;
271     m_pspace = nullptr;
272     m_address = 0;
273     m_symtab = nullptr;
274     m_line = 0;
275   }
276 
277   /* Store a new set of values in the cache.  */
set(struct program_space * pspace,CORE_ADDR address,struct symtab * symtab,int line)278   void set (struct program_space *pspace, CORE_ADDR address,
279 	    struct symtab *symtab, int line)
280   {
281     gdb_assert (pspace != nullptr);
282 
283     m_valid = true;
284     m_pspace = pspace;
285     m_address = address;
286     m_symtab = symtab;
287     m_line = line;
288   }
289 
290 private:
291   /* True when the cache is valid.  */
292   bool m_valid = false;
293 
294   /* The last program space displayed.  */
295   struct program_space *m_pspace = nullptr;
296 
297   /* The last address displayed.  */
298   CORE_ADDR m_address = 0;
299 
300   /* The last symtab displayed.  */
301   struct symtab *m_symtab = nullptr;
302 
303   /* The last line number displayed.  */
304   int m_line = 0;
305 };
306 
307 /* An actual instance of the cache, holds information about the last symtab
308    displayed.  */
309 static last_displayed_symtab_info_type last_displayed_symtab_info;
310 
311 
312 
313 /* See stack.h.  */
314 
315 bool
frame_show_address(struct frame_info * frame,struct symtab_and_line sal)316 frame_show_address (struct frame_info *frame,
317 		    struct symtab_and_line sal)
318 {
319   /* If there is a line number, but no PC, then there is no location
320      information associated with this sal.  The only way that should
321      happen is for the call sites of inlined functions (SAL comes from
322      find_frame_sal).  Otherwise, we would have some PC range if the
323      SAL came from a line table.  */
324   if (sal.line != 0 && sal.pc == 0 && sal.end == 0)
325     {
326       if (get_next_frame (frame) == NULL)
327 	gdb_assert (inline_skipped_frames (inferior_thread ()) > 0);
328       else
329 	gdb_assert (get_frame_type (get_next_frame (frame)) == INLINE_FRAME);
330       return false;
331     }
332 
333   return get_frame_pc (frame) != sal.pc || !sal.is_stmt;
334 }
335 
336 /* See frame.h.  */
337 
338 void
print_stack_frame_to_uiout(struct ui_out * uiout,struct frame_info * frame,int print_level,enum print_what print_what,int set_current_sal)339 print_stack_frame_to_uiout (struct ui_out *uiout, struct frame_info *frame,
340 			    int print_level, enum print_what print_what,
341 			    int set_current_sal)
342 {
343   scoped_restore save_uiout = make_scoped_restore (&current_uiout, uiout);
344 
345   print_stack_frame (frame, print_level, print_what, set_current_sal);
346 }
347 
348 /* Show or print a stack frame FRAME briefly.  The output is formatted
349    according to PRINT_LEVEL and PRINT_WHAT printing the frame's
350    relative level, function name, argument list, and file name and
351    line number.  If the frame's PC is not at the beginning of the
352    source line, the actual PC is printed at the beginning.  */
353 
354 void
print_stack_frame(struct frame_info * frame,int print_level,enum print_what print_what,int set_current_sal)355 print_stack_frame (struct frame_info *frame, int print_level,
356 		   enum print_what print_what,
357 		   int set_current_sal)
358 {
359 
360   /* For mi, always print location and address.  */
361   if (current_uiout->is_mi_like_p ())
362     print_what = LOC_AND_ADDRESS;
363 
364   try
365     {
366       print_frame_info (user_frame_print_options,
367 			frame, print_level, print_what, 1 /* print_args */,
368 			set_current_sal);
369       if (set_current_sal)
370 	set_current_sal_from_frame (frame);
371     }
372   catch (const gdb_exception_error &e)
373     {
374     }
375 }
376 
377 /* Print nameless arguments of frame FRAME on STREAM, where START is
378    the offset of the first nameless argument, and NUM is the number of
379    nameless arguments to print.  FIRST is nonzero if this is the first
380    argument (not just the first nameless argument).  */
381 
382 static void
print_frame_nameless_args(struct frame_info * frame,long start,int num,int first,struct ui_file * stream)383 print_frame_nameless_args (struct frame_info *frame, long start, int num,
384 			   int first, struct ui_file *stream)
385 {
386   struct gdbarch *gdbarch = get_frame_arch (frame);
387   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
388   int i;
389   CORE_ADDR argsaddr;
390   long arg_value;
391 
392   for (i = 0; i < num; i++)
393     {
394       QUIT;
395       argsaddr = get_frame_args_address (frame);
396       if (!argsaddr)
397 	return;
398       arg_value = read_memory_integer (argsaddr + start,
399 				       sizeof (int), byte_order);
400       if (!first)
401 	fprintf_filtered (stream, ", ");
402       fprintf_filtered (stream, "%ld", arg_value);
403       first = 0;
404       start += sizeof (int);
405     }
406 }
407 
408 /* Print single argument of inferior function.  ARG must be already
409    read in.
410 
411    Errors are printed as if they would be the parameter value.  Use zeroed ARG
412    iff it should not be printed according to user settings.  */
413 
414 static void
print_frame_arg(const frame_print_options & fp_opts,const struct frame_arg * arg)415 print_frame_arg (const frame_print_options &fp_opts,
416 		 const struct frame_arg *arg)
417 {
418   struct ui_out *uiout = current_uiout;
419 
420   string_file stb;
421 
422   gdb_assert (!arg->val || !arg->error);
423   gdb_assert (arg->entry_kind == print_entry_values_no
424 	      || arg->entry_kind == print_entry_values_only
425 	      || (!uiout->is_mi_like_p ()
426 		  && arg->entry_kind == print_entry_values_compact));
427 
428   annotate_arg_emitter arg_emitter;
429   ui_out_emit_tuple tuple_emitter (uiout, NULL);
430   fprintf_symbol_filtered (&stb, arg->sym->print_name (),
431 			   arg->sym->language (), DMGL_PARAMS | DMGL_ANSI);
432   if (arg->entry_kind == print_entry_values_compact)
433     {
434       /* It is OK to provide invalid MI-like stream as with
435 	 PRINT_ENTRY_VALUE_COMPACT we never use MI.  */
436       stb.puts ("=");
437 
438       fprintf_symbol_filtered (&stb, arg->sym->print_name (),
439 			       arg->sym->language (),
440 			       DMGL_PARAMS | DMGL_ANSI);
441     }
442   if (arg->entry_kind == print_entry_values_only
443       || arg->entry_kind == print_entry_values_compact)
444     stb.puts ("@entry");
445   uiout->field_stream ("name", stb, variable_name_style.style ());
446   annotate_arg_name_end ();
447   uiout->text ("=");
448 
449   ui_file_style style;
450   if (!arg->val && !arg->error)
451     uiout->text ("...");
452   else
453     {
454       if (arg->error)
455 	{
456 	  stb.printf (_("<error reading variable: %s>"), arg->error.get ());
457 	  style = metadata_style.style ();
458 	}
459       else
460 	{
461 	  try
462 	    {
463 	      const struct language_defn *language;
464 	      struct value_print_options vp_opts;
465 
466 	      /* Avoid value_print because it will deref ref parameters.  We
467 		 just want to print their addresses.  Print ??? for args whose
468 		 address we do not know.  We pass 2 as "recurse" to val_print
469 		 because our standard indentation here is 4 spaces, and
470 		 val_print indents 2 for each recurse.  */
471 
472 	      annotate_arg_value (value_type (arg->val));
473 
474 	      /* Use the appropriate language to display our symbol, unless the
475 		 user forced the language to a specific language.  */
476 	      if (language_mode == language_mode_auto)
477 		language = language_def (arg->sym->language ());
478 	      else
479 		language = current_language;
480 
481 	      get_no_prettyformat_print_options (&vp_opts);
482 	      vp_opts.deref_ref = 1;
483 	      vp_opts.raw = fp_opts.print_raw_frame_arguments;
484 
485 	      /* True in "summary" mode, false otherwise.  */
486 	      vp_opts.summary
487 		= fp_opts.print_frame_arguments == print_frame_arguments_scalars;
488 
489 	      common_val_print_checked (arg->val, &stb, 2, &vp_opts, language);
490 	    }
491 	  catch (const gdb_exception_error &except)
492 	    {
493 	      stb.printf (_("<error reading variable: %s>"),
494 			  except.what ());
495 	      style = metadata_style.style ();
496 	    }
497 	}
498     }
499 
500   uiout->field_stream ("value", stb, style);
501 }
502 
503 /* Read in inferior function local SYM at FRAME into ARGP.  Caller is
504    responsible for xfree of ARGP->ERROR.  This function never throws an
505    exception.  */
506 
507 void
read_frame_local(struct symbol * sym,struct frame_info * frame,struct frame_arg * argp)508 read_frame_local (struct symbol *sym, struct frame_info *frame,
509 		  struct frame_arg *argp)
510 {
511   argp->sym = sym;
512   argp->val = NULL;
513   argp->error = NULL;
514 
515   try
516     {
517       argp->val = read_var_value (sym, NULL, frame);
518     }
519   catch (const gdb_exception_error &except)
520     {
521       argp->error.reset (xstrdup (except.what ()));
522     }
523 }
524 
525 /* Read in inferior function parameter SYM at FRAME into ARGP.  This
526    function never throws an exception.  */
527 
528 void
read_frame_arg(const frame_print_options & fp_opts,symbol * sym,frame_info * frame,struct frame_arg * argp,struct frame_arg * entryargp)529 read_frame_arg (const frame_print_options &fp_opts,
530 		symbol *sym, frame_info *frame,
531 		struct frame_arg *argp, struct frame_arg *entryargp)
532 {
533   struct value *val = NULL, *entryval = NULL;
534   char *val_error = NULL, *entryval_error = NULL;
535   int val_equal = 0;
536 
537   if (fp_opts.print_entry_values != print_entry_values_only
538       && fp_opts.print_entry_values != print_entry_values_preferred)
539     {
540       try
541 	{
542 	  val = read_var_value (sym, NULL, frame);
543 	}
544       catch (const gdb_exception_error &except)
545 	{
546 	  val_error = (char *) alloca (except.message->size () + 1);
547 	  strcpy (val_error, except.what ());
548 	}
549     }
550 
551   if (SYMBOL_COMPUTED_OPS (sym) != NULL
552       && SYMBOL_COMPUTED_OPS (sym)->read_variable_at_entry != NULL
553       && fp_opts.print_entry_values != print_entry_values_no
554       && (fp_opts.print_entry_values != print_entry_values_if_needed
555 	  || !val || value_optimized_out (val)))
556     {
557       try
558 	{
559 	  const struct symbol_computed_ops *ops;
560 
561 	  ops = SYMBOL_COMPUTED_OPS (sym);
562 	  entryval = ops->read_variable_at_entry (sym, frame);
563 	}
564       catch (const gdb_exception_error &except)
565 	{
566 	  if (except.error != NO_ENTRY_VALUE_ERROR)
567 	    {
568 	      entryval_error = (char *) alloca (except.message->size () + 1);
569 	      strcpy (entryval_error, except.what ());
570 	    }
571 	}
572 
573       if (entryval != NULL && value_optimized_out (entryval))
574 	entryval = NULL;
575 
576       if (fp_opts.print_entry_values == print_entry_values_compact
577 	  || fp_opts.print_entry_values == print_entry_values_default)
578 	{
579 	  /* For MI do not try to use print_entry_values_compact for ARGP.  */
580 
581 	  if (val && entryval && !current_uiout->is_mi_like_p ())
582 	    {
583 	      struct type *type = value_type (val);
584 
585 	      if (value_lazy (val))
586 		value_fetch_lazy (val);
587 	      if (value_lazy (entryval))
588 		value_fetch_lazy (entryval);
589 
590 	      if (value_contents_eq (val, 0, entryval, 0, TYPE_LENGTH (type)))
591 		{
592 		  /* Initialize it just to avoid a GCC false warning.  */
593 		  struct value *val_deref = NULL, *entryval_deref;
594 
595 		  /* DW_AT_call_value does match with the current
596 		     value.  If it is a reference still try to verify if
597 		     dereferenced DW_AT_call_data_value does not differ.  */
598 
599 		  try
600 		    {
601 		      struct type *type_deref;
602 
603 		      val_deref = coerce_ref (val);
604 		      if (value_lazy (val_deref))
605 			value_fetch_lazy (val_deref);
606 		      type_deref = value_type (val_deref);
607 
608 		      entryval_deref = coerce_ref (entryval);
609 		      if (value_lazy (entryval_deref))
610 			value_fetch_lazy (entryval_deref);
611 
612 		      /* If the reference addresses match but dereferenced
613 			 content does not match print them.  */
614 		      if (val != val_deref
615 			  && value_contents_eq (val_deref, 0,
616 						entryval_deref, 0,
617 						TYPE_LENGTH (type_deref)))
618 			val_equal = 1;
619 		    }
620 		  catch (const gdb_exception_error &except)
621 		    {
622 		      /* If the dereferenced content could not be
623 			 fetched do not display anything.  */
624 		      if (except.error == NO_ENTRY_VALUE_ERROR)
625 			val_equal = 1;
626 		      else if (except.message != NULL)
627 			{
628 			  entryval_error
629 			    = (char *) alloca (except.message->size () + 1);
630 			  strcpy (entryval_error, except.what ());
631 			}
632 		    }
633 
634 		  /* Value was not a reference; and its content matches.  */
635 		  if (val == val_deref)
636 		    val_equal = 1;
637 
638 		  if (val_equal)
639 		    entryval = NULL;
640 		}
641 	    }
642 
643 	  /* Try to remove possibly duplicate error message for ENTRYARGP even
644 	     in MI mode.  */
645 
646 	  if (val_error && entryval_error
647 	      && strcmp (val_error, entryval_error) == 0)
648 	    {
649 	      entryval_error = NULL;
650 
651 	      /* Do not se VAL_EQUAL as the same error message may be shown for
652 		 the entry value even if no entry values are present in the
653 		 inferior.  */
654 	    }
655 	}
656     }
657 
658   if (entryval == NULL)
659     {
660       if (fp_opts.print_entry_values == print_entry_values_preferred)
661 	{
662 	  gdb_assert (val == NULL);
663 
664 	  try
665 	    {
666 	      val = read_var_value (sym, NULL, frame);
667 	    }
668 	  catch (const gdb_exception_error &except)
669 	    {
670 	      val_error = (char *) alloca (except.message->size () + 1);
671 	      strcpy (val_error, except.what ());
672 	    }
673 	}
674       if (fp_opts.print_entry_values == print_entry_values_only
675 	  || fp_opts.print_entry_values == print_entry_values_both
676 	  || (fp_opts.print_entry_values == print_entry_values_preferred
677 	      && (!val || value_optimized_out (val))))
678 	{
679 	  entryval = allocate_optimized_out_value (SYMBOL_TYPE (sym));
680 	  entryval_error = NULL;
681 	}
682     }
683   if ((fp_opts.print_entry_values == print_entry_values_compact
684        || fp_opts.print_entry_values == print_entry_values_if_needed
685        || fp_opts.print_entry_values == print_entry_values_preferred)
686       && (!val || value_optimized_out (val)) && entryval != NULL)
687     {
688       val = NULL;
689       val_error = NULL;
690     }
691 
692   argp->sym = sym;
693   argp->val = val;
694   argp->error.reset (val_error ? xstrdup (val_error) : NULL);
695   if (!val && !val_error)
696     argp->entry_kind = print_entry_values_only;
697   else if ((fp_opts.print_entry_values == print_entry_values_compact
698 	   || fp_opts.print_entry_values == print_entry_values_default)
699 	   && val_equal)
700     {
701       argp->entry_kind = print_entry_values_compact;
702       gdb_assert (!current_uiout->is_mi_like_p ());
703     }
704   else
705     argp->entry_kind = print_entry_values_no;
706 
707   entryargp->sym = sym;
708   entryargp->val = entryval;
709   entryargp->error.reset (entryval_error ? xstrdup (entryval_error) : NULL);
710   if (!entryval && !entryval_error)
711     entryargp->entry_kind = print_entry_values_no;
712   else
713     entryargp->entry_kind = print_entry_values_only;
714 }
715 
716 /* Print the arguments of frame FRAME on STREAM, given the function
717    FUNC running in that frame (as a symbol), where NUM is the number
718    of arguments according to the stack frame (or -1 if the number of
719    arguments is unknown).  */
720 
721 /* Note that currently the "number of arguments according to the
722    stack frame" is only known on VAX where i refers to the "number of
723    ints of arguments according to the stack frame".  */
724 
725 static void
print_frame_args(const frame_print_options & fp_opts,struct symbol * func,struct frame_info * frame,int num,struct ui_file * stream)726 print_frame_args (const frame_print_options &fp_opts,
727 		  struct symbol *func, struct frame_info *frame,
728 		  int num, struct ui_file *stream)
729 {
730   struct ui_out *uiout = current_uiout;
731   int first = 1;
732   /* Offset of next stack argument beyond the one we have seen that is
733      at the highest offset, or -1 if we haven't come to a stack
734      argument yet.  */
735   long highest_offset = -1;
736   /* Number of ints of arguments that we have printed so far.  */
737   int args_printed = 0;
738   /* True if we should print arg names.  If false, we only indicate
739      the presence of arguments by printing ellipsis.  */
740   bool print_names
741     = fp_opts.print_frame_arguments != print_frame_arguments_presence;
742   /* True if we should print arguments, false otherwise.  */
743   bool print_args
744     = (print_names
745        && fp_opts.print_frame_arguments != print_frame_arguments_none);
746 
747   /* Temporarily change the selected frame to the given FRAME.
748      This allows routines that rely on the selected frame instead
749      of being given a frame as parameter to use the correct frame.  */
750   scoped_restore_selected_frame restore_selected_frame;
751   select_frame (frame);
752 
753   if (func)
754     {
755       const struct block *b = SYMBOL_BLOCK_VALUE (func);
756       struct block_iterator iter;
757       struct symbol *sym;
758 
759       ALL_BLOCK_SYMBOLS (b, iter, sym)
760 	{
761 	  struct frame_arg arg, entryarg;
762 
763 	  QUIT;
764 
765 	  /* Keep track of the highest stack argument offset seen, and
766 	     skip over any kinds of symbols we don't care about.  */
767 
768 	  if (!SYMBOL_IS_ARGUMENT (sym))
769 	    continue;
770 
771 	  if (!print_names)
772 	    {
773 	      uiout->text ("...");
774 	      first = 0;
775 	      break;
776 	    }
777 
778 	  switch (SYMBOL_CLASS (sym))
779 	    {
780 	    case LOC_ARG:
781 	    case LOC_REF_ARG:
782 	      {
783 		long current_offset = SYMBOL_VALUE (sym);
784 		int arg_size = TYPE_LENGTH (SYMBOL_TYPE (sym));
785 
786 		/* Compute address of next argument by adding the size of
787 		   this argument and rounding to an int boundary.  */
788 		current_offset =
789 		  ((current_offset + arg_size + sizeof (int) - 1)
790 		   & ~(sizeof (int) - 1));
791 
792 		/* If this is the highest offset seen yet, set
793 		   highest_offset.  */
794 		if (highest_offset == -1
795 		    || (current_offset > highest_offset))
796 		  highest_offset = current_offset;
797 
798 		/* Add the number of ints we're about to print to
799 		   args_printed.  */
800 		args_printed += (arg_size + sizeof (int) - 1) / sizeof (int);
801 	      }
802 
803 	      /* We care about types of symbols, but don't need to
804 		 keep track of stack offsets in them.  */
805 	    case LOC_REGISTER:
806 	    case LOC_REGPARM_ADDR:
807 	    case LOC_COMPUTED:
808 	    case LOC_OPTIMIZED_OUT:
809 	    default:
810 	      break;
811 	    }
812 
813 	  /* We have to look up the symbol because arguments can have
814 	     two entries (one a parameter, one a local) and the one we
815 	     want is the local, which lookup_symbol will find for us.
816 	     This includes gcc1 (not gcc2) on SPARC when passing a
817 	     small structure and gcc2 when the argument type is float
818 	     and it is passed as a double and converted to float by
819 	     the prologue (in the latter case the type of the LOC_ARG
820 	     symbol is double and the type of the LOC_LOCAL symbol is
821 	     float).  */
822 	  /* But if the parameter name is null, don't try it.  Null
823 	     parameter names occur on the RS/6000, for traceback
824 	     tables.  FIXME, should we even print them?  */
825 
826 	  if (*sym->linkage_name ())
827 	    {
828 	      struct symbol *nsym;
829 
830 	      nsym = lookup_symbol_search_name (sym->search_name (),
831 						b, VAR_DOMAIN).symbol;
832 	      gdb_assert (nsym != NULL);
833 	      if (SYMBOL_CLASS (nsym) == LOC_REGISTER
834 		  && !SYMBOL_IS_ARGUMENT (nsym))
835 		{
836 		  /* There is a LOC_ARG/LOC_REGISTER pair.  This means
837 		     that it was passed on the stack and loaded into a
838 		     register, or passed in a register and stored in a
839 		     stack slot.  GDB 3.x used the LOC_ARG; GDB
840 		     4.0-4.11 used the LOC_REGISTER.
841 
842 		     Reasons for using the LOC_ARG:
843 
844 		     (1) Because find_saved_registers may be slow for
845 			 remote debugging.
846 
847 		     (2) Because registers are often re-used and stack
848 			 slots rarely (never?) are.  Therefore using
849 			 the stack slot is much less likely to print
850 			 garbage.
851 
852 		     Reasons why we might want to use the LOC_REGISTER:
853 
854 		     (1) So that the backtrace prints the same value
855 			 as "print foo".  I see no compelling reason
856 			 why this needs to be the case; having the
857 			 backtrace print the value which was passed
858 			 in, and "print foo" print the value as
859 			 modified within the called function, makes
860 			 perfect sense to me.
861 
862 		     Additional note: It might be nice if "info args"
863 		     displayed both values.
864 
865 		     One more note: There is a case with SPARC
866 		     structure passing where we need to use the
867 		     LOC_REGISTER, but this is dealt with by creating
868 		     a single LOC_REGPARM in symbol reading.  */
869 
870 		  /* Leave sym (the LOC_ARG) alone.  */
871 		  ;
872 		}
873 	      else
874 		sym = nsym;
875 	    }
876 
877 	  /* Print the current arg.  */
878 	  if (!first)
879 	    uiout->text (", ");
880 	  uiout->wrap_hint ("    ");
881 
882 	  if (!print_args)
883 	    {
884 	      arg.sym = sym;
885 	      arg.entry_kind = print_entry_values_no;
886 	      entryarg.sym = sym;
887 	      entryarg.entry_kind = print_entry_values_no;
888 	    }
889 	  else
890 	    read_frame_arg (fp_opts, sym, frame, &arg, &entryarg);
891 
892 	  if (arg.entry_kind != print_entry_values_only)
893 	    print_frame_arg (fp_opts, &arg);
894 
895 	  if (entryarg.entry_kind != print_entry_values_no)
896 	    {
897 	      if (arg.entry_kind != print_entry_values_only)
898 		{
899 		  uiout->text (", ");
900 		  uiout->wrap_hint ("    ");
901 		}
902 
903 	      print_frame_arg (fp_opts, &entryarg);
904 	    }
905 
906 	  first = 0;
907 	}
908     }
909 
910   /* Don't print nameless args in situations where we don't know
911      enough about the stack to find them.  */
912   if (num != -1)
913     {
914       long start;
915 
916       if (highest_offset == -1)
917 	start = gdbarch_frame_args_skip (get_frame_arch (frame));
918       else
919 	start = highest_offset;
920 
921       if (!print_names && !first && num > 0)
922 	uiout->text ("...");
923       else
924 	print_frame_nameless_args (frame, start, num - args_printed,
925 				   first, stream);
926     }
927 }
928 
929 /* Set the current source and line to the location given by frame
930    FRAME, if possible.  When CENTER is true, adjust so the relevant
931    line is in the center of the next 'list'.  */
932 
933 void
set_current_sal_from_frame(struct frame_info * frame)934 set_current_sal_from_frame (struct frame_info *frame)
935 {
936   symtab_and_line sal = find_frame_sal (frame);
937   if (sal.symtab != NULL)
938     set_current_source_symtab_and_line (sal);
939 }
940 
941 /* If ON, GDB will display disassembly of the next source line when
942    execution of the program being debugged stops.
943    If AUTO (which is the default), or there's no line info to determine
944    the source line of the next instruction, display disassembly of next
945    instruction instead.  */
946 
947 static enum auto_boolean disassemble_next_line;
948 
949 static void
show_disassemble_next_line(struct ui_file * file,int from_tty,struct cmd_list_element * c,const char * value)950 show_disassemble_next_line (struct ui_file *file, int from_tty,
951 				 struct cmd_list_element *c,
952 				 const char *value)
953 {
954   fprintf_filtered (file,
955 		    _("Debugger's willingness to use "
956 		      "disassemble-next-line is %s.\n"),
957 		    value);
958 }
959 
960 /* Use TRY_CATCH to catch the exception from the gdb_disassembly
961    because it will be broken by filter sometime.  */
962 
963 static void
do_gdb_disassembly(struct gdbarch * gdbarch,int how_many,CORE_ADDR low,CORE_ADDR high)964 do_gdb_disassembly (struct gdbarch *gdbarch,
965 		    int how_many, CORE_ADDR low, CORE_ADDR high)
966 {
967 
968   try
969     {
970       gdb_disassembly (gdbarch, current_uiout,
971 		       DISASSEMBLY_RAW_INSN, how_many,
972 		       low, high);
973     }
974   catch (const gdb_exception_error &exception)
975     {
976       /* If an exception was thrown while doing the disassembly, print
977 	 the error message, to give the user a clue of what happened.  */
978       exception_print (gdb_stderr, exception);
979     }
980 }
981 
982 /* Converts the PRINT_FRAME_INFO choice to an optional enum print_what.
983    Value not present indicates to the caller to use default values
984    specific to the command being executed.  */
985 
986 static gdb::optional<enum print_what>
print_frame_info_to_print_what(const char * print_frame_info)987 print_frame_info_to_print_what (const char *print_frame_info)
988 {
989   for (int i = 0; print_frame_info_choices[i] != NULL; i++)
990     if (print_frame_info == print_frame_info_choices[i])
991       return print_frame_info_print_what[i];
992 
993   internal_error (__FILE__, __LINE__,
994 		  "Unexpected print frame-info value `%s'.",
995 		  print_frame_info);
996 }
997 
998 /* Print the PC from FRAME, plus any flags, to UIOUT.  */
999 
1000 static void
print_pc(struct ui_out * uiout,struct gdbarch * gdbarch,frame_info * frame,CORE_ADDR pc)1001 print_pc (struct ui_out *uiout, struct gdbarch *gdbarch, frame_info *frame,
1002 	  CORE_ADDR pc)
1003 {
1004   uiout->field_core_addr ("addr", gdbarch, pc);
1005 
1006   std::string flags = gdbarch_get_pc_address_flags (gdbarch, frame, pc);
1007   if (!flags.empty ())
1008     {
1009       uiout->text (" [");
1010       uiout->field_string ("addr_flags", flags);
1011       uiout->text ("]");
1012     }
1013 }
1014 
1015 /* See stack.h.  */
1016 
1017 void
get_user_print_what_frame_info(gdb::optional<enum print_what> * what)1018 get_user_print_what_frame_info (gdb::optional<enum print_what> *what)
1019 {
1020   *what
1021     = print_frame_info_to_print_what
1022 	(user_frame_print_options.print_frame_info);
1023 }
1024 
1025 /* Print information about frame FRAME.  The output is format according
1026    to PRINT_LEVEL and PRINT_WHAT and PRINT_ARGS.  For the meaning of
1027    PRINT_WHAT, see enum print_what comments in frame.h.
1028    Note that PRINT_WHAT is overridden if FP_OPTS.print_frame_info
1029    != print_frame_info_auto.
1030 
1031    Used in "where" output, and to emit breakpoint or step
1032    messages.  */
1033 
1034 void
print_frame_info(const frame_print_options & fp_opts,frame_info * frame,int print_level,enum print_what print_what,int print_args,int set_current_sal)1035 print_frame_info (const frame_print_options &fp_opts,
1036 		  frame_info *frame, int print_level,
1037 		  enum print_what print_what, int print_args,
1038 		  int set_current_sal)
1039 {
1040   struct gdbarch *gdbarch = get_frame_arch (frame);
1041   int source_print;
1042   int location_print;
1043   struct ui_out *uiout = current_uiout;
1044 
1045   if (!current_uiout->is_mi_like_p ()
1046       && fp_opts.print_frame_info != print_frame_info_auto)
1047     {
1048       /* Use the specific frame information desired by the user.  */
1049       print_what = *print_frame_info_to_print_what (fp_opts.print_frame_info);
1050     }
1051 
1052   if (get_frame_type (frame) == DUMMY_FRAME
1053       || get_frame_type (frame) == SIGTRAMP_FRAME
1054       || get_frame_type (frame) == ARCH_FRAME)
1055     {
1056       ui_out_emit_tuple tuple_emitter (uiout, "frame");
1057 
1058       annotate_frame_begin (print_level ? frame_relative_level (frame) : 0,
1059 			    gdbarch, get_frame_pc (frame));
1060 
1061       /* Do this regardless of SOURCE because we don't have any source
1062 	 to list for this frame.  */
1063       if (print_level)
1064 	{
1065 	  uiout->text ("#");
1066 	  uiout->field_fmt_signed (2, ui_left, "level",
1067 				   frame_relative_level (frame));
1068 	}
1069       if (uiout->is_mi_like_p ())
1070 	{
1071 	  annotate_frame_address ();
1072 	  print_pc (uiout, gdbarch, frame, get_frame_pc (frame));
1073 	  annotate_frame_address_end ();
1074 	}
1075 
1076       if (get_frame_type (frame) == DUMMY_FRAME)
1077 	{
1078 	  annotate_function_call ();
1079 	  uiout->field_string ("func", "<function called from gdb>",
1080 			       metadata_style.style ());
1081 	}
1082       else if (get_frame_type (frame) == SIGTRAMP_FRAME)
1083 	{
1084 	  annotate_signal_handler_caller ();
1085 	  uiout->field_string ("func", "<signal handler called>",
1086 			       metadata_style.style ());
1087 	}
1088       else if (get_frame_type (frame) == ARCH_FRAME)
1089 	{
1090 	  uiout->field_string ("func", "<cross-architecture call>",
1091 			       metadata_style.style ());
1092 	}
1093       uiout->text ("\n");
1094       annotate_frame_end ();
1095 
1096       /* If disassemble-next-line is set to auto or on output the next
1097 	 instruction.  */
1098       if (disassemble_next_line == AUTO_BOOLEAN_AUTO
1099 	  || disassemble_next_line == AUTO_BOOLEAN_TRUE)
1100 	do_gdb_disassembly (get_frame_arch (frame), 1,
1101 			    get_frame_pc (frame), get_frame_pc (frame) + 1);
1102 
1103       return;
1104     }
1105 
1106   /* If FRAME is not the innermost frame, that normally means that
1107      FRAME->pc points to *after* the call instruction, and we want to
1108      get the line containing the call, never the next line.  But if
1109      the next frame is a SIGTRAMP_FRAME or a DUMMY_FRAME, then the
1110      next frame was not entered as the result of a call, and we want
1111      to get the line containing FRAME->pc.  */
1112   symtab_and_line sal = find_frame_sal (frame);
1113 
1114   location_print = (print_what == LOCATION
1115 		    || print_what == SRC_AND_LOC
1116 		    || print_what == LOC_AND_ADDRESS
1117 		    || print_what == SHORT_LOCATION);
1118   if (location_print || !sal.symtab)
1119     print_frame (fp_opts, frame, print_level, print_what, print_args, sal);
1120 
1121   source_print = (print_what == SRC_LINE || print_what == SRC_AND_LOC);
1122 
1123   /* If disassemble-next-line is set to auto or on and doesn't have
1124      the line debug messages for $pc, output the next instruction.  */
1125   if ((disassemble_next_line == AUTO_BOOLEAN_AUTO
1126        || disassemble_next_line == AUTO_BOOLEAN_TRUE)
1127       && source_print && !sal.symtab)
1128     do_gdb_disassembly (get_frame_arch (frame), 1,
1129 			get_frame_pc (frame), get_frame_pc (frame) + 1);
1130 
1131   if (source_print && sal.symtab)
1132     {
1133       int mid_statement = ((print_what == SRC_LINE)
1134 			   && frame_show_address (frame, sal));
1135       if (annotation_level > 0
1136 	  && annotate_source_line (sal.symtab, sal.line, mid_statement,
1137 				   get_frame_pc (frame)))
1138 	{
1139 	  /* The call to ANNOTATE_SOURCE_LINE already printed the
1140 	     annotation for this source line, so we avoid the two cases
1141 	     below and do not print the actual source line.  The
1142 	     documentation for annotations makes it clear that the source
1143 	     line annotation is printed __instead__ of printing the source
1144 	     line, not as well as.
1145 
1146 	     However, if we fail to print the source line, which usually
1147 	     means either the source file is missing, or the requested
1148 	     line is out of range of the file, then we don't print the
1149 	     source annotation, and will pass through the "normal" print
1150 	     source line code below, the expectation is that this code
1151 	     will print an appropriate error.  */
1152 	}
1153       else if (deprecated_print_frame_info_listing_hook)
1154 	deprecated_print_frame_info_listing_hook (sal.symtab, sal.line,
1155 						  sal.line + 1, 0);
1156       else
1157 	{
1158 	  struct value_print_options opts;
1159 
1160 	  get_user_print_options (&opts);
1161 	  /* We used to do this earlier, but that is clearly
1162 	     wrong.  This function is used by many different
1163 	     parts of gdb, including normal_stop in infrun.c,
1164 	     which uses this to print out the current PC
1165 	     when we stepi/nexti into the middle of a source
1166 	     line.  Only the command line really wants this
1167 	     behavior.  Other UIs probably would like the
1168 	     ability to decide for themselves if it is desired.  */
1169 	  if (opts.addressprint && mid_statement)
1170 	    {
1171 	      print_pc (uiout, gdbarch, frame, get_frame_pc (frame));
1172 	      uiout->text ("\t");
1173 	    }
1174 
1175 	  print_source_lines (sal.symtab, sal.line, sal.line + 1, 0);
1176 	}
1177 
1178       /* If disassemble-next-line is set to on and there is line debug
1179 	 messages, output assembly codes for next line.  */
1180       if (disassemble_next_line == AUTO_BOOLEAN_TRUE)
1181 	do_gdb_disassembly (get_frame_arch (frame), -1, sal.pc, sal.end);
1182     }
1183 
1184   if (set_current_sal)
1185     {
1186       CORE_ADDR pc;
1187 
1188       if (get_frame_pc_if_available (frame, &pc))
1189 	last_displayed_symtab_info.set (sal.pspace, pc, sal.symtab, sal.line);
1190       else
1191 	last_displayed_symtab_info.invalidate ();
1192     }
1193 
1194   annotate_frame_end ();
1195 
1196   gdb_flush (gdb_stdout);
1197 }
1198 
1199 /* See stack.h.  */
1200 
1201 void
clear_last_displayed_sal(void)1202 clear_last_displayed_sal (void)
1203 {
1204   last_displayed_symtab_info.invalidate ();
1205 }
1206 
1207 /* See stack.h.  */
1208 
1209 bool
last_displayed_sal_is_valid(void)1210 last_displayed_sal_is_valid (void)
1211 {
1212   return last_displayed_symtab_info.is_valid ();
1213 }
1214 
1215 /* See stack.h.  */
1216 
1217 struct program_space *
get_last_displayed_pspace(void)1218 get_last_displayed_pspace (void)
1219 {
1220   return last_displayed_symtab_info.pspace ();
1221 }
1222 
1223 /* See stack.h.  */
1224 
1225 CORE_ADDR
get_last_displayed_addr(void)1226 get_last_displayed_addr (void)
1227 {
1228   return last_displayed_symtab_info.address ();
1229 }
1230 
1231 /* See stack.h.  */
1232 
1233 struct symtab*
get_last_displayed_symtab(void)1234 get_last_displayed_symtab (void)
1235 {
1236   return last_displayed_symtab_info.symtab ();
1237 }
1238 
1239 /* See stack.h.  */
1240 
1241 int
get_last_displayed_line(void)1242 get_last_displayed_line (void)
1243 {
1244   return last_displayed_symtab_info.line ();
1245 }
1246 
1247 /* See stack.h.  */
1248 
1249 symtab_and_line
get_last_displayed_sal()1250 get_last_displayed_sal ()
1251 {
1252   symtab_and_line sal;
1253 
1254   if (last_displayed_symtab_info.is_valid ())
1255     {
1256       sal.pspace = last_displayed_symtab_info.pspace ();
1257       sal.pc = last_displayed_symtab_info.address ();
1258       sal.symtab = last_displayed_symtab_info.symtab ();
1259       sal.line = last_displayed_symtab_info.line ();
1260     }
1261 
1262   return sal;
1263 }
1264 
1265 
1266 /* Attempt to obtain the name, FUNLANG and optionally FUNCP of the function
1267    corresponding to FRAME.  */
1268 
1269 gdb::unique_xmalloc_ptr<char>
find_frame_funname(struct frame_info * frame,enum language * funlang,struct symbol ** funcp)1270 find_frame_funname (struct frame_info *frame, enum language *funlang,
1271 		    struct symbol **funcp)
1272 {
1273   struct symbol *func;
1274   gdb::unique_xmalloc_ptr<char> funname;
1275 
1276   *funlang = language_unknown;
1277   if (funcp)
1278     *funcp = NULL;
1279 
1280   func = get_frame_function (frame);
1281   if (func)
1282     {
1283       const char *print_name = func->print_name ();
1284 
1285       *funlang = func->language ();
1286       if (funcp)
1287 	*funcp = func;
1288       if (*funlang == language_cplus)
1289 	{
1290 	  /* It seems appropriate to use print_name() here,
1291 	     to display the demangled name that we already have
1292 	     stored in the symbol table, but we stored a version
1293 	     with DMGL_PARAMS turned on, and here we don't want to
1294 	     display parameters.  So remove the parameters.  */
1295 	  funname = cp_remove_params (print_name);
1296 	}
1297 
1298       /* If we didn't hit the C++ case above, set *funname
1299 	 here.  */
1300       if (funname == NULL)
1301 	funname.reset (xstrdup (print_name));
1302     }
1303   else
1304     {
1305       struct bound_minimal_symbol msymbol;
1306       CORE_ADDR pc;
1307 
1308       if (!get_frame_address_in_block_if_available (frame, &pc))
1309 	return funname;
1310 
1311       msymbol = lookup_minimal_symbol_by_pc (pc);
1312       if (msymbol.minsym != NULL)
1313 	{
1314 	  funname.reset (xstrdup (msymbol.minsym->print_name ()));
1315 	  *funlang = msymbol.minsym->language ();
1316 	}
1317     }
1318 
1319   return funname;
1320 }
1321 
1322 static void
print_frame(const frame_print_options & fp_opts,frame_info * frame,int print_level,enum print_what print_what,int print_args,struct symtab_and_line sal)1323 print_frame (const frame_print_options &fp_opts,
1324 	     frame_info *frame, int print_level,
1325 	     enum print_what print_what, int print_args,
1326 	     struct symtab_and_line sal)
1327 {
1328   struct gdbarch *gdbarch = get_frame_arch (frame);
1329   struct ui_out *uiout = current_uiout;
1330   enum language funlang = language_unknown;
1331   struct value_print_options opts;
1332   struct symbol *func;
1333   CORE_ADDR pc = 0;
1334   int pc_p;
1335 
1336   pc_p = get_frame_pc_if_available (frame, &pc);
1337 
1338   gdb::unique_xmalloc_ptr<char> funname
1339     = find_frame_funname (frame, &funlang, &func);
1340 
1341   annotate_frame_begin (print_level ? frame_relative_level (frame) : 0,
1342 			gdbarch, pc);
1343 
1344   {
1345     ui_out_emit_tuple tuple_emitter (uiout, "frame");
1346 
1347     if (print_level)
1348       {
1349 	uiout->text ("#");
1350 	uiout->field_fmt_signed (2, ui_left, "level",
1351 				 frame_relative_level (frame));
1352       }
1353     get_user_print_options (&opts);
1354     if (opts.addressprint)
1355       if (!sal.symtab
1356 	  || frame_show_address (frame, sal)
1357 	  || print_what == LOC_AND_ADDRESS)
1358 	{
1359 	  annotate_frame_address ();
1360 	  if (pc_p)
1361 	    print_pc (uiout, gdbarch, frame, pc);
1362 	  else
1363 	    uiout->field_string ("addr", "<unavailable>",
1364 				 metadata_style.style ());
1365 	  annotate_frame_address_end ();
1366 	  uiout->text (" in ");
1367 	}
1368     annotate_frame_function_name ();
1369 
1370     string_file stb;
1371     fprintf_symbol_filtered (&stb, funname ? funname.get () : "??",
1372 			     funlang, DMGL_ANSI);
1373     uiout->field_stream ("func", stb, function_name_style.style ());
1374     uiout->wrap_hint ("   ");
1375     annotate_frame_args ();
1376 
1377     uiout->text (" (");
1378     if (print_args)
1379       {
1380 	int numargs;
1381 
1382 	if (gdbarch_frame_num_args_p (gdbarch))
1383 	  {
1384 	    numargs = gdbarch_frame_num_args (gdbarch, frame);
1385 	    gdb_assert (numargs >= 0);
1386 	  }
1387 	else
1388 	  numargs = -1;
1389 
1390 	{
1391 	  ui_out_emit_list list_emitter (uiout, "args");
1392 	  try
1393 	    {
1394 	      print_frame_args (fp_opts, func, frame, numargs, gdb_stdout);
1395 	    }
1396 	  catch (const gdb_exception_error &e)
1397 	    {
1398 	    }
1399 
1400 	    /* FIXME: ARGS must be a list.  If one argument is a string it
1401 	       will have " that will not be properly escaped.  */
1402 	    }
1403 	QUIT;
1404       }
1405     uiout->text (")");
1406     if (print_what != SHORT_LOCATION && sal.symtab)
1407       {
1408 	const char *filename_display;
1409 
1410 	filename_display = symtab_to_filename_for_display (sal.symtab);
1411 	annotate_frame_source_begin ();
1412 	uiout->wrap_hint ("   ");
1413 	uiout->text (" at ");
1414 	annotate_frame_source_file ();
1415 	uiout->field_string ("file", filename_display,
1416 			     file_name_style.style ());
1417 	if (uiout->is_mi_like_p ())
1418 	  {
1419 	    const char *fullname = symtab_to_fullname (sal.symtab);
1420 
1421 	    uiout->field_string ("fullname", fullname);
1422 	  }
1423 	annotate_frame_source_file_end ();
1424 	uiout->text (":");
1425 	annotate_frame_source_line ();
1426 	uiout->field_signed ("line", sal.line);
1427 	annotate_frame_source_end ();
1428       }
1429 
1430     if (print_what != SHORT_LOCATION
1431 	&& pc_p && (funname == NULL || sal.symtab == NULL))
1432       {
1433 	char *lib = solib_name_from_address (get_frame_program_space (frame),
1434 					     get_frame_pc (frame));
1435 
1436 	if (lib)
1437 	  {
1438 	    annotate_frame_where ();
1439 	    uiout->wrap_hint ("  ");
1440 	    uiout->text (" from ");
1441 	    uiout->field_string ("from", lib, file_name_style.style ());
1442 	  }
1443       }
1444     if (uiout->is_mi_like_p ())
1445       uiout->field_string ("arch",
1446 			   (gdbarch_bfd_arch_info (gdbarch))->printable_name);
1447   }
1448 
1449   uiout->text ("\n");
1450 }
1451 
1452 
1453 /* Completion function for "frame function", "info frame function", and
1454    "select-frame function" commands.  */
1455 
1456 static void
frame_selection_by_function_completer(struct cmd_list_element * ignore,completion_tracker & tracker,const char * text,const char * word)1457 frame_selection_by_function_completer (struct cmd_list_element *ignore,
1458 				       completion_tracker &tracker,
1459 				       const char *text, const char *word)
1460 {
1461   /* This is used to complete function names within a stack.  It would be
1462      nice if we only offered functions that were actually in the stack.
1463      However, this would mean unwinding the stack to completion, which
1464      could take too long, or on a corrupted stack, possibly not end.
1465      Instead, we offer all symbol names as a safer choice.  */
1466   collect_symbol_completion_matches (tracker,
1467 				     complete_symbol_mode::EXPRESSION,
1468 				     symbol_name_match_type::EXPRESSION,
1469 				     text, word);
1470 }
1471 
1472 /* Core of all the "info frame" sub-commands.  Print information about a
1473    frame FI.  If SELECTED_FRAME_P is true then the user didn't provide a
1474    frame specification, they just entered 'info frame'.  If the user did
1475    provide a frame specification (for example 'info frame 0', 'info frame
1476    level 1') then SELECTED_FRAME_P will be false.  */
1477 
1478 static void
info_frame_command_core(struct frame_info * fi,bool selected_frame_p)1479 info_frame_command_core (struct frame_info *fi, bool selected_frame_p)
1480 {
1481   struct symbol *func;
1482   struct symtab *s;
1483   struct frame_info *calling_frame_info;
1484   int numregs;
1485   const char *funname = 0;
1486   enum language funlang = language_unknown;
1487   const char *pc_regname;
1488   struct gdbarch *gdbarch;
1489   CORE_ADDR frame_pc;
1490   int frame_pc_p;
1491   /* Initialize it to avoid "may be used uninitialized" warning.  */
1492   CORE_ADDR caller_pc = 0;
1493   int caller_pc_p = 0;
1494 
1495   gdbarch = get_frame_arch (fi);
1496 
1497   /* Name of the value returned by get_frame_pc().  Per comments, "pc"
1498      is not a good name.  */
1499   if (gdbarch_pc_regnum (gdbarch) >= 0)
1500     /* OK, this is weird.  The gdbarch_pc_regnum hardware register's value can
1501        easily not match that of the internal value returned by
1502        get_frame_pc().  */
1503     pc_regname = gdbarch_register_name (gdbarch, gdbarch_pc_regnum (gdbarch));
1504   else
1505     /* But then, this is weird to.  Even without gdbarch_pc_regnum, an
1506        architectures will often have a hardware register called "pc",
1507        and that register's value, again, can easily not match
1508        get_frame_pc().  */
1509     pc_regname = "pc";
1510 
1511   frame_pc_p = get_frame_pc_if_available (fi, &frame_pc);
1512   func = get_frame_function (fi);
1513   symtab_and_line sal = find_frame_sal (fi);
1514   s = sal.symtab;
1515   gdb::unique_xmalloc_ptr<char> func_only;
1516   if (func)
1517     {
1518       funname = func->print_name ();
1519       funlang = func->language ();
1520       if (funlang == language_cplus)
1521 	{
1522 	  /* It seems appropriate to use print_name() here,
1523 	     to display the demangled name that we already have
1524 	     stored in the symbol table, but we stored a version
1525 	     with DMGL_PARAMS turned on, and here we don't want to
1526 	     display parameters.  So remove the parameters.  */
1527 	  func_only = cp_remove_params (funname);
1528 
1529 	  if (func_only)
1530 	    funname = func_only.get ();
1531 	}
1532     }
1533   else if (frame_pc_p)
1534     {
1535       struct bound_minimal_symbol msymbol;
1536 
1537       msymbol = lookup_minimal_symbol_by_pc (frame_pc);
1538       if (msymbol.minsym != NULL)
1539 	{
1540 	  funname = msymbol.minsym->print_name ();
1541 	  funlang = msymbol.minsym->language ();
1542 	}
1543     }
1544   calling_frame_info = get_prev_frame (fi);
1545 
1546   if (selected_frame_p && frame_relative_level (fi) >= 0)
1547     {
1548       printf_filtered (_("Stack level %d, frame at "),
1549 		       frame_relative_level (fi));
1550     }
1551   else
1552     {
1553       printf_filtered (_("Stack frame at "));
1554     }
1555   fputs_filtered (paddress (gdbarch, get_frame_base (fi)), gdb_stdout);
1556   printf_filtered (":\n");
1557   printf_filtered (" %s = ", pc_regname);
1558   if (frame_pc_p)
1559     fputs_filtered (paddress (gdbarch, get_frame_pc (fi)), gdb_stdout);
1560   else
1561     fputs_styled ("<unavailable>", metadata_style.style (), gdb_stdout);
1562 
1563   wrap_here ("   ");
1564   if (funname)
1565     {
1566       printf_filtered (" in ");
1567       fprintf_symbol_filtered (gdb_stdout, funname, funlang,
1568 			       DMGL_ANSI | DMGL_PARAMS);
1569     }
1570   wrap_here ("   ");
1571   if (sal.symtab)
1572     printf_filtered
1573       (" (%ps:%d)",
1574        styled_string (file_name_style.style (),
1575 		      symtab_to_filename_for_display (sal.symtab)),
1576        sal.line);
1577   puts_filtered ("; ");
1578   wrap_here ("    ");
1579   printf_filtered ("saved %s = ", pc_regname);
1580 
1581   if (!frame_id_p (frame_unwind_caller_id (fi)))
1582     val_print_not_saved (gdb_stdout);
1583   else
1584     {
1585       try
1586 	{
1587 	  caller_pc = frame_unwind_caller_pc (fi);
1588 	  caller_pc_p = 1;
1589 	}
1590       catch (const gdb_exception_error &ex)
1591 	{
1592 	  switch (ex.error)
1593 	    {
1594 	    case NOT_AVAILABLE_ERROR:
1595 	      val_print_unavailable (gdb_stdout);
1596 	      break;
1597 	    case OPTIMIZED_OUT_ERROR:
1598 	      val_print_not_saved (gdb_stdout);
1599 	      break;
1600 	    default:
1601 	      fprintf_styled (gdb_stdout, metadata_style.style (),
1602 			      _("<error: %s>"),
1603 			      ex.what ());
1604 	      break;
1605 	    }
1606 	}
1607     }
1608 
1609   if (caller_pc_p)
1610     fputs_filtered (paddress (gdbarch, caller_pc), gdb_stdout);
1611   printf_filtered ("\n");
1612 
1613   if (calling_frame_info == NULL)
1614     {
1615       enum unwind_stop_reason reason;
1616 
1617       reason = get_frame_unwind_stop_reason (fi);
1618       if (reason != UNWIND_NO_REASON)
1619 	printf_filtered (_(" Outermost frame: %s\n"),
1620 			 frame_stop_reason_string (fi));
1621     }
1622   else if (get_frame_type (fi) == TAILCALL_FRAME)
1623     puts_filtered (" tail call frame");
1624   else if (get_frame_type (fi) == INLINE_FRAME)
1625     printf_filtered (" inlined into frame %d",
1626 		     frame_relative_level (get_prev_frame (fi)));
1627   else
1628     {
1629       printf_filtered (" called by frame at ");
1630       fputs_filtered (paddress (gdbarch, get_frame_base (calling_frame_info)),
1631 		      gdb_stdout);
1632     }
1633   if (get_next_frame (fi) && calling_frame_info)
1634     puts_filtered (",");
1635   wrap_here ("   ");
1636   if (get_next_frame (fi))
1637     {
1638       printf_filtered (" caller of frame at ");
1639       fputs_filtered (paddress (gdbarch, get_frame_base (get_next_frame (fi))),
1640 		      gdb_stdout);
1641     }
1642   if (get_next_frame (fi) || calling_frame_info)
1643     puts_filtered ("\n");
1644 
1645   if (s)
1646     printf_filtered (" source language %s.\n",
1647 		     language_str (s->language));
1648 
1649   {
1650     /* Address of the argument list for this frame, or 0.  */
1651     CORE_ADDR arg_list = get_frame_args_address (fi);
1652     /* Number of args for this frame, or -1 if unknown.  */
1653     int numargs;
1654 
1655     if (arg_list == 0)
1656       printf_filtered (" Arglist at unknown address.\n");
1657     else
1658       {
1659 	printf_filtered (" Arglist at ");
1660 	fputs_filtered (paddress (gdbarch, arg_list), gdb_stdout);
1661 	printf_filtered (",");
1662 
1663 	if (!gdbarch_frame_num_args_p (gdbarch))
1664 	  {
1665 	    numargs = -1;
1666 	    puts_filtered (" args: ");
1667 	  }
1668 	else
1669 	  {
1670 	    numargs = gdbarch_frame_num_args (gdbarch, fi);
1671 	    gdb_assert (numargs >= 0);
1672 	    if (numargs == 0)
1673 	      puts_filtered (" no args.");
1674 	    else if (numargs == 1)
1675 	      puts_filtered (" 1 arg: ");
1676 	    else
1677 	      printf_filtered (" %d args: ", numargs);
1678 	  }
1679 	print_frame_args (user_frame_print_options,
1680 			  func, fi, numargs, gdb_stdout);
1681 	puts_filtered ("\n");
1682       }
1683   }
1684   {
1685     /* Address of the local variables for this frame, or 0.  */
1686     CORE_ADDR arg_list = get_frame_locals_address (fi);
1687 
1688     if (arg_list == 0)
1689       printf_filtered (" Locals at unknown address,");
1690     else
1691       {
1692 	printf_filtered (" Locals at ");
1693 	fputs_filtered (paddress (gdbarch, arg_list), gdb_stdout);
1694 	printf_filtered (",");
1695       }
1696   }
1697 
1698   /* Print as much information as possible on the location of all the
1699      registers.  */
1700   {
1701     int count;
1702     int i;
1703     int need_nl = 1;
1704     int sp_regnum = gdbarch_sp_regnum (gdbarch);
1705 
1706     /* The sp is special; what's displayed isn't the save address, but
1707        the value of the previous frame's sp.  This is a legacy thing,
1708        at one stage the frame cached the previous frame's SP instead
1709        of its address, hence it was easiest to just display the cached
1710        value.  */
1711     if (sp_regnum >= 0)
1712       {
1713 	struct value *value = frame_unwind_register_value (fi, sp_regnum);
1714 	gdb_assert (value != NULL);
1715 
1716 	if (!value_optimized_out (value) && value_entirely_available (value))
1717 	  {
1718 	    if (VALUE_LVAL (value) == not_lval)
1719 	      {
1720 		CORE_ADDR sp;
1721 		enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
1722 		int sp_size = register_size (gdbarch, sp_regnum);
1723 
1724 		sp = extract_unsigned_integer (value_contents_all (value),
1725 					       sp_size, byte_order);
1726 
1727 		printf_filtered (" Previous frame's sp is ");
1728 		fputs_filtered (paddress (gdbarch, sp), gdb_stdout);
1729 		printf_filtered ("\n");
1730 	      }
1731 	    else if (VALUE_LVAL (value) == lval_memory)
1732 	      {
1733 		printf_filtered (" Previous frame's sp at ");
1734 		fputs_filtered (paddress (gdbarch, value_address (value)),
1735 				gdb_stdout);
1736 		printf_filtered ("\n");
1737 	      }
1738 	    else if (VALUE_LVAL (value) == lval_register)
1739 	      {
1740 		printf_filtered (" Previous frame's sp in %s\n",
1741 				 gdbarch_register_name (gdbarch,
1742 							VALUE_REGNUM (value)));
1743 	      }
1744 
1745 	    release_value (value);
1746 	    need_nl = 0;
1747 	  }
1748 	/* else keep quiet.  */
1749       }
1750 
1751     count = 0;
1752     numregs = gdbarch_num_cooked_regs (gdbarch);
1753     for (i = 0; i < numregs; i++)
1754       if (i != sp_regnum
1755 	  && gdbarch_register_reggroup_p (gdbarch, i, all_reggroup))
1756 	{
1757 	  enum lval_type lval;
1758 	  int optimized;
1759 	  int unavailable;
1760 	  CORE_ADDR addr;
1761 	  int realnum;
1762 
1763 	  /* Find out the location of the saved register without
1764 	     fetching the corresponding value.  */
1765 	  frame_register_unwind (fi, i, &optimized, &unavailable,
1766 				 &lval, &addr, &realnum, NULL);
1767 	  /* For moment, only display registers that were saved on the
1768 	     stack.  */
1769 	  if (!optimized && !unavailable && lval == lval_memory)
1770 	    {
1771 	      if (count == 0)
1772 		puts_filtered (" Saved registers:\n ");
1773 	      else
1774 		puts_filtered (",");
1775 	      wrap_here (" ");
1776 	      printf_filtered (" %s at ",
1777 			       gdbarch_register_name (gdbarch, i));
1778 	      fputs_filtered (paddress (gdbarch, addr), gdb_stdout);
1779 	      count++;
1780 	    }
1781 	}
1782     if (count || need_nl)
1783       puts_filtered ("\n");
1784   }
1785 }
1786 
1787 /* Return the innermost frame at level LEVEL.  */
1788 
1789 static struct frame_info *
leading_innermost_frame(int level)1790 leading_innermost_frame (int level)
1791 {
1792   struct frame_info *leading;
1793 
1794   leading = get_current_frame ();
1795 
1796   gdb_assert (level >= 0);
1797 
1798   while (leading != nullptr && level)
1799     {
1800       QUIT;
1801       leading = get_prev_frame (leading);
1802       level--;
1803     }
1804 
1805   return leading;
1806 }
1807 
1808 /* Return the starting frame needed to handle COUNT outermost frames.  */
1809 
1810 static struct frame_info *
trailing_outermost_frame(int count)1811 trailing_outermost_frame (int count)
1812 {
1813   struct frame_info *current;
1814   struct frame_info *trailing;
1815 
1816   trailing = get_current_frame ();
1817 
1818   gdb_assert (count > 0);
1819 
1820   current = trailing;
1821   while (current != nullptr && count--)
1822     {
1823       QUIT;
1824       current = get_prev_frame (current);
1825     }
1826 
1827   /* Will stop when CURRENT reaches the top of the stack.
1828      TRAILING will be COUNT below it.  */
1829   while (current != nullptr)
1830     {
1831       QUIT;
1832       trailing = get_prev_frame (trailing);
1833       current = get_prev_frame (current);
1834     }
1835 
1836   return trailing;
1837 }
1838 
1839 /* The core of all the "select-frame" sub-commands.  Just wraps a call to
1840    SELECT_FRAME.  */
1841 
1842 static void
select_frame_command_core(struct frame_info * fi,bool ignored)1843 select_frame_command_core (struct frame_info *fi, bool ignored)
1844 {
1845   frame_info *prev_frame = get_selected_frame ();
1846   select_frame (fi);
1847   if (get_selected_frame () != prev_frame)
1848     gdb::observers::user_selected_context_changed.notify (USER_SELECTED_FRAME);
1849 }
1850 
1851 /* See stack.h.  */
1852 
1853 void
select_frame_for_mi(struct frame_info * fi)1854 select_frame_for_mi (struct frame_info *fi)
1855 {
1856   select_frame_command_core (fi, false /* Ignored.  */);
1857 }
1858 
1859 /* The core of all the "frame" sub-commands.  Select frame FI, and if this
1860    means we change frame send out a change notification (otherwise, just
1861    reprint the current frame summary).   */
1862 
1863 static void
frame_command_core(struct frame_info * fi,bool ignored)1864 frame_command_core (struct frame_info *fi, bool ignored)
1865 {
1866   frame_info *prev_frame = get_selected_frame ();
1867   select_frame (fi);
1868   if (get_selected_frame () != prev_frame)
1869     gdb::observers::user_selected_context_changed.notify (USER_SELECTED_FRAME);
1870   else
1871     print_selected_thread_frame (current_uiout, USER_SELECTED_FRAME);
1872 }
1873 
1874 /* The three commands 'frame', 'select-frame', and 'info frame' all have a
1875    common set of sub-commands that allow a specific frame to be selected.
1876    All of the sub-command functions are static methods within this class
1877    template which is then instantiated below.  The template parameter is a
1878    callback used to implement the functionality of the base command
1879    ('frame', 'select-frame', or 'info frame').
1880 
1881    In the template parameter FI is the frame being selected.  The
1882    SELECTED_FRAME_P flag is true if the frame being selected was done by
1883    default, which happens when the user uses the base command with no
1884    arguments.  For example the commands 'info frame', 'select-frame',
1885    'frame' will all cause SELECTED_FRAME_P to be true.  In all other cases
1886    SELECTED_FRAME_P is false.  */
1887 
1888 template <void (*FPTR) (struct frame_info *fi, bool selected_frame_p)>
1889 class frame_command_helper
1890 {
1891 public:
1892 
1893   /* The "frame level" family of commands.  The ARG is an integer that is
1894      the frame's level in the stack.  */
1895   static void
level(const char * arg,int from_tty)1896   level (const char *arg, int from_tty)
1897   {
1898     int level = value_as_long (parse_and_eval (arg));
1899     struct frame_info *fid
1900       = find_relative_frame (get_current_frame (), &level);
1901     if (level != 0)
1902       error (_("No frame at level %s."), arg);
1903     FPTR (fid, false);
1904   }
1905 
1906   /* The "frame address" family of commands.  ARG is a stack-pointer
1907      address for an existing frame.  This command does not allow new
1908      frames to be created.  */
1909 
1910   static void
address(const char * arg,int from_tty)1911   address (const char *arg, int from_tty)
1912   {
1913     CORE_ADDR addr = value_as_address (parse_and_eval (arg));
1914     struct frame_info *fid = find_frame_for_address (addr);
1915     if (fid == NULL)
1916       error (_("No frame at address %s."), arg);
1917     FPTR (fid, false);
1918   }
1919 
1920   /* The "frame view" family of commands.  ARG is one or two addresses and
1921      is used to view a frame that might be outside the current backtrace.
1922      The addresses are stack-pointer address, and (optional) pc-address.  */
1923 
1924   static void
view(const char * args,int from_tty)1925   view (const char *args, int from_tty)
1926   {
1927     struct frame_info *fid;
1928 
1929     if (args == NULL)
1930       error (_("Missing address argument to view a frame"));
1931 
1932     gdb_argv argv (args);
1933 
1934     if (argv.count () == 2)
1935       {
1936 	CORE_ADDR addr[2];
1937 
1938 	addr [0] = value_as_address (parse_and_eval (argv[0]));
1939 	addr [1] = value_as_address (parse_and_eval (argv[1]));
1940 	fid = create_new_frame (addr[0], addr[1]);
1941       }
1942     else
1943       {
1944 	CORE_ADDR addr = value_as_address (parse_and_eval (argv[0]));
1945 	fid = create_new_frame (addr, false);
1946       }
1947     FPTR (fid, false);
1948   }
1949 
1950   /* The "frame function" family of commands.  ARG is the name of a
1951      function within the stack, the first function (searching from frame
1952      0) with that name will be selected.  */
1953 
1954   static void
function(const char * arg,int from_tty)1955   function (const char *arg, int from_tty)
1956   {
1957     if (arg == NULL)
1958       error (_("Missing function name argument"));
1959     struct frame_info *fid = find_frame_for_function (arg);
1960     if (fid == NULL)
1961       error (_("No frame for function \"%s\"."), arg);
1962     FPTR (fid, false);
1963   }
1964 
1965   /* The "frame" base command, that is, when no sub-command is specified.
1966      If one argument is provided then we assume that this is a frame's
1967      level as historically, this was the supported command syntax that was
1968      used most often.
1969 
1970      If no argument is provided, then the current frame is selected.  */
1971 
1972   static void
base_command(const char * arg,int from_tty)1973   base_command (const char *arg, int from_tty)
1974   {
1975     if (arg == NULL)
1976       FPTR (get_selected_frame (_("No stack.")), true);
1977     else
1978       level (arg, from_tty);
1979   }
1980 };
1981 
1982 /* Instantiate three FRAME_COMMAND_HELPER instances to implement the
1983    sub-commands for 'info frame', 'frame', and 'select-frame' commands.  */
1984 
1985 static frame_command_helper <info_frame_command_core> info_frame_cmd;
1986 static frame_command_helper <frame_command_core> frame_cmd;
1987 static frame_command_helper <select_frame_command_core> select_frame_cmd;
1988 
1989 /* Print briefly all stack frames or just the innermost COUNT_EXP
1990    frames.  */
1991 
1992 static void
backtrace_command_1(const frame_print_options & fp_opts,const backtrace_cmd_options & bt_opts,const char * count_exp,int from_tty)1993 backtrace_command_1 (const frame_print_options &fp_opts,
1994 		     const backtrace_cmd_options &bt_opts,
1995 		     const char *count_exp, int from_tty)
1996 
1997 {
1998   struct frame_info *fi;
1999   int count;
2000   int py_start = 0, py_end = 0;
2001   enum ext_lang_bt_status result = EXT_LANG_BT_ERROR;
2002 
2003   if (!target_has_stack ())
2004     error (_("No stack."));
2005 
2006   if (count_exp)
2007     {
2008       count = parse_and_eval_long (count_exp);
2009       if (count < 0)
2010 	py_start = count;
2011       else
2012 	{
2013 	  py_start = 0;
2014 	  /* The argument to apply_ext_lang_frame_filter is the number
2015 	     of the final frame to print, and frames start at 0.  */
2016 	  py_end = count - 1;
2017 	}
2018     }
2019   else
2020     {
2021       py_end = -1;
2022       count = -1;
2023     }
2024 
2025   frame_filter_flags flags = 0;
2026 
2027   if (bt_opts.full)
2028     flags |= PRINT_LOCALS;
2029   if (bt_opts.hide)
2030     flags |= PRINT_HIDE;
2031 
2032   if (!bt_opts.no_filters)
2033     {
2034       enum ext_lang_frame_args arg_type;
2035 
2036       flags |= PRINT_LEVEL | PRINT_FRAME_INFO | PRINT_ARGS;
2037       if (from_tty)
2038 	flags |= PRINT_MORE_FRAMES;
2039 
2040       if (fp_opts.print_frame_arguments == print_frame_arguments_scalars)
2041 	arg_type = CLI_SCALAR_VALUES;
2042       else if (fp_opts.print_frame_arguments == print_frame_arguments_all)
2043 	arg_type = CLI_ALL_VALUES;
2044       else if (fp_opts.print_frame_arguments == print_frame_arguments_presence)
2045 	arg_type = CLI_PRESENCE;
2046       else if (fp_opts.print_frame_arguments == print_frame_arguments_none)
2047 	arg_type = NO_VALUES;
2048       else
2049 	gdb_assert (0);
2050 
2051       result = apply_ext_lang_frame_filter (get_current_frame (), flags,
2052 					    arg_type, current_uiout,
2053 					    py_start, py_end);
2054     }
2055 
2056   /* Run the inbuilt backtrace if there are no filters registered, or
2057      "-no-filters" has been specified from the command.  */
2058   if (bt_opts.no_filters || result == EXT_LANG_BT_NO_FILTERS)
2059     {
2060       struct frame_info *trailing;
2061 
2062       /* The following code must do two things.  First, it must set the
2063 	 variable TRAILING to the frame from which we should start
2064 	 printing.  Second, it must set the variable count to the number
2065 	 of frames which we should print, or -1 if all of them.  */
2066 
2067       if (count_exp != NULL && count < 0)
2068 	{
2069 	  trailing = trailing_outermost_frame (-count);
2070 	  count = -1;
2071 	}
2072       else
2073 	trailing = get_current_frame ();
2074 
2075       for (fi = trailing; fi && count--; fi = get_prev_frame (fi))
2076 	{
2077 	  QUIT;
2078 
2079 	  /* Don't use print_stack_frame; if an error() occurs it probably
2080 	     means further attempts to backtrace would fail (on the other
2081 	     hand, perhaps the code does or could be fixed to make sure
2082 	     the frame->prev field gets set to NULL in that case).  */
2083 
2084 	  print_frame_info (fp_opts, fi, 1, LOCATION, 1, 0);
2085 	  if ((flags & PRINT_LOCALS) != 0)
2086 	    {
2087 	      struct frame_id frame_id = get_frame_id (fi);
2088 
2089 	      print_frame_local_vars (fi, false, NULL, NULL, 1, gdb_stdout);
2090 
2091 	      /* print_frame_local_vars invalidates FI.  */
2092 	      fi = frame_find_by_id (frame_id);
2093 	      if (fi == NULL)
2094 		{
2095 		  trailing = NULL;
2096 		  warning (_("Unable to restore previously selected frame."));
2097 		  break;
2098 		}
2099 	    }
2100 
2101 	  /* Save the last frame to check for error conditions.  */
2102 	  trailing = fi;
2103 	}
2104 
2105       /* If we've stopped before the end, mention that.  */
2106       if (fi && from_tty)
2107 	printf_filtered (_("(More stack frames follow...)\n"));
2108 
2109       /* If we've run out of frames, and the reason appears to be an error
2110 	 condition, print it.  */
2111       if (fi == NULL && trailing != NULL)
2112 	{
2113 	  enum unwind_stop_reason reason;
2114 
2115 	  reason = get_frame_unwind_stop_reason (trailing);
2116 	  if (reason >= UNWIND_FIRST_ERROR)
2117 	    printf_filtered (_("Backtrace stopped: %s\n"),
2118 			     frame_stop_reason_string (trailing));
2119 	}
2120     }
2121 }
2122 
2123 /* Create an option_def_group array grouping all the "backtrace"
2124    options, with FP_OPTS, BT_CMD_OPT, SET_BT_OPTS as contexts.  */
2125 
2126 static inline std::array<gdb::option::option_def_group, 3>
make_backtrace_options_def_group(frame_print_options * fp_opts,backtrace_cmd_options * bt_cmd_opts,set_backtrace_options * set_bt_opts)2127 make_backtrace_options_def_group (frame_print_options *fp_opts,
2128 				  backtrace_cmd_options *bt_cmd_opts,
2129 				  set_backtrace_options *set_bt_opts)
2130 {
2131   return {{
2132     { {frame_print_option_defs}, fp_opts },
2133     { {set_backtrace_option_defs}, set_bt_opts },
2134     { {backtrace_command_option_defs}, bt_cmd_opts }
2135   }};
2136 }
2137 
2138 /* Parse the backtrace command's qualifiers.  Returns ARG advanced
2139    past the qualifiers, if any.  BT_CMD_OPTS, if not null, is used to
2140    store the parsed qualifiers.  */
2141 
2142 static const char *
2143 parse_backtrace_qualifiers (const char *arg,
2144 			    backtrace_cmd_options *bt_cmd_opts = nullptr)
2145 {
2146   while (true)
2147     {
2148       const char *save_arg = arg;
2149       std::string this_arg = extract_arg (&arg);
2150 
2151       if (this_arg.empty ())
2152 	return arg;
2153 
2154       if (subset_compare (this_arg.c_str (), "no-filters"))
2155 	{
2156 	  if (bt_cmd_opts != nullptr)
2157 	    bt_cmd_opts->no_filters = true;
2158 	}
2159       else if (subset_compare (this_arg.c_str (), "full"))
2160 	{
2161 	  if (bt_cmd_opts != nullptr)
2162 	    bt_cmd_opts->full = true;
2163 	}
2164       else if (subset_compare (this_arg.c_str (), "hide"))
2165 	{
2166 	  if (bt_cmd_opts != nullptr)
2167 	    bt_cmd_opts->hide = true;
2168 	}
2169       else
2170 	{
2171 	  /* Not a recognized qualifier, so stop.  */
2172 	  return save_arg;
2173 	}
2174     }
2175 }
2176 
2177 static void
backtrace_command(const char * arg,int from_tty)2178 backtrace_command (const char *arg, int from_tty)
2179 {
2180   frame_print_options fp_opts = user_frame_print_options;
2181   backtrace_cmd_options bt_cmd_opts;
2182   set_backtrace_options set_bt_opts = user_set_backtrace_options;
2183 
2184   auto grp
2185     = make_backtrace_options_def_group (&fp_opts, &bt_cmd_opts, &set_bt_opts);
2186   gdb::option::process_options
2187     (&arg, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, grp);
2188 
2189   /* Parse non-'-'-prefixed qualifiers, for backwards
2190      compatibility.  */
2191   if (arg != NULL)
2192     {
2193       arg = parse_backtrace_qualifiers (arg, &bt_cmd_opts);
2194       if (*arg == '\0')
2195 	arg = NULL;
2196     }
2197 
2198   /* These options are handled quite deep in the unwind machinery, so
2199      we get to pass them down by swapping globals.  */
2200   scoped_restore restore_set_backtrace_options
2201     = make_scoped_restore (&user_set_backtrace_options, set_bt_opts);
2202 
2203   backtrace_command_1 (fp_opts, bt_cmd_opts, arg, from_tty);
2204 }
2205 
2206 /* Completer for the "backtrace" command.  */
2207 
2208 static void
backtrace_command_completer(struct cmd_list_element * ignore,completion_tracker & tracker,const char * text,const char *)2209 backtrace_command_completer (struct cmd_list_element *ignore,
2210 			     completion_tracker &tracker,
2211 			     const char *text, const char */*word*/)
2212 {
2213   const auto group
2214     = make_backtrace_options_def_group (nullptr, nullptr, nullptr);
2215   if (gdb::option::complete_options
2216       (tracker, &text, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, group))
2217     return;
2218 
2219   if (*text != '\0')
2220     {
2221       const char *p = skip_to_space (text);
2222       if (*p == '\0')
2223 	{
2224 	  static const char *const backtrace_cmd_qualifier_choices[] = {
2225 	    "full", "no-filters", "hide", nullptr,
2226 	  };
2227 	  complete_on_enum (tracker, backtrace_cmd_qualifier_choices,
2228 			    text, text);
2229 
2230 	  if (tracker.have_completions ())
2231 	    return;
2232 	}
2233       else
2234 	{
2235 	  const char *cmd = parse_backtrace_qualifiers (text);
2236 	  tracker.advance_custom_word_point_by (cmd - text);
2237 	  text = cmd;
2238 	}
2239     }
2240 
2241   const char *word = advance_to_expression_complete_word_point (tracker, text);
2242   expression_completer (ignore, tracker, text, word);
2243 }
2244 
2245 /* Iterate over the local variables of a block B, calling CB with
2246    CB_DATA.  */
2247 
2248 static void
iterate_over_block_locals(const struct block * b,iterate_over_block_arg_local_vars_cb cb,void * cb_data)2249 iterate_over_block_locals (const struct block *b,
2250 			   iterate_over_block_arg_local_vars_cb cb,
2251 			   void *cb_data)
2252 {
2253   struct block_iterator iter;
2254   struct symbol *sym;
2255 
2256   ALL_BLOCK_SYMBOLS (b, iter, sym)
2257     {
2258       switch (SYMBOL_CLASS (sym))
2259 	{
2260 	case LOC_CONST:
2261 	case LOC_LOCAL:
2262 	case LOC_REGISTER:
2263 	case LOC_STATIC:
2264 	case LOC_COMPUTED:
2265 	case LOC_OPTIMIZED_OUT:
2266 	  if (SYMBOL_IS_ARGUMENT (sym))
2267 	    break;
2268 	  if (SYMBOL_DOMAIN (sym) == COMMON_BLOCK_DOMAIN)
2269 	    break;
2270 	  (*cb) (sym->print_name (), sym, cb_data);
2271 	  break;
2272 
2273 	default:
2274 	  /* Ignore symbols which are not locals.  */
2275 	  break;
2276 	}
2277     }
2278 }
2279 
2280 /* Iterate over all the local variables in block B, including all its
2281    superblocks, stopping when the top-level block is reached.  */
2282 
2283 void
iterate_over_block_local_vars(const struct block * block,iterate_over_block_arg_local_vars_cb cb,void * cb_data)2284 iterate_over_block_local_vars (const struct block *block,
2285 			       iterate_over_block_arg_local_vars_cb cb,
2286 			       void *cb_data)
2287 {
2288   while (block)
2289     {
2290       iterate_over_block_locals (block, cb, cb_data);
2291       /* After handling the function's top-level block, stop.  Don't
2292 	 continue to its superblock, the block of per-file
2293 	 symbols.  */
2294       if (BLOCK_FUNCTION (block))
2295 	break;
2296       block = BLOCK_SUPERBLOCK (block);
2297     }
2298 }
2299 
2300 /* Data to be passed around in the calls to the locals and args
2301    iterators.  */
2302 
2303 struct print_variable_and_value_data
2304 {
2305   gdb::optional<compiled_regex> preg;
2306   gdb::optional<compiled_regex> treg;
2307   struct frame_id frame_id;
2308   int num_tabs;
2309   struct ui_file *stream;
2310   int values_printed;
2311 };
2312 
2313 /* The callback for the locals and args iterators.  */
2314 
2315 static void
do_print_variable_and_value(const char * print_name,struct symbol * sym,void * cb_data)2316 do_print_variable_and_value (const char *print_name,
2317 			     struct symbol *sym,
2318 			     void *cb_data)
2319 {
2320   struct print_variable_and_value_data *p
2321     = (struct print_variable_and_value_data *) cb_data;
2322   struct frame_info *frame;
2323 
2324   if (p->preg.has_value ()
2325       && p->preg->exec (sym->natural_name (), 0, NULL, 0) != 0)
2326     return;
2327   if (p->treg.has_value ()
2328       && !treg_matches_sym_type_name (*p->treg, sym))
2329     return;
2330 
2331   frame = frame_find_by_id (p->frame_id);
2332   if (frame == NULL)
2333     {
2334       warning (_("Unable to restore previously selected frame."));
2335       return;
2336     }
2337 
2338   print_variable_and_value (print_name, sym, frame, p->stream, p->num_tabs);
2339 
2340   /* print_variable_and_value invalidates FRAME.  */
2341   frame = NULL;
2342 
2343   p->values_printed = 1;
2344 }
2345 
2346 /* Prepares the regular expression REG from REGEXP.
2347    If REGEXP is NULL, it results in an empty regular expression.  */
2348 
2349 static void
prepare_reg(const char * regexp,gdb::optional<compiled_regex> * reg)2350 prepare_reg (const char *regexp, gdb::optional<compiled_regex> *reg)
2351 {
2352   if (regexp != NULL)
2353     {
2354       int cflags = REG_NOSUB | (case_sensitivity == case_sensitive_off
2355 				? REG_ICASE : 0);
2356       reg->emplace (regexp, cflags, _("Invalid regexp"));
2357     }
2358   else
2359     reg->reset ();
2360 }
2361 
2362 /* Print all variables from the innermost up to the function block of FRAME.
2363    Print them with values to STREAM indented by NUM_TABS.
2364    If REGEXP is not NULL, only print local variables whose name
2365    matches REGEXP.
2366    If T_REGEXP is not NULL, only print local variables whose type
2367    matches T_REGEXP.
2368    If no local variables have been printed and !QUIET, prints a message
2369    explaining why no local variables could be printed.
2370 
2371    This function will invalidate FRAME.  */
2372 
2373 static void
print_frame_local_vars(struct frame_info * frame,bool quiet,const char * regexp,const char * t_regexp,int num_tabs,struct ui_file * stream)2374 print_frame_local_vars (struct frame_info *frame,
2375 			bool quiet,
2376 			const char *regexp, const char *t_regexp,
2377 			int num_tabs, struct ui_file *stream)
2378 {
2379   struct print_variable_and_value_data cb_data;
2380   const struct block *block;
2381   CORE_ADDR pc;
2382 
2383   if (!get_frame_pc_if_available (frame, &pc))
2384     {
2385       if (!quiet)
2386 	fprintf_filtered (stream,
2387 			  _("PC unavailable, cannot determine locals.\n"));
2388       return;
2389     }
2390 
2391   block = get_frame_block (frame, 0);
2392   if (block == 0)
2393     {
2394       if (!quiet)
2395 	fprintf_filtered (stream, "No symbol table info available.\n");
2396       return;
2397     }
2398 
2399   prepare_reg (regexp, &cb_data.preg);
2400   prepare_reg (t_regexp, &cb_data.treg);
2401   cb_data.frame_id = get_frame_id (frame);
2402   cb_data.num_tabs = 4 * num_tabs;
2403   cb_data.stream = stream;
2404   cb_data.values_printed = 0;
2405 
2406   /* Temporarily change the selected frame to the given FRAME.
2407      This allows routines that rely on the selected frame instead
2408      of being given a frame as parameter to use the correct frame.  */
2409   scoped_restore_selected_frame restore_selected_frame;
2410   select_frame (frame);
2411 
2412   iterate_over_block_local_vars (block,
2413 				 do_print_variable_and_value,
2414 				 &cb_data);
2415 
2416   if (!cb_data.values_printed && !quiet)
2417     {
2418       if (regexp == NULL && t_regexp == NULL)
2419 	fprintf_filtered (stream, _("No locals.\n"));
2420       else
2421 	fprintf_filtered (stream, _("No matching locals.\n"));
2422     }
2423 }
2424 
2425 /* Structure to hold the values of the options used by the 'info
2426    variables' command and other similar commands.  These correspond to the
2427    -q and -t options.  */
2428 
2429 struct info_print_options
2430 {
2431   bool quiet = false;
2432   char *type_regexp = nullptr;
2433 
~info_print_optionsinfo_print_options2434   ~info_print_options ()
2435   {
2436     xfree (type_regexp);
2437   }
2438 };
2439 
2440 /* The options used by the 'info locals' and 'info args' commands.  */
2441 
2442 static const gdb::option::option_def info_print_options_defs[] = {
2443   gdb::option::boolean_option_def<info_print_options> {
2444     "q",
2445     [] (info_print_options *opt) { return &opt->quiet; },
2446     nullptr, /* show_cmd_cb */
2447     nullptr /* set_doc */
2448   },
2449 
2450   gdb::option::string_option_def<info_print_options> {
2451     "t",
2452     [] (info_print_options *opt) { return &opt->type_regexp; },
2453     nullptr, /* show_cmd_cb */
2454     nullptr /* set_doc */
2455   }
2456 };
2457 
2458 /* Returns the option group used by 'info locals' and 'info args'
2459    commands.  */
2460 
2461 static gdb::option::option_def_group
make_info_print_options_def_group(info_print_options * opts)2462 make_info_print_options_def_group (info_print_options *opts)
2463 {
2464   return {{info_print_options_defs}, opts};
2465 }
2466 
2467 /* Command completer for 'info locals' and 'info args'.  */
2468 
2469 static void
info_print_command_completer(struct cmd_list_element * ignore,completion_tracker & tracker,const char * text,const char *)2470 info_print_command_completer (struct cmd_list_element *ignore,
2471 			      completion_tracker &tracker,
2472 			      const char *text, const char * /* word */)
2473 {
2474   const auto group
2475     = make_info_print_options_def_group (nullptr);
2476   if (gdb::option::complete_options
2477       (tracker, &text, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, group))
2478     return;
2479 
2480   const char *word = advance_to_expression_complete_word_point (tracker, text);
2481   symbol_completer (ignore, tracker, text, word);
2482 }
2483 
2484 /* Implement the 'info locals' command.  */
2485 
2486 void
info_locals_command(const char * args,int from_tty)2487 info_locals_command (const char *args, int from_tty)
2488 {
2489   info_print_options opts;
2490   auto grp = make_info_print_options_def_group (&opts);
2491   gdb::option::process_options
2492     (&args, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, grp);
2493   if (args != nullptr && *args == '\0')
2494     args = nullptr;
2495 
2496   print_frame_local_vars (get_selected_frame (_("No frame selected.")),
2497 			  opts.quiet, args, opts.type_regexp,
2498 			  0, gdb_stdout);
2499 }
2500 
2501 /* Iterate over all the argument variables in block B.  */
2502 
2503 void
iterate_over_block_arg_vars(const struct block * b,iterate_over_block_arg_local_vars_cb cb,void * cb_data)2504 iterate_over_block_arg_vars (const struct block *b,
2505 			     iterate_over_block_arg_local_vars_cb cb,
2506 			     void *cb_data)
2507 {
2508   struct block_iterator iter;
2509   struct symbol *sym, *sym2;
2510 
2511   ALL_BLOCK_SYMBOLS (b, iter, sym)
2512     {
2513       /* Don't worry about things which aren't arguments.  */
2514       if (SYMBOL_IS_ARGUMENT (sym))
2515 	{
2516 	  /* We have to look up the symbol because arguments can have
2517 	     two entries (one a parameter, one a local) and the one we
2518 	     want is the local, which lookup_symbol will find for us.
2519 	     This includes gcc1 (not gcc2) on the sparc when passing a
2520 	     small structure and gcc2 when the argument type is float
2521 	     and it is passed as a double and converted to float by
2522 	     the prologue (in the latter case the type of the LOC_ARG
2523 	     symbol is double and the type of the LOC_LOCAL symbol is
2524 	     float).  There are also LOC_ARG/LOC_REGISTER pairs which
2525 	     are not combined in symbol-reading.  */
2526 
2527 	  sym2 = lookup_symbol_search_name (sym->search_name (),
2528 					    b, VAR_DOMAIN).symbol;
2529 	  (*cb) (sym->print_name (), sym2, cb_data);
2530 	}
2531     }
2532 }
2533 
2534 /* Print all argument variables of the function of FRAME.
2535    Print them with values to STREAM.
2536    If REGEXP is not NULL, only print argument variables whose name
2537    matches REGEXP.
2538    If T_REGEXP is not NULL, only print argument variables whose type
2539    matches T_REGEXP.
2540    If no argument variables have been printed and !QUIET, prints a message
2541    explaining why no argument variables could be printed.
2542 
2543    This function will invalidate FRAME.  */
2544 
2545 static void
print_frame_arg_vars(struct frame_info * frame,bool quiet,const char * regexp,const char * t_regexp,struct ui_file * stream)2546 print_frame_arg_vars (struct frame_info *frame,
2547 		      bool quiet,
2548 		      const char *regexp, const char *t_regexp,
2549 		      struct ui_file *stream)
2550 {
2551   struct print_variable_and_value_data cb_data;
2552   struct symbol *func;
2553   CORE_ADDR pc;
2554   gdb::optional<compiled_regex> preg;
2555   gdb::optional<compiled_regex> treg;
2556 
2557   if (!get_frame_pc_if_available (frame, &pc))
2558     {
2559       if (!quiet)
2560 	fprintf_filtered (stream,
2561 			  _("PC unavailable, cannot determine args.\n"));
2562       return;
2563     }
2564 
2565   func = get_frame_function (frame);
2566   if (func == NULL)
2567     {
2568       if (!quiet)
2569 	fprintf_filtered (stream, _("No symbol table info available.\n"));
2570       return;
2571     }
2572 
2573   prepare_reg (regexp, &cb_data.preg);
2574   prepare_reg (t_regexp, &cb_data.treg);
2575   cb_data.frame_id = get_frame_id (frame);
2576   cb_data.num_tabs = 0;
2577   cb_data.stream = stream;
2578   cb_data.values_printed = 0;
2579 
2580   iterate_over_block_arg_vars (SYMBOL_BLOCK_VALUE (func),
2581 			       do_print_variable_and_value, &cb_data);
2582 
2583   /* do_print_variable_and_value invalidates FRAME.  */
2584   frame = NULL;
2585 
2586   if (!cb_data.values_printed && !quiet)
2587     {
2588       if (regexp == NULL && t_regexp == NULL)
2589 	fprintf_filtered (stream, _("No arguments.\n"));
2590       else
2591 	fprintf_filtered (stream, _("No matching arguments.\n"));
2592     }
2593 }
2594 
2595 /* Implement the 'info args' command.  */
2596 
2597 void
info_args_command(const char * args,int from_tty)2598 info_args_command (const char *args, int from_tty)
2599 {
2600   info_print_options opts;
2601   auto grp = make_info_print_options_def_group (&opts);
2602   gdb::option::process_options
2603     (&args, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, grp);
2604   if (args != nullptr && *args == '\0')
2605     args = nullptr;
2606 
2607   print_frame_arg_vars (get_selected_frame (_("No frame selected.")),
2608 			opts.quiet, args, opts.type_regexp, gdb_stdout);
2609 }
2610 
2611 /* Return the symbol-block in which the selected frame is executing.
2612    Can return zero under various legitimate circumstances.
2613 
2614    If ADDR_IN_BLOCK is non-zero, set *ADDR_IN_BLOCK to the relevant
2615    code address within the block returned.  We use this to decide
2616    which macros are in scope.  */
2617 
2618 const struct block *
get_selected_block(CORE_ADDR * addr_in_block)2619 get_selected_block (CORE_ADDR *addr_in_block)
2620 {
2621   if (!has_stack_frames ())
2622     return 0;
2623 
2624   return get_frame_block (get_selected_frame (NULL), addr_in_block);
2625 }
2626 
2627 /* Find a frame a certain number of levels away from FRAME.
2628    LEVEL_OFFSET_PTR points to an int containing the number of levels.
2629    Positive means go to earlier frames (up); negative, the reverse.
2630    The int that contains the number of levels is counted toward
2631    zero as the frames for those levels are found.
2632    If the top or bottom frame is reached, that frame is returned,
2633    but the final value of *LEVEL_OFFSET_PTR is nonzero and indicates
2634    how much farther the original request asked to go.  */
2635 
2636 struct frame_info *
find_relative_frame(struct frame_info * frame,int * level_offset_ptr)2637 find_relative_frame (struct frame_info *frame, int *level_offset_ptr)
2638 {
2639   /* Going up is simple: just call get_prev_frame enough times or
2640      until the initial frame is reached.  */
2641   while (*level_offset_ptr > 0)
2642     {
2643       struct frame_info *prev = get_prev_frame (frame);
2644 
2645       if (!prev)
2646 	break;
2647       (*level_offset_ptr)--;
2648       frame = prev;
2649     }
2650 
2651   /* Going down is just as simple.  */
2652   while (*level_offset_ptr < 0)
2653     {
2654       struct frame_info *next = get_next_frame (frame);
2655 
2656       if (!next)
2657 	break;
2658       (*level_offset_ptr)++;
2659       frame = next;
2660     }
2661 
2662   return frame;
2663 }
2664 
2665 /* Select the frame up one or COUNT_EXP stack levels from the
2666    previously selected frame, and print it briefly.  */
2667 
2668 static void
up_silently_base(const char * count_exp)2669 up_silently_base (const char *count_exp)
2670 {
2671   struct frame_info *frame;
2672   int count = 1;
2673 
2674   if (count_exp)
2675     count = parse_and_eval_long (count_exp);
2676 
2677   frame = find_relative_frame (get_selected_frame ("No stack."), &count);
2678   if (count != 0 && count_exp == NULL)
2679     error (_("Initial frame selected; you cannot go up."));
2680   select_frame (frame);
2681 }
2682 
2683 static void
up_silently_command(const char * count_exp,int from_tty)2684 up_silently_command (const char *count_exp, int from_tty)
2685 {
2686   up_silently_base (count_exp);
2687 }
2688 
2689 static void
up_command(const char * count_exp,int from_tty)2690 up_command (const char *count_exp, int from_tty)
2691 {
2692   up_silently_base (count_exp);
2693   gdb::observers::user_selected_context_changed.notify (USER_SELECTED_FRAME);
2694 }
2695 
2696 /* Select the frame down one or COUNT_EXP stack levels from the previously
2697    selected frame, and print it briefly.  */
2698 
2699 static void
down_silently_base(const char * count_exp)2700 down_silently_base (const char *count_exp)
2701 {
2702   struct frame_info *frame;
2703   int count = -1;
2704 
2705   if (count_exp)
2706     count = -parse_and_eval_long (count_exp);
2707 
2708   frame = find_relative_frame (get_selected_frame ("No stack."), &count);
2709   if (count != 0 && count_exp == NULL)
2710     {
2711       /* We only do this if COUNT_EXP is not specified.  That way
2712 	 "down" means to really go down (and let me know if that is
2713 	 impossible), but "down 9999" can be used to mean go all the
2714 	 way down without getting an error.  */
2715 
2716       error (_("Bottom (innermost) frame selected; you cannot go down."));
2717     }
2718 
2719   select_frame (frame);
2720 }
2721 
2722 static void
down_silently_command(const char * count_exp,int from_tty)2723 down_silently_command (const char *count_exp, int from_tty)
2724 {
2725   down_silently_base (count_exp);
2726 }
2727 
2728 static void
down_command(const char * count_exp,int from_tty)2729 down_command (const char *count_exp, int from_tty)
2730 {
2731   down_silently_base (count_exp);
2732   gdb::observers::user_selected_context_changed.notify (USER_SELECTED_FRAME);
2733 }
2734 
2735 void
return_command(const char * retval_exp,int from_tty)2736 return_command (const char *retval_exp, int from_tty)
2737 {
2738   /* Initialize it just to avoid a GCC false warning.  */
2739   enum return_value_convention rv_conv = RETURN_VALUE_STRUCT_CONVENTION;
2740   struct frame_info *thisframe;
2741   struct gdbarch *gdbarch;
2742   struct symbol *thisfun;
2743   struct value *return_value = NULL;
2744   struct value *function = NULL;
2745   const char *query_prefix = "";
2746 
2747   thisframe = get_selected_frame ("No selected frame.");
2748   thisfun = get_frame_function (thisframe);
2749   gdbarch = get_frame_arch (thisframe);
2750 
2751   if (get_frame_type (get_current_frame ()) == INLINE_FRAME)
2752     error (_("Can not force return from an inlined function."));
2753 
2754   /* Compute the return value.  If the computation triggers an error,
2755      let it bail.  If the return type can't be handled, set
2756      RETURN_VALUE to NULL, and QUERY_PREFIX to an informational
2757      message.  */
2758   if (retval_exp)
2759     {
2760       expression_up retval_expr = parse_expression (retval_exp);
2761       struct type *return_type = NULL;
2762 
2763       /* Compute the return value.  Should the computation fail, this
2764 	 call throws an error.  */
2765       return_value = evaluate_expression (retval_expr.get ());
2766 
2767       /* Cast return value to the return type of the function.  Should
2768 	 the cast fail, this call throws an error.  */
2769       if (thisfun != NULL)
2770 	return_type = TYPE_TARGET_TYPE (SYMBOL_TYPE (thisfun));
2771       if (return_type == NULL)
2772 	{
2773 	  if (retval_expr->first_opcode () != UNOP_CAST
2774 	      && retval_expr->first_opcode () != UNOP_CAST_TYPE)
2775 	    error (_("Return value type not available for selected "
2776 		     "stack frame.\n"
2777 		     "Please use an explicit cast of the value to return."));
2778 	  return_type = value_type (return_value);
2779 	}
2780       return_type = check_typedef (return_type);
2781       return_value = value_cast (return_type, return_value);
2782 
2783       /* Make sure the value is fully evaluated.  It may live in the
2784 	 stack frame we're about to pop.  */
2785       if (value_lazy (return_value))
2786 	value_fetch_lazy (return_value);
2787 
2788       if (thisfun != NULL)
2789 	function = read_var_value (thisfun, NULL, thisframe);
2790 
2791       rv_conv = RETURN_VALUE_REGISTER_CONVENTION;
2792       if (return_type->code () == TYPE_CODE_VOID)
2793 	/* If the return-type is "void", don't try to find the
2794 	   return-value's location.  However, do still evaluate the
2795 	   return expression so that, even when the expression result
2796 	   is discarded, side effects such as "return i++" still
2797 	   occur.  */
2798 	return_value = NULL;
2799       else if (thisfun != NULL)
2800 	{
2801 	  rv_conv = struct_return_convention (gdbarch, function, return_type);
2802 	  if (rv_conv == RETURN_VALUE_STRUCT_CONVENTION
2803 	      || rv_conv == RETURN_VALUE_ABI_RETURNS_ADDRESS)
2804 	    {
2805 	      query_prefix = "The location at which to store the "
2806 		"function's return value is unknown.\n"
2807 		"If you continue, the return value "
2808 		"that you specified will be ignored.\n";
2809 	      return_value = NULL;
2810 	    }
2811 	}
2812     }
2813 
2814   /* Does an interactive user really want to do this?  Include
2815      information, such as how well GDB can handle the return value, in
2816      the query message.  */
2817   if (from_tty)
2818     {
2819       int confirmed;
2820 
2821       if (thisfun == NULL)
2822 	confirmed = query (_("%sMake selected stack frame return now? "),
2823 			   query_prefix);
2824       else
2825 	{
2826 	  if (TYPE_NO_RETURN (thisfun->type))
2827 	    warning (_("Function does not return normally to caller."));
2828 	  confirmed = query (_("%sMake %s return now? "), query_prefix,
2829 			     thisfun->print_name ());
2830 	}
2831       if (!confirmed)
2832 	error (_("Not confirmed"));
2833     }
2834 
2835   /* Discard the selected frame and all frames inner-to it.  */
2836   frame_pop (get_selected_frame (NULL));
2837 
2838   /* Store RETURN_VALUE in the just-returned register set.  */
2839   if (return_value != NULL)
2840     {
2841       struct type *return_type = value_type (return_value);
2842       struct gdbarch *cache_arch = get_current_regcache ()->arch ();
2843 
2844       gdb_assert (rv_conv != RETURN_VALUE_STRUCT_CONVENTION
2845 		  && rv_conv != RETURN_VALUE_ABI_RETURNS_ADDRESS);
2846       gdbarch_return_value (cache_arch, function, return_type,
2847 			    get_current_regcache (), NULL /*read*/,
2848 			    value_contents (return_value) /*write*/);
2849     }
2850 
2851   /* If we are at the end of a call dummy now, pop the dummy frame
2852      too.  */
2853   if (get_frame_type (get_current_frame ()) == DUMMY_FRAME)
2854     frame_pop (get_current_frame ());
2855 
2856   select_frame (get_current_frame ());
2857   /* If interactive, print the frame that is now current.  */
2858   if (from_tty)
2859     print_stack_frame (get_selected_frame (NULL), 1, SRC_AND_LOC, 1);
2860 }
2861 
2862 /* Find the most inner frame in the current stack for a function called
2863    FUNCTION_NAME.  If no matching frame is found return NULL.  */
2864 
2865 static struct frame_info *
find_frame_for_function(const char * function_name)2866 find_frame_for_function (const char *function_name)
2867 {
2868   /* Used to hold the lower and upper addresses for each of the
2869      SYMTAB_AND_LINEs found for functions matching FUNCTION_NAME.  */
2870   struct function_bounds
2871   {
2872     CORE_ADDR low, high;
2873   };
2874   struct frame_info *frame;
2875   bool found = false;
2876   int level = 1;
2877 
2878   gdb_assert (function_name != NULL);
2879 
2880   frame = get_current_frame ();
2881   std::vector<symtab_and_line> sals
2882     = decode_line_with_current_source (function_name,
2883 				       DECODE_LINE_FUNFIRSTLINE);
2884   gdb::def_vector<function_bounds> func_bounds (sals.size ());
2885   for (size_t i = 0; i < sals.size (); i++)
2886     {
2887       if (sals[i].pspace != current_program_space)
2888 	func_bounds[i].low = func_bounds[i].high = 0;
2889       else if (sals[i].pc == 0
2890 	       || find_pc_partial_function (sals[i].pc, NULL,
2891 					    &func_bounds[i].low,
2892 					    &func_bounds[i].high) == 0)
2893 	func_bounds[i].low = func_bounds[i].high = 0;
2894     }
2895 
2896   do
2897     {
2898       for (size_t i = 0; (i < sals.size () && !found); i++)
2899 	found = (get_frame_pc (frame) >= func_bounds[i].low
2900 		 && get_frame_pc (frame) < func_bounds[i].high);
2901       if (!found)
2902 	{
2903 	  level = 1;
2904 	  frame = find_relative_frame (frame, &level);
2905 	}
2906     }
2907   while (!found && level == 0);
2908 
2909   if (!found)
2910     frame = NULL;
2911 
2912   return frame;
2913 }
2914 
2915 /* Implements the dbx 'func' command.  */
2916 
2917 static void
func_command(const char * arg,int from_tty)2918 func_command (const char *arg, int from_tty)
2919 {
2920   if (arg == NULL)
2921     return;
2922 
2923   struct frame_info *frame = find_frame_for_function (arg);
2924   if (frame == NULL)
2925     error (_("'%s' not within current stack frame."), arg);
2926   if (frame != get_selected_frame (NULL))
2927     {
2928       select_frame (frame);
2929       print_stack_frame (get_selected_frame (NULL), 1, SRC_AND_LOC, 1);
2930     }
2931 }
2932 
2933 /* The qcs command line flags for the "frame apply" commands.  Keep
2934    this in sync with the "thread apply" commands.  */
2935 
2936 using qcs_flag_option_def
2937   = gdb::option::flag_option_def<qcs_flags>;
2938 
2939 static const gdb::option::option_def fr_qcs_flags_option_defs[] = {
2940   qcs_flag_option_def {
2941     "q", [] (qcs_flags *opt) { return &opt->quiet; },
2942     N_("Disables printing the frame location information."),
2943   },
2944 
2945   qcs_flag_option_def {
2946     "c", [] (qcs_flags *opt) { return &opt->cont; },
2947     N_("Print any error raised by COMMAND and continue."),
2948   },
2949 
2950   qcs_flag_option_def {
2951     "s", [] (qcs_flags *opt) { return &opt->silent; },
2952     N_("Silently ignore any errors or empty output produced by COMMAND."),
2953   },
2954 };
2955 
2956 /* Create an option_def_group array for all the "frame apply" options,
2957    with FLAGS and SET_BT_OPTS as context.  */
2958 
2959 static inline std::array<gdb::option::option_def_group, 2>
make_frame_apply_options_def_group(qcs_flags * flags,set_backtrace_options * set_bt_opts)2960 make_frame_apply_options_def_group (qcs_flags *flags,
2961 				    set_backtrace_options *set_bt_opts)
2962 {
2963   return {{
2964     { {fr_qcs_flags_option_defs}, flags },
2965     { {set_backtrace_option_defs}, set_bt_opts },
2966   }};
2967 }
2968 
2969 /* Apply a GDB command to all stack frames, or a set of identified frames,
2970    or innermost COUNT frames.
2971    With a negative COUNT, apply command on outermost -COUNT frames.
2972 
2973    frame apply 3 info frame     Apply 'info frame' to frames 0, 1, 2
2974    frame apply -3 info frame    Apply 'info frame' to outermost 3 frames.
2975    frame apply all x/i $pc      Apply 'x/i $pc' cmd to all frames.
2976    frame apply all -s p local_var_no_idea_in_which_frame
2977 		If a frame has a local variable called
2978 		local_var_no_idea_in_which_frame, print frame
2979 		and value of local_var_no_idea_in_which_frame.
2980    frame apply all -s -q p local_var_no_idea_in_which_frame
2981 		Same as before, but only print the variable value.
2982    frame apply level 2-5 0 4-7 -s p i = i + 1
2983 		Adds 1 to the variable i in the specified frames.
2984 		Note that i will be incremented twice in
2985 		frames 4 and 5.  */
2986 
2987 /* Apply a GDB command to COUNT stack frames, starting at TRAILING.
2988    CMD starts with 0 or more qcs flags followed by the GDB command to apply.
2989    COUNT -1 means all frames starting at TRAILING.  WHICH_COMMAND is used
2990    for error messages.  */
2991 
2992 static void
frame_apply_command_count(const char * which_command,const char * cmd,int from_tty,struct frame_info * trailing,int count)2993 frame_apply_command_count (const char *which_command,
2994 			   const char *cmd, int from_tty,
2995 			   struct frame_info *trailing, int count)
2996 {
2997   qcs_flags flags;
2998   set_backtrace_options set_bt_opts = user_set_backtrace_options;
2999 
3000   auto group = make_frame_apply_options_def_group (&flags, &set_bt_opts);
3001   gdb::option::process_options
3002     (&cmd, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, group);
3003 
3004   validate_flags_qcs (which_command, &flags);
3005 
3006   if (cmd == NULL || *cmd == '\0')
3007     error (_("Please specify a command to apply on the selected frames"));
3008 
3009   /* The below will restore the current inferior/thread/frame.
3010      Usually, only the frame is effectively to be restored.
3011      But in case CMD switches of inferior/thread, better restore
3012      these also.  */
3013   scoped_restore_current_thread restore_thread;
3014 
3015   /* These options are handled quite deep in the unwind machinery, so
3016      we get to pass them down by swapping globals.  */
3017   scoped_restore restore_set_backtrace_options
3018     = make_scoped_restore (&user_set_backtrace_options, set_bt_opts);
3019 
3020   for (frame_info *fi = trailing; fi && count--; fi = get_prev_frame (fi))
3021     {
3022       QUIT;
3023 
3024       select_frame (fi);
3025       try
3026 	{
3027 	  std::string cmd_result;
3028 	  {
3029 	    /* In case CMD switches of inferior/thread/frame, the below
3030 	       restores the inferior/thread/frame.  FI can then be
3031 	       set to the selected frame.  */
3032 	    scoped_restore_current_thread restore_fi_current_frame;
3033 
3034 	    cmd_result = execute_command_to_string
3035 	      (cmd, from_tty, gdb_stdout->term_out ());
3036 	  }
3037 	  fi = get_selected_frame (_("frame apply "
3038 				     "unable to get selected frame."));
3039 	  if (!flags.silent || cmd_result.length () > 0)
3040 	    {
3041 	      if (!flags.quiet)
3042 		print_stack_frame (fi, 1, LOCATION, 0);
3043 	      printf_filtered ("%s", cmd_result.c_str ());
3044 	    }
3045 	}
3046       catch (const gdb_exception_error &ex)
3047 	{
3048 	  fi = get_selected_frame (_("frame apply "
3049 				     "unable to get selected frame."));
3050 	  if (!flags.silent)
3051 	    {
3052 	      if (!flags.quiet)
3053 		print_stack_frame (fi, 1, LOCATION, 0);
3054 	      if (flags.cont)
3055 		printf_filtered ("%s\n", ex.what ());
3056 	      else
3057 		throw;
3058 	    }
3059 	}
3060     }
3061 }
3062 
3063 /* Completer for the "frame apply ..." commands.  */
3064 
3065 static void
frame_apply_completer(completion_tracker & tracker,const char * text)3066 frame_apply_completer (completion_tracker &tracker, const char *text)
3067 {
3068   const auto group = make_frame_apply_options_def_group (nullptr, nullptr);
3069   if (gdb::option::complete_options
3070       (tracker, &text, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, group))
3071     return;
3072 
3073   complete_nested_command_line (tracker, text);
3074 }
3075 
3076 /* Completer for the "frame apply" commands.  */
3077 
3078 static void
frame_apply_level_cmd_completer(struct cmd_list_element * ignore,completion_tracker & tracker,const char * text,const char *)3079 frame_apply_level_cmd_completer (struct cmd_list_element *ignore,
3080 				 completion_tracker &tracker,
3081 				 const char *text, const char */*word*/)
3082 {
3083   /* Do this explicitly because there's an early return below.  */
3084   tracker.set_use_custom_word_point (true);
3085 
3086   number_or_range_parser levels (text);
3087 
3088   /* Skip the LEVEL list to find the options and command args.  */
3089   try
3090     {
3091       while (!levels.finished ())
3092 	{
3093 	  /* Call for effect.  */
3094 	  levels.get_number ();
3095 
3096 	  if (levels.in_range ())
3097 	    levels.skip_range ();
3098 	}
3099     }
3100   catch (const gdb_exception_error &ex)
3101     {
3102       /* get_number throws if it parses a negative number, for
3103 	 example.  But a seemingly negative number may be the start of
3104 	 an option instead.  */
3105     }
3106 
3107   const char *cmd = levels.cur_tok ();
3108 
3109   if (cmd == text)
3110     {
3111       /* No level list yet.  */
3112       return;
3113     }
3114 
3115   /* Check if we're past a valid LEVEL already.  */
3116   if (levels.finished ()
3117       && cmd > text && !isspace (cmd[-1]))
3118     return;
3119 
3120   /* We're past LEVELs, advance word point.  */
3121   tracker.advance_custom_word_point_by (cmd - text);
3122   text = cmd;
3123 
3124   frame_apply_completer (tracker, text);
3125 }
3126 
3127 /* Completer for the "frame apply all" command.  */
3128 
3129 void
frame_apply_all_cmd_completer(struct cmd_list_element * ignore,completion_tracker & tracker,const char * text,const char *)3130 frame_apply_all_cmd_completer (struct cmd_list_element *ignore,
3131 			       completion_tracker &tracker,
3132 			       const char *text, const char */*word*/)
3133 {
3134   frame_apply_completer (tracker, text);
3135 }
3136 
3137 /* Completer for the "frame apply COUNT" command.  */
3138 
3139 static void
frame_apply_cmd_completer(struct cmd_list_element * ignore,completion_tracker & tracker,const char * text,const char *)3140 frame_apply_cmd_completer (struct cmd_list_element *ignore,
3141 			   completion_tracker &tracker,
3142 			   const char *text, const char */*word*/)
3143 {
3144   const char *cmd = text;
3145 
3146   int count = get_number_trailer (&cmd, 0);
3147   if (count == 0)
3148     return;
3149 
3150   /* Check if we're past a valid COUNT already.  */
3151   if (cmd > text && !isspace (cmd[-1]))
3152     return;
3153 
3154   /* We're past COUNT, advance word point.  */
3155   tracker.advance_custom_word_point_by (cmd - text);
3156   text = cmd;
3157 
3158   frame_apply_completer (tracker, text);
3159 }
3160 
3161 /* Implementation of the "frame apply level" command.  */
3162 
3163 static void
frame_apply_level_command(const char * cmd,int from_tty)3164 frame_apply_level_command (const char *cmd, int from_tty)
3165 {
3166   if (!target_has_stack ())
3167     error (_("No stack."));
3168 
3169   bool level_found = false;
3170   const char *levels_str = cmd;
3171   number_or_range_parser levels (levels_str);
3172 
3173   /* Skip the LEVEL list to find the flags and command args.  */
3174   while (!levels.finished ())
3175     {
3176       /* Call for effect.  */
3177       levels.get_number ();
3178 
3179       level_found = true;
3180       if (levels.in_range ())
3181 	levels.skip_range ();
3182     }
3183 
3184   if (!level_found)
3185     error (_("Missing or invalid LEVEL... argument"));
3186 
3187   cmd = levels.cur_tok ();
3188 
3189   /* Redo the LEVELS parsing, but applying COMMAND.  */
3190   levels.init (levels_str);
3191   while (!levels.finished ())
3192     {
3193       const int level_beg = levels.get_number ();
3194       int n_frames;
3195 
3196       if (levels.in_range ())
3197 	{
3198 	  n_frames = levels.end_value () - level_beg + 1;
3199 	  levels.skip_range ();
3200 	}
3201       else
3202 	n_frames = 1;
3203 
3204       frame_apply_command_count ("frame apply level", cmd, from_tty,
3205 				 leading_innermost_frame (level_beg), n_frames);
3206     }
3207 }
3208 
3209 /* Implementation of the "frame apply all" command.  */
3210 
3211 static void
frame_apply_all_command(const char * cmd,int from_tty)3212 frame_apply_all_command (const char *cmd, int from_tty)
3213 {
3214   if (!target_has_stack ())
3215     error (_("No stack."));
3216 
3217   frame_apply_command_count ("frame apply all", cmd, from_tty,
3218 			     get_current_frame (), INT_MAX);
3219 }
3220 
3221 /* Implementation of the "frame apply" command.  */
3222 
3223 static void
frame_apply_command(const char * cmd,int from_tty)3224 frame_apply_command (const char* cmd, int from_tty)
3225 {
3226   int count;
3227   struct frame_info *trailing;
3228 
3229   if (!target_has_stack ())
3230     error (_("No stack."));
3231 
3232   if (cmd == NULL)
3233     error (_("Missing COUNT argument."));
3234   count = get_number_trailer (&cmd, 0);
3235   if (count == 0)
3236     error (_("Invalid COUNT argument."));
3237 
3238   if (count < 0)
3239     {
3240       trailing = trailing_outermost_frame (-count);
3241       count = -1;
3242     }
3243   else
3244     trailing = get_current_frame ();
3245 
3246   frame_apply_command_count ("frame apply", cmd, from_tty,
3247 			     trailing, count);
3248 }
3249 
3250 /* Implementation of the "faas" command.  */
3251 
3252 static void
faas_command(const char * cmd,int from_tty)3253 faas_command (const char *cmd, int from_tty)
3254 {
3255   if (cmd == NULL || *cmd == '\0')
3256     error (_("Please specify a command to apply on all frames"));
3257   std::string expanded = std::string ("frame apply all -s ") + cmd;
3258   execute_command (expanded.c_str (), from_tty);
3259 }
3260 
3261 
3262 /* Find inner-mode frame with frame address ADDRESS.  Return NULL if no
3263    matching frame can be found.  */
3264 
3265 static struct frame_info *
find_frame_for_address(CORE_ADDR address)3266 find_frame_for_address (CORE_ADDR address)
3267 {
3268   struct frame_id id;
3269   struct frame_info *fid;
3270 
3271   id = frame_id_build_wild (address);
3272 
3273   /* If (s)he specifies the frame with an address, he deserves
3274      what (s)he gets.  Still, give the highest one that matches.
3275      (NOTE: cagney/2004-10-29: Why highest, or outer-most, I don't
3276      know).  */
3277   for (fid = get_current_frame ();
3278        fid != NULL;
3279        fid = get_prev_frame (fid))
3280     {
3281       if (frame_id_eq (id, get_frame_id (fid)))
3282 	{
3283 	  struct frame_info *prev_frame;
3284 
3285 	  while (1)
3286 	    {
3287 	      prev_frame = get_prev_frame (fid);
3288 	      if (!prev_frame
3289 		  || !frame_id_eq (id, get_frame_id (prev_frame)))
3290 		break;
3291 	      fid = prev_frame;
3292 	    }
3293 	  return fid;
3294 	}
3295     }
3296   return NULL;
3297 }
3298 
3299 
3300 
3301 /* Commands with a prefix of `frame apply'.  */
3302 static struct cmd_list_element *frame_apply_cmd_list = NULL;
3303 
3304 /* Commands with a prefix of `frame'.  */
3305 static struct cmd_list_element *frame_cmd_list = NULL;
3306 
3307 /* Commands with a prefix of `select frame'.  */
3308 static struct cmd_list_element *select_frame_cmd_list = NULL;
3309 
3310 /* Commands with a prefix of `info frame'.  */
3311 static struct cmd_list_element *info_frame_cmd_list = NULL;
3312 
3313 void _initialize_stack ();
3314 void
_initialize_stack()3315 _initialize_stack ()
3316 {
3317   struct cmd_list_element *cmd;
3318 
3319   add_com ("return", class_stack, return_command, _("\
3320 Make selected stack frame return to its caller.\n\
3321 Control remains in the debugger, but when you continue\n\
3322 execution will resume in the frame above the one now selected.\n\
3323 If an argument is given, it is an expression for the value to return."));
3324 
3325   add_com ("up", class_stack, up_command, _("\
3326 Select and print stack frame that called this one.\n\
3327 An argument says how many frames up to go."));
3328   add_com ("up-silently", class_support, up_silently_command, _("\
3329 Same as the `up' command, but does not print anything.\n\
3330 This is useful in command scripts."));
3331 
3332   cmd_list_element *down_cmd
3333     = add_com ("down", class_stack, down_command, _("\
3334 Select and print stack frame called by this one.\n\
3335 An argument says how many frames down to go."));
3336   add_com_alias ("do", down_cmd, class_stack, 1);
3337   add_com_alias ("dow", down_cmd, class_stack, 1);
3338   add_com ("down-silently", class_support, down_silently_command, _("\
3339 Same as the `down' command, but does not print anything.\n\
3340 This is useful in command scripts."));
3341 
3342   cmd_list_element *frame_cmd_el
3343     = add_prefix_cmd ("frame", class_stack,
3344 		      &frame_cmd.base_command, _("\
3345 Select and print a stack frame.\n\
3346 With no argument, print the selected stack frame.  (See also \"info frame\").\n\
3347 A single numerical argument specifies the frame to select."),
3348 		      &frame_cmd_list, 1, &cmdlist);
3349   add_com_alias ("f", frame_cmd_el, class_stack, 1);
3350 
3351 #define FRAME_APPLY_OPTION_HELP "\
3352 Prints the frame location information followed by COMMAND output.\n\
3353 \n\
3354 By default, an error raised during the execution of COMMAND\n\
3355 aborts \"frame apply\".\n\
3356 \n\
3357 Options:\n\
3358 %OPTIONS%"
3359 
3360   const auto frame_apply_opts
3361     = make_frame_apply_options_def_group (nullptr, nullptr);
3362 
3363   static std::string frame_apply_cmd_help = gdb::option::build_help (_("\
3364 Apply a command to a number of frames.\n\
3365 Usage: frame apply COUNT [OPTION]... COMMAND\n\
3366 With a negative COUNT argument, applies the command on outermost -COUNT frames.\n"
3367 				  FRAME_APPLY_OPTION_HELP),
3368 			       frame_apply_opts);
3369 
3370   cmd = add_prefix_cmd ("apply", class_stack, frame_apply_command,
3371 			frame_apply_cmd_help.c_str (),
3372 			&frame_apply_cmd_list, 1,
3373 			&frame_cmd_list);
3374   set_cmd_completer_handle_brkchars (cmd, frame_apply_cmd_completer);
3375 
3376   static std::string frame_apply_all_cmd_help = gdb::option::build_help (_("\
3377 Apply a command to all frames.\n\
3378 \n\
3379 Usage: frame apply all [OPTION]... COMMAND\n"
3380 				  FRAME_APPLY_OPTION_HELP),
3381 			       frame_apply_opts);
3382 
3383   cmd = add_cmd ("all", class_stack, frame_apply_all_command,
3384 		 frame_apply_all_cmd_help.c_str (),
3385 		 &frame_apply_cmd_list);
3386   set_cmd_completer_handle_brkchars (cmd, frame_apply_all_cmd_completer);
3387 
3388   static std::string frame_apply_level_cmd_help = gdb::option::build_help (_("\
3389 Apply a command to a list of frames.\n\
3390 \n\
3391 Usage: frame apply level LEVEL... [OPTION]... COMMAND\n\
3392 LEVEL is a space-separated list of levels of frames to apply COMMAND on.\n"
3393 				  FRAME_APPLY_OPTION_HELP),
3394 			       frame_apply_opts);
3395 
3396   cmd = add_cmd ("level", class_stack, frame_apply_level_command,
3397 	   frame_apply_level_cmd_help.c_str (),
3398 	   &frame_apply_cmd_list);
3399   set_cmd_completer_handle_brkchars (cmd, frame_apply_level_cmd_completer);
3400 
3401   cmd = add_com ("faas", class_stack, faas_command, _("\
3402 Apply a command to all frames (ignoring errors and empty output).\n\
3403 Usage: faas [OPTION]... COMMAND\n\
3404 shortcut for 'frame apply all -s [OPTION]... COMMAND'\n\
3405 See \"help frame apply all\" for available options."));
3406   set_cmd_completer_handle_brkchars (cmd, frame_apply_all_cmd_completer);
3407 
3408   add_cmd ("address", class_stack, &frame_cmd.address,
3409 	   _("\
3410 Select and print a stack frame by stack address.\n\
3411 \n\
3412 Usage: frame address STACK-ADDRESS"),
3413 	   &frame_cmd_list);
3414 
3415   add_cmd ("view", class_stack, &frame_cmd.view,
3416 	   _("\
3417 View a stack frame that might be outside the current backtrace.\n\
3418 \n\
3419 Usage: frame view STACK-ADDRESS\n\
3420        frame view STACK-ADDRESS PC-ADDRESS"),
3421 	   &frame_cmd_list);
3422 
3423   cmd = add_cmd ("function", class_stack, &frame_cmd.function,
3424 	   _("\
3425 Select and print a stack frame by function name.\n\
3426 \n\
3427 Usage: frame function NAME\n\
3428 \n\
3429 The innermost frame that visited function NAME is selected."),
3430 	   &frame_cmd_list);
3431   set_cmd_completer (cmd, frame_selection_by_function_completer);
3432 
3433 
3434   add_cmd ("level", class_stack, &frame_cmd.level,
3435 	   _("\
3436 Select and print a stack frame by level.\n\
3437 \n\
3438 Usage: frame level LEVEL"),
3439 	   &frame_cmd_list);
3440 
3441   cmd = add_prefix_cmd_suppress_notification ("select-frame", class_stack,
3442 		      &select_frame_cmd.base_command, _("\
3443 Select a stack frame without printing anything.\n\
3444 A single numerical argument specifies the frame to select."),
3445 		      &select_frame_cmd_list, 1, &cmdlist,
3446 		      &cli_suppress_notification.user_selected_context);
3447 
3448   add_cmd_suppress_notification ("address", class_stack,
3449 			 &select_frame_cmd.address, _("\
3450 Select a stack frame by stack address.\n\
3451 \n\
3452 Usage: select-frame address STACK-ADDRESS"),
3453 			 &select_frame_cmd_list,
3454 			 &cli_suppress_notification.user_selected_context);
3455 
3456 
3457   add_cmd_suppress_notification ("view", class_stack,
3458 		 &select_frame_cmd.view, _("\
3459 Select a stack frame that might be outside the current backtrace.\n\
3460 \n\
3461 Usage: select-frame view STACK-ADDRESS\n\
3462        select-frame view STACK-ADDRESS PC-ADDRESS"),
3463 		 &select_frame_cmd_list,
3464 		 &cli_suppress_notification.user_selected_context);
3465 
3466   cmd = add_cmd_suppress_notification ("function", class_stack,
3467 	       &select_frame_cmd.function, _("\
3468 Select a stack frame by function name.\n\
3469 \n\
3470 Usage: select-frame function NAME"),
3471 	       &select_frame_cmd_list,
3472 	       &cli_suppress_notification.user_selected_context);
3473   set_cmd_completer (cmd, frame_selection_by_function_completer);
3474 
3475   add_cmd_suppress_notification ("level", class_stack,
3476 			 &select_frame_cmd.level, _("\
3477 Select a stack frame by level.\n\
3478 \n\
3479 Usage: select-frame level LEVEL"),
3480 			 &select_frame_cmd_list,
3481 			 &cli_suppress_notification.user_selected_context);
3482 
3483   const auto backtrace_opts
3484     = make_backtrace_options_def_group (nullptr, nullptr, nullptr);
3485 
3486   static std::string backtrace_help
3487     = gdb::option::build_help (_("\
3488 Print backtrace of all stack frames, or innermost COUNT frames.\n\
3489 Usage: backtrace [OPTION]... [QUALIFIER]... [COUNT | -COUNT]\n\
3490 \n\
3491 Options:\n\
3492 %OPTIONS%\n\
3493 \n\
3494 For backward compatibility, the following qualifiers are supported:\n\
3495 \n\
3496    full       - same as -full option.\n\
3497    no-filters - same as -no-filters option.\n\
3498    hide       - same as -hide.\n\
3499 \n\
3500 With a negative COUNT, print outermost -COUNT frames."),
3501 			       backtrace_opts);
3502 
3503   cmd_list_element *backtrace_cmd
3504     = add_com ("backtrace", class_stack, backtrace_command,
3505 	       backtrace_help.c_str ());
3506   set_cmd_completer_handle_brkchars (backtrace_cmd, backtrace_command_completer);
3507 
3508   add_com_alias ("bt", backtrace_cmd, class_stack, 0);
3509 
3510   add_com_alias ("where", backtrace_cmd, class_stack, 0);
3511   cmd_list_element *info_stack_cmd
3512     = add_info ("stack", backtrace_command,
3513 		_("Backtrace of the stack, or innermost COUNT frames."));
3514   add_info_alias ("s", info_stack_cmd, 1);
3515 
3516   cmd_list_element *info_frame_cmd_el
3517     = add_prefix_cmd ("frame", class_info, &info_frame_cmd.base_command,
3518 		      _("All about the selected stack frame.\n\
3519 With no arguments, displays information about the currently selected stack\n\
3520 frame.  Alternatively a frame specification may be provided (See \"frame\")\n\
3521 the information is then printed about the specified frame."),
3522 		      &info_frame_cmd_list, 1, &infolist);
3523   add_info_alias ("f", info_frame_cmd_el, 1);
3524 
3525   add_cmd ("address", class_stack, &info_frame_cmd.address,
3526 	   _("\
3527 Print information about a stack frame selected by stack address.\n\
3528 \n\
3529 Usage: info frame address STACK-ADDRESS"),
3530 	   &info_frame_cmd_list);
3531 
3532   add_cmd ("view", class_stack, &info_frame_cmd.view,
3533 	   _("\
3534 Print information about a stack frame outside the current backtrace.\n\
3535 \n\
3536 Usage: info frame view STACK-ADDRESS\n\
3537        info frame view STACK-ADDRESS PC-ADDRESS"),
3538 	   &info_frame_cmd_list);
3539 
3540   cmd = add_cmd ("function", class_stack, &info_frame_cmd.function,
3541 	   _("\
3542 Print information about a stack frame selected by function name.\n\
3543 \n\
3544 Usage: info frame function NAME"),
3545 	   &info_frame_cmd_list);
3546   set_cmd_completer (cmd, frame_selection_by_function_completer);
3547 
3548   add_cmd ("level", class_stack, &info_frame_cmd.level,
3549 	   _("\
3550 Print information about a stack frame selected by level.\n\
3551 \n\
3552 Usage: info frame level LEVEL"),
3553 	   &info_frame_cmd_list);
3554 
3555   cmd = add_info ("locals", info_locals_command,
3556 		  info_print_args_help (_("\
3557 All local variables of current stack frame or those matching REGEXPs.\n\
3558 Usage: info locals [-q] [-t TYPEREGEXP] [NAMEREGEXP]\n\
3559 Prints the local variables of the current stack frame.\n"),
3560 					_("local variables"),
3561 					false));
3562   set_cmd_completer_handle_brkchars (cmd, info_print_command_completer);
3563   cmd = add_info ("args", info_args_command,
3564 		  info_print_args_help (_("\
3565 All argument variables of current stack frame or those matching REGEXPs.\n\
3566 Usage: info args [-q] [-t TYPEREGEXP] [NAMEREGEXP]\n\
3567 Prints the argument variables of the current stack frame.\n"),
3568 					_("argument variables"),
3569 					false));
3570   set_cmd_completer_handle_brkchars (cmd, info_print_command_completer);
3571 
3572   if (dbx_commands)
3573     add_com ("func", class_stack, func_command, _("\
3574 Select the stack frame that contains NAME.\n\
3575 Usage: func NAME"));
3576 
3577   /* Install "set print raw frame-arguments", a deprecated spelling of
3578      "set print raw-frame-arguments".  */
3579   set_show_commands set_show_frame_args
3580     = add_setshow_boolean_cmd
3581       ("frame-arguments", no_class,
3582        &user_frame_print_options.print_raw_frame_arguments,
3583        _("\
3584 Set whether to print frame arguments in raw form."), _("\
3585 Show whether to print frame arguments in raw form."), _("\
3586 If set, frame arguments are printed in raw form, bypassing any\n\
3587 pretty-printers for that value."),
3588        NULL, NULL,
3589        &setprintrawlist, &showprintrawlist);
3590   deprecate_cmd (set_show_frame_args.set, "set print raw-frame-arguments");
3591 
3592   add_setshow_auto_boolean_cmd ("disassemble-next-line", class_stack,
3593 				&disassemble_next_line, _("\
3594 Set whether to disassemble next source line or insn when execution stops."),
3595 				_("\
3596 Show whether to disassemble next source line or insn when execution stops."),
3597 				_("\
3598 If ON, GDB will display disassembly of the next source line, in addition\n\
3599 to displaying the source line itself.  If the next source line cannot\n\
3600 be displayed (e.g., source is unavailable or there's no line info), GDB\n\
3601 will display disassembly of next instruction instead of showing the\n\
3602 source line.\n\
3603 If AUTO, display disassembly of next instruction only if the source line\n\
3604 cannot be displayed.\n\
3605 If OFF (which is the default), never display the disassembly of the next\n\
3606 source line."),
3607 				NULL,
3608 				show_disassemble_next_line,
3609 				&setlist, &showlist);
3610   disassemble_next_line = AUTO_BOOLEAN_FALSE;
3611 
3612   gdb::option::add_setshow_cmds_for_options
3613     (class_stack, &user_frame_print_options,
3614      frame_print_option_defs, &setprintlist, &showprintlist);
3615 }
3616