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