c072a2ef4cc503a3932101d56063746fe0ee867e
[external/binutils.git] / gdb / stack.c
1 /* Print and select stack frames for GDB, the GNU debugger.
2
3    Copyright (C) 1986-2013 Free Software Foundation, Inc.
4
5    This file is part of GDB.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19
20 #include "defs.h"
21 #include "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 "exceptions.h"
40 #include "reggroups.h"
41 #include "regcache.h"
42 #include "solib.h"
43 #include "valprint.h"
44 #include "gdbthread.h"
45 #include "cp-support.h"
46 #include "disasm.h"
47 #include "inline-frame.h"
48 #include "linespec.h"
49 #include "cli/cli-utils.h"
50
51 #include "gdb_assert.h"
52 #include <ctype.h>
53 #include "gdb_string.h"
54
55 #include "psymtab.h"
56 #include "symfile.h"
57
58 void (*deprecated_selected_frame_level_changed_hook) (int);
59
60 /* The possible choices of "set print frame-arguments", and the value
61    of this setting.  */
62
63 static const char *const print_frame_arguments_choices[] =
64   {"all", "scalars", "none", NULL};
65 static const char *print_frame_arguments = "scalars";
66
67 /* The possible choices of "set print entry-values", and the value
68    of this setting.  */
69
70 const char print_entry_values_no[] = "no";
71 const char print_entry_values_only[] = "only";
72 const char print_entry_values_preferred[] = "preferred";
73 const char print_entry_values_if_needed[] = "if-needed";
74 const char print_entry_values_both[] = "both";
75 const char print_entry_values_compact[] = "compact";
76 const char print_entry_values_default[] = "default";
77 static const char *const print_entry_values_choices[] =
78 {
79   print_entry_values_no,
80   print_entry_values_only,
81   print_entry_values_preferred,
82   print_entry_values_if_needed,
83   print_entry_values_both,
84   print_entry_values_compact,
85   print_entry_values_default,
86   NULL
87 };
88 const char *print_entry_values = print_entry_values_default;
89
90 /* Prototypes for local functions.  */
91
92 static void print_frame_local_vars (struct frame_info *, int,
93                                     struct ui_file *);
94
95 static void print_frame (struct frame_info *frame, int print_level,
96                          enum print_what print_what,  int print_args,
97                          struct symtab_and_line sal);
98
99 static void set_last_displayed_sal (int valid,
100                                     struct program_space *pspace,
101                                     CORE_ADDR addr,
102                                     struct symtab *symtab,
103                                     int line);
104
105 /* Zero means do things normally; we are interacting directly with the
106    user.  One means print the full filename and linenumber when a
107    frame is printed, and do so in a format emacs18/emacs19.22 can
108    parse.  Two means print similar annotations, but in many more
109    cases and in a slightly different syntax.  */
110
111 int annotation_level = 0;
112
113 /* These variables hold the last symtab and line we displayed to the user.
114  * This is where we insert a breakpoint or a skiplist entry by default.  */
115 static int last_displayed_sal_valid = 0;
116 static struct program_space *last_displayed_pspace = 0;
117 static CORE_ADDR last_displayed_addr = 0;
118 static struct symtab *last_displayed_symtab = 0;
119 static int last_displayed_line = 0;
120 \f
121
122 /* Return 1 if we should display the address in addition to the location,
123    because we are in the middle of a statement.  */
124
125 static int
126 frame_show_address (struct frame_info *frame,
127                     struct symtab_and_line sal)
128 {
129   /* If there is a line number, but no PC, then there is no location
130      information associated with this sal.  The only way that should
131      happen is for the call sites of inlined functions (SAL comes from
132      find_frame_sal).  Otherwise, we would have some PC range if the
133      SAL came from a line table.  */
134   if (sal.line != 0 && sal.pc == 0 && sal.end == 0)
135     {
136       if (get_next_frame (frame) == NULL)
137         gdb_assert (inline_skipped_frames (inferior_ptid) > 0);
138       else
139         gdb_assert (get_frame_type (get_next_frame (frame)) == INLINE_FRAME);
140       return 0;
141     }
142
143   return get_frame_pc (frame) != sal.pc;
144 }
145
146 /* Show or print a stack frame FRAME briefly.  The output is format
147    according to PRINT_LEVEL and PRINT_WHAT printing the frame's
148    relative level, function name, argument list, and file name and
149    line number.  If the frame's PC is not at the beginning of the
150    source line, the actual PC is printed at the beginning.  */
151
152 void
153 print_stack_frame (struct frame_info *frame, int print_level,
154                    enum print_what print_what)
155 {
156   volatile struct gdb_exception e;
157
158   /* For mi, alway print location and address.  */
159   if (ui_out_is_mi_like_p (current_uiout))
160     print_what = LOC_AND_ADDRESS;
161
162   TRY_CATCH (e, RETURN_MASK_ERROR)
163     {
164       int center = (print_what == SRC_LINE || print_what == SRC_AND_LOC);
165
166       print_frame_info (frame, print_level, print_what, 1 /* print_args */);
167       set_current_sal_from_frame (frame, center);
168     }
169 }
170
171 /* Print nameless arguments of frame FRAME on STREAM, where START is
172    the offset of the first nameless argument, and NUM is the number of
173    nameless arguments to print.  FIRST is nonzero if this is the first
174    argument (not just the first nameless argument).  */
175
176 static void
177 print_frame_nameless_args (struct frame_info *frame, long start, int num,
178                            int first, struct ui_file *stream)
179 {
180   struct gdbarch *gdbarch = get_frame_arch (frame);
181   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
182   int i;
183   CORE_ADDR argsaddr;
184   long arg_value;
185
186   for (i = 0; i < num; i++)
187     {
188       QUIT;
189       argsaddr = get_frame_args_address (frame);
190       if (!argsaddr)
191         return;
192       arg_value = read_memory_integer (argsaddr + start,
193                                        sizeof (int), byte_order);
194       if (!first)
195         fprintf_filtered (stream, ", ");
196       fprintf_filtered (stream, "%ld", arg_value);
197       first = 0;
198       start += sizeof (int);
199     }
200 }
201
202 /* Print single argument of inferior function.  ARG must be already
203    read in.
204
205    Errors are printed as if they would be the parameter value.  Use zeroed ARG
206    iff it should not be printed accoring to user settings.  */
207
208 static void
209 print_frame_arg (const struct frame_arg *arg)
210 {
211   struct ui_out *uiout = current_uiout;
212   volatile struct gdb_exception except;
213   struct cleanup *old_chain;
214   struct ui_file *stb;
215
216   stb = mem_fileopen ();
217   old_chain = make_cleanup_ui_file_delete (stb);
218
219   gdb_assert (!arg->val || !arg->error);
220   gdb_assert (arg->entry_kind == print_entry_values_no
221               || arg->entry_kind == print_entry_values_only
222               || (!ui_out_is_mi_like_p (uiout)
223                   && arg->entry_kind == print_entry_values_compact));
224
225   annotate_arg_begin ();
226
227   make_cleanup_ui_out_tuple_begin_end (uiout, NULL);
228   fprintf_symbol_filtered (stb, SYMBOL_PRINT_NAME (arg->sym),
229                            SYMBOL_LANGUAGE (arg->sym), DMGL_PARAMS | DMGL_ANSI);
230   if (arg->entry_kind == print_entry_values_compact)
231     {
232       /* It is OK to provide invalid MI-like stream as with
233          PRINT_ENTRY_VALUE_COMPACT we never use MI.  */
234       fputs_filtered ("=", stb);
235
236       fprintf_symbol_filtered (stb, SYMBOL_PRINT_NAME (arg->sym),
237                                SYMBOL_LANGUAGE (arg->sym),
238                                DMGL_PARAMS | DMGL_ANSI);
239     }
240   if (arg->entry_kind == print_entry_values_only
241       || arg->entry_kind == print_entry_values_compact)
242     fputs_filtered ("@entry", stb);
243   ui_out_field_stream (uiout, "name", stb);
244   annotate_arg_name_end ();
245   ui_out_text (uiout, "=");
246
247   if (!arg->val && !arg->error)
248     ui_out_text (uiout, "...");
249   else
250     {
251       if (arg->error)
252         except.message = arg->error;
253       else
254         {
255           /* TRY_CATCH has two statements, wrap it in a block.  */
256
257           TRY_CATCH (except, RETURN_MASK_ERROR)
258             {
259               const struct language_defn *language;
260               struct value_print_options opts;
261
262               /* Avoid value_print because it will deref ref parameters.  We
263                  just want to print their addresses.  Print ??? for args whose
264                  address we do not know.  We pass 2 as "recurse" to val_print
265                  because our standard indentation here is 4 spaces, and
266                  val_print indents 2 for each recurse.  */ 
267
268               annotate_arg_value (value_type (arg->val));
269
270               /* Use the appropriate language to display our symbol, unless the
271                  user forced the language to a specific language.  */
272               if (language_mode == language_mode_auto)
273                 language = language_def (SYMBOL_LANGUAGE (arg->sym));
274               else
275                 language = current_language;
276
277               get_raw_print_options (&opts);
278               opts.deref_ref = 1;
279
280               /* True in "summary" mode, false otherwise.  */
281               opts.summary = !strcmp (print_frame_arguments, "scalars");
282
283               common_val_print (arg->val, stb, 2, &opts, language);
284             }
285         }
286       if (except.message)
287         fprintf_filtered (stb, _("<error reading variable: %s>"),
288                           except.message);
289     }
290
291   ui_out_field_stream (uiout, "value", stb);
292
293   /* Also invoke ui_out_tuple_end.  */
294   do_cleanups (old_chain);
295
296   annotate_arg_end ();
297 }
298
299 /* Read in inferior function parameter SYM at FRAME into ARGP.  Caller is
300    responsible for xfree of ARGP->ERROR.  This function never throws an
301    exception.  */
302
303 void
304 read_frame_arg (struct symbol *sym, struct frame_info *frame,
305                 struct frame_arg *argp, struct frame_arg *entryargp)
306 {
307   struct value *val = NULL, *entryval = NULL;
308   char *val_error = NULL, *entryval_error = NULL;
309   int val_equal = 0;
310   volatile struct gdb_exception except;
311
312   if (print_entry_values != print_entry_values_only
313       && print_entry_values != print_entry_values_preferred)
314     {
315       TRY_CATCH (except, RETURN_MASK_ERROR)
316         {
317           val = read_var_value (sym, frame);
318         }
319       if (!val)
320         {
321           val_error = alloca (strlen (except.message) + 1);
322           strcpy (val_error, except.message);
323         }
324     }
325
326   if (SYMBOL_COMPUTED_OPS (sym) != NULL
327       && SYMBOL_COMPUTED_OPS (sym)->read_variable_at_entry != NULL
328       && print_entry_values != print_entry_values_no
329       && (print_entry_values != print_entry_values_if_needed
330           || !val || value_optimized_out (val)))
331     {
332       TRY_CATCH (except, RETURN_MASK_ERROR)
333         {
334           const struct symbol_computed_ops *ops;
335
336           ops = SYMBOL_COMPUTED_OPS (sym);
337           entryval = ops->read_variable_at_entry (sym, frame);
338         }
339       if (!entryval)
340         {
341           entryval_error = alloca (strlen (except.message) + 1);
342           strcpy (entryval_error, except.message);
343         }
344
345       if (except.error == NO_ENTRY_VALUE_ERROR
346           || (entryval && value_optimized_out (entryval)))
347         {
348           entryval = NULL;
349           entryval_error = NULL;
350         }
351
352       if (print_entry_values == print_entry_values_compact
353           || print_entry_values == print_entry_values_default)
354         {
355           /* For MI do not try to use print_entry_values_compact for ARGP.  */
356
357           if (val && entryval && !ui_out_is_mi_like_p (current_uiout))
358             {
359               struct type *type = value_type (val);
360
361               if (!value_optimized_out (val) && value_lazy (val))
362                 value_fetch_lazy (val);
363               if (!value_optimized_out (val) && value_lazy (entryval))
364                 value_fetch_lazy (entryval);
365               if (!value_optimized_out (val)
366                   && value_available_contents_eq (val, 0, entryval, 0,
367                                                   TYPE_LENGTH (type)))
368                 {
369                   /* Initialize it just to avoid a GCC false warning.  */
370                   struct value *val_deref = NULL, *entryval_deref;
371
372                   /* DW_AT_GNU_call_site_value does match with the current
373                      value.  If it is a reference still try to verify if
374                      dereferenced DW_AT_GNU_call_site_data_value does not
375                      differ.  */
376
377                   TRY_CATCH (except, RETURN_MASK_ERROR)
378                     {
379                       struct type *type_deref;
380
381                       val_deref = coerce_ref (val);
382                       if (value_lazy (val_deref))
383                         value_fetch_lazy (val_deref);
384                       type_deref = value_type (val_deref);
385
386                       entryval_deref = coerce_ref (entryval);
387                       if (value_lazy (entryval_deref))
388                         value_fetch_lazy (entryval_deref);
389
390                       /* If the reference addresses match but dereferenced
391                          content does not match print them.  */
392                       if (val != val_deref
393                           && value_available_contents_eq (val_deref, 0,
394                                                           entryval_deref, 0,
395                                                       TYPE_LENGTH (type_deref)))
396                         val_equal = 1;
397                     }
398
399                   /* Value was not a reference; and its content matches.  */
400                   if (val == val_deref)
401                     val_equal = 1;
402                   /* If the dereferenced content could not be fetched do not
403                      display anything.  */
404                   else if (except.error == NO_ENTRY_VALUE_ERROR)
405                     val_equal = 1;
406                   else if (except.message)
407                     {
408                       entryval_error = alloca (strlen (except.message) + 1);
409                       strcpy (entryval_error, except.message);
410                     }
411
412                   if (val_equal)
413                     entryval = NULL;
414                 }
415             }
416
417           /* Try to remove possibly duplicate error message for ENTRYARGP even
418              in MI mode.  */
419
420           if (val_error && entryval_error
421               && strcmp (val_error, entryval_error) == 0)
422             {
423               entryval_error = NULL;
424
425               /* Do not se VAL_EQUAL as the same error message may be shown for
426                  the entry value even if no entry values are present in the
427                  inferior.  */
428             }
429         }
430     }
431
432   if (entryval == NULL)
433     {
434       if (print_entry_values == print_entry_values_preferred)
435         {
436           TRY_CATCH (except, RETURN_MASK_ERROR)
437             {
438               val = read_var_value (sym, frame);
439             }
440           if (!val)
441             {
442               val_error = alloca (strlen (except.message) + 1);
443               strcpy (val_error, except.message);
444             }
445         }
446       if (print_entry_values == print_entry_values_only
447           || print_entry_values == print_entry_values_both
448           || (print_entry_values == print_entry_values_preferred
449               && (!val || value_optimized_out (val))))
450         entryval = allocate_optimized_out_value (SYMBOL_TYPE (sym));
451     }
452   if ((print_entry_values == print_entry_values_compact
453        || print_entry_values == print_entry_values_if_needed
454        || print_entry_values == print_entry_values_preferred)
455       && (!val || value_optimized_out (val)) && entryval != NULL)
456     {
457       val = NULL;
458       val_error = NULL;
459     }
460
461   argp->sym = sym;
462   argp->val = val;
463   argp->error = val_error ? xstrdup (val_error) : NULL;
464   if (!val && !val_error)
465     argp->entry_kind = print_entry_values_only;
466   else if ((print_entry_values == print_entry_values_compact
467            || print_entry_values == print_entry_values_default) && val_equal)
468     {
469       argp->entry_kind = print_entry_values_compact;
470       gdb_assert (!ui_out_is_mi_like_p (current_uiout));
471     }
472   else
473     argp->entry_kind = print_entry_values_no;
474
475   entryargp->sym = sym;
476   entryargp->val = entryval;
477   entryargp->error = entryval_error ? xstrdup (entryval_error) : NULL;
478   if (!entryval && !entryval_error)
479     entryargp->entry_kind = print_entry_values_no;
480   else
481     entryargp->entry_kind = print_entry_values_only;
482 }
483
484 /* Print the arguments of frame FRAME on STREAM, given the function
485    FUNC running in that frame (as a symbol), where NUM is the number
486    of arguments according to the stack frame (or -1 if the number of
487    arguments is unknown).  */
488
489 /* Note that currently the "number of arguments according to the
490    stack frame" is only known on VAX where i refers to the "number of
491    ints of arguments according to the stack frame".  */
492
493 static void
494 print_frame_args (struct symbol *func, struct frame_info *frame,
495                   int num, struct ui_file *stream)
496 {
497   struct ui_out *uiout = current_uiout;
498   int first = 1;
499   /* Offset of next stack argument beyond the one we have seen that is
500      at the highest offset, or -1 if we haven't come to a stack
501      argument yet.  */
502   long highest_offset = -1;
503   /* Number of ints of arguments that we have printed so far.  */
504   int args_printed = 0;
505   struct cleanup *old_chain;
506   struct ui_file *stb;
507   /* True if we should print arguments, false otherwise.  */
508   int print_args = strcmp (print_frame_arguments, "none");
509
510   stb = mem_fileopen ();
511   old_chain = make_cleanup_ui_file_delete (stb);
512
513   if (func)
514     {
515       struct block *b = SYMBOL_BLOCK_VALUE (func);
516       struct block_iterator iter;
517       struct symbol *sym;
518
519       ALL_BLOCK_SYMBOLS (b, iter, sym)
520         {
521           struct frame_arg arg, entryarg;
522
523           QUIT;
524
525           /* Keep track of the highest stack argument offset seen, and
526              skip over any kinds of symbols we don't care about.  */
527
528           if (!SYMBOL_IS_ARGUMENT (sym))
529             continue;
530
531           switch (SYMBOL_CLASS (sym))
532             {
533             case LOC_ARG:
534             case LOC_REF_ARG:
535               {
536                 long current_offset = SYMBOL_VALUE (sym);
537                 int arg_size = TYPE_LENGTH (SYMBOL_TYPE (sym));
538
539                 /* Compute address of next argument by adding the size of
540                    this argument and rounding to an int boundary.  */
541                 current_offset =
542                   ((current_offset + arg_size + sizeof (int) - 1)
543                    & ~(sizeof (int) - 1));
544
545                 /* If this is the highest offset seen yet, set
546                    highest_offset.  */
547                 if (highest_offset == -1
548                     || (current_offset > highest_offset))
549                   highest_offset = current_offset;
550
551                 /* Add the number of ints we're about to print to
552                    args_printed.  */
553                 args_printed += (arg_size + sizeof (int) - 1) / sizeof (int);
554               }
555
556               /* We care about types of symbols, but don't need to
557                  keep track of stack offsets in them.  */
558             case LOC_REGISTER:
559             case LOC_REGPARM_ADDR:
560             case LOC_COMPUTED:
561             case LOC_OPTIMIZED_OUT:
562             default:
563               break;
564             }
565
566           /* We have to look up the symbol because arguments can have
567              two entries (one a parameter, one a local) and the one we
568              want is the local, which lookup_symbol will find for us.
569              This includes gcc1 (not gcc2) on SPARC when passing a
570              small structure and gcc2 when the argument type is float
571              and it is passed as a double and converted to float by
572              the prologue (in the latter case the type of the LOC_ARG
573              symbol is double and the type of the LOC_LOCAL symbol is
574              float).  */
575           /* But if the parameter name is null, don't try it.  Null
576              parameter names occur on the RS/6000, for traceback
577              tables.  FIXME, should we even print them?  */
578
579           if (*SYMBOL_LINKAGE_NAME (sym))
580             {
581               struct symbol *nsym;
582
583               nsym = lookup_symbol (SYMBOL_LINKAGE_NAME (sym),
584                                     b, VAR_DOMAIN, NULL);
585               gdb_assert (nsym != NULL);
586               if (SYMBOL_CLASS (nsym) == LOC_REGISTER
587                   && !SYMBOL_IS_ARGUMENT (nsym))
588                 {
589                   /* There is a LOC_ARG/LOC_REGISTER pair.  This means
590                      that it was passed on the stack and loaded into a
591                      register, or passed in a register and stored in a
592                      stack slot.  GDB 3.x used the LOC_ARG; GDB
593                      4.0-4.11 used the LOC_REGISTER.
594
595                      Reasons for using the LOC_ARG:
596
597                      (1) Because find_saved_registers may be slow for
598                          remote debugging.
599
600                      (2) Because registers are often re-used and stack
601                          slots rarely (never?) are.  Therefore using
602                          the stack slot is much less likely to print
603                          garbage.
604
605                      Reasons why we might want to use the LOC_REGISTER:
606
607                      (1) So that the backtrace prints the same value
608                          as "print foo".  I see no compelling reason
609                          why this needs to be the case; having the
610                          backtrace print the value which was passed
611                          in, and "print foo" print the value as
612                          modified within the called function, makes
613                          perfect sense to me.
614
615                      Additional note: It might be nice if "info args"
616                      displayed both values.
617
618                      One more note: There is a case with SPARC
619                      structure passing where we need to use the
620                      LOC_REGISTER, but this is dealt with by creating
621                      a single LOC_REGPARM in symbol reading.  */
622
623                   /* Leave sym (the LOC_ARG) alone.  */
624                   ;
625                 }
626               else
627                 sym = nsym;
628             }
629
630           /* Print the current arg.  */
631           if (!first)
632             ui_out_text (uiout, ", ");
633           ui_out_wrap_hint (uiout, "    ");
634
635           if (!print_args)
636             {
637               memset (&arg, 0, sizeof (arg));
638               arg.sym = sym;
639               arg.entry_kind = print_entry_values_no;
640               memset (&entryarg, 0, sizeof (entryarg));
641               entryarg.sym = sym;
642               entryarg.entry_kind = print_entry_values_no;
643             }
644           else
645             read_frame_arg (sym, frame, &arg, &entryarg);
646
647           if (arg.entry_kind != print_entry_values_only)
648             print_frame_arg (&arg);
649
650           if (entryarg.entry_kind != print_entry_values_no)
651             {
652               if (arg.entry_kind != print_entry_values_only)
653                 {
654                   ui_out_text (uiout, ", ");
655                   ui_out_wrap_hint (uiout, "    ");
656                 }
657
658               print_frame_arg (&entryarg);
659             }
660
661           xfree (arg.error);
662           xfree (entryarg.error);
663
664           first = 0;
665         }
666     }
667
668   /* Don't print nameless args in situations where we don't know
669      enough about the stack to find them.  */
670   if (num != -1)
671     {
672       long start;
673
674       if (highest_offset == -1)
675         start = gdbarch_frame_args_skip (get_frame_arch (frame));
676       else
677         start = highest_offset;
678
679       print_frame_nameless_args (frame, start, num - args_printed,
680                                  first, stream);
681     }
682
683   do_cleanups (old_chain);
684 }
685
686 /* Set the current source and line to the location given by frame
687    FRAME, if possible.  When CENTER is true, adjust so the relevant
688    line is in the center of the next 'list'.  */
689
690 void
691 set_current_sal_from_frame (struct frame_info *frame, int center)
692 {
693   struct symtab_and_line sal;
694
695   find_frame_sal (frame, &sal);
696   if (sal.symtab)
697     {
698       if (center)
699         sal.line = max (sal.line - get_lines_to_list () / 2, 1);
700       set_current_source_symtab_and_line (&sal);
701     }
702 }
703
704 /* If ON, GDB will display disassembly of the next source line when
705    execution of the program being debugged stops.
706    If AUTO (which is the default), or there's no line info to determine
707    the source line of the next instruction, display disassembly of next
708    instruction instead.  */
709
710 static enum auto_boolean disassemble_next_line;
711
712 static void
713 show_disassemble_next_line (struct ui_file *file, int from_tty,
714                                  struct cmd_list_element *c,
715                                  const char *value)
716 {
717   fprintf_filtered (file,
718                     _("Debugger's willingness to use "
719                       "disassemble-next-line is %s.\n"),
720                     value);
721 }
722
723 /* Use TRY_CATCH to catch the exception from the gdb_disassembly
724    because it will be broken by filter sometime.  */
725
726 static void
727 do_gdb_disassembly (struct gdbarch *gdbarch,
728                     int how_many, CORE_ADDR low, CORE_ADDR high)
729 {
730   volatile struct gdb_exception exception;
731
732   TRY_CATCH (exception, RETURN_MASK_ERROR)
733     {
734       gdb_disassembly (gdbarch, current_uiout, 0,
735                        DISASSEMBLY_RAW_INSN, how_many,
736                        low, high);
737     }
738   if (exception.reason < 0)
739     {
740       /* If an exception was thrown while doing the disassembly, print
741          the error message, to give the user a clue of what happened.  */
742       exception_print (gdb_stderr, exception);
743     }
744 }
745
746 /* Print information about frame FRAME.  The output is format according
747    to PRINT_LEVEL and PRINT_WHAT and PRINT_ARGS.  The meaning of
748    PRINT_WHAT is:
749    
750    SRC_LINE: Print only source line.
751    LOCATION: Print only location.
752    LOC_AND_SRC: Print location and source line.
753
754    Used in "where" output, and to emit breakpoint or step
755    messages.  */
756
757 void
758 print_frame_info (struct frame_info *frame, int print_level,
759                   enum print_what print_what, int print_args)
760 {
761   struct gdbarch *gdbarch = get_frame_arch (frame);
762   struct symtab_and_line sal;
763   int source_print;
764   int location_print;
765   struct ui_out *uiout = current_uiout;
766
767   if (get_frame_type (frame) == DUMMY_FRAME
768       || get_frame_type (frame) == SIGTRAMP_FRAME
769       || get_frame_type (frame) == ARCH_FRAME)
770     {
771       struct cleanup *uiout_cleanup
772         = make_cleanup_ui_out_tuple_begin_end (uiout, "frame");
773
774       annotate_frame_begin (print_level ? frame_relative_level (frame) : 0,
775                             gdbarch, get_frame_pc (frame));
776
777       /* Do this regardless of SOURCE because we don't have any source
778          to list for this frame.  */
779       if (print_level)
780         {
781           ui_out_text (uiout, "#");
782           ui_out_field_fmt_int (uiout, 2, ui_left, "level",
783                                 frame_relative_level (frame));
784         }
785       if (ui_out_is_mi_like_p (uiout))
786         {
787           annotate_frame_address ();
788           ui_out_field_core_addr (uiout, "addr",
789                                   gdbarch, get_frame_pc (frame));
790           annotate_frame_address_end ();
791         }
792
793       if (get_frame_type (frame) == DUMMY_FRAME)
794         {
795           annotate_function_call ();
796           ui_out_field_string (uiout, "func", "<function called from gdb>");
797         }
798       else if (get_frame_type (frame) == SIGTRAMP_FRAME)
799         {
800           annotate_signal_handler_caller ();
801           ui_out_field_string (uiout, "func", "<signal handler called>");
802         }
803       else if (get_frame_type (frame) == ARCH_FRAME)
804         {
805           ui_out_field_string (uiout, "func", "<cross-architecture call>");
806         }
807       ui_out_text (uiout, "\n");
808       annotate_frame_end ();
809
810       do_cleanups (uiout_cleanup);
811       return;
812     }
813
814   /* If FRAME is not the innermost frame, that normally means that
815      FRAME->pc points to *after* the call instruction, and we want to
816      get the line containing the call, never the next line.  But if
817      the next frame is a SIGTRAMP_FRAME or a DUMMY_FRAME, then the
818      next frame was not entered as the result of a call, and we want
819      to get the line containing FRAME->pc.  */
820   find_frame_sal (frame, &sal);
821
822   location_print = (print_what == LOCATION 
823                     || print_what == LOC_AND_ADDRESS
824                     || print_what == SRC_AND_LOC);
825
826   if (location_print || !sal.symtab)
827     print_frame (frame, print_level, print_what, print_args, sal);
828
829   source_print = (print_what == SRC_LINE || print_what == SRC_AND_LOC);
830
831   /* If disassemble-next-line is set to auto or on and doesn't have
832      the line debug messages for $pc, output the next instruction.  */
833   if ((disassemble_next_line == AUTO_BOOLEAN_AUTO
834        || disassemble_next_line == AUTO_BOOLEAN_TRUE)
835       && source_print && !sal.symtab)
836     do_gdb_disassembly (get_frame_arch (frame), 1,
837                         get_frame_pc (frame), get_frame_pc (frame) + 1);
838
839   if (source_print && sal.symtab)
840     {
841       int done = 0;
842       int mid_statement = ((print_what == SRC_LINE)
843                            && frame_show_address (frame, sal));
844
845       if (annotation_level)
846         done = identify_source_line (sal.symtab, sal.line, mid_statement,
847                                      get_frame_pc (frame));
848       if (!done)
849         {
850           if (deprecated_print_frame_info_listing_hook)
851             deprecated_print_frame_info_listing_hook (sal.symtab, 
852                                                       sal.line, 
853                                                       sal.line + 1, 0);
854           else
855             {
856               struct value_print_options opts;
857
858               get_user_print_options (&opts);
859               /* We used to do this earlier, but that is clearly
860                  wrong.  This function is used by many different
861                  parts of gdb, including normal_stop in infrun.c,
862                  which uses this to print out the current PC
863                  when we stepi/nexti into the middle of a source
864                  line.  Only the command line really wants this
865                  behavior.  Other UIs probably would like the
866                  ability to decide for themselves if it is desired.  */
867               if (opts.addressprint && mid_statement)
868                 {
869                   ui_out_field_core_addr (uiout, "addr",
870                                           gdbarch, get_frame_pc (frame));
871                   ui_out_text (uiout, "\t");
872                 }
873
874               print_source_lines (sal.symtab, sal.line, sal.line + 1, 0);
875             }
876         }
877
878       /* If disassemble-next-line is set to on and there is line debug
879          messages, output assembly codes for next line.  */
880       if (disassemble_next_line == AUTO_BOOLEAN_TRUE)
881         do_gdb_disassembly (get_frame_arch (frame), -1, sal.pc, sal.end);
882     }
883
884   if (print_what != LOCATION)
885     {
886       CORE_ADDR pc;
887
888       if (get_frame_pc_if_available (frame, &pc))
889         set_last_displayed_sal (1, sal.pspace, pc, sal.symtab, sal.line);
890       else
891         set_last_displayed_sal (0, 0, 0, 0, 0);
892     }
893
894   annotate_frame_end ();
895
896   gdb_flush (gdb_stdout);
897 }
898
899 /* Remember the last symtab and line we displayed, which we use e.g.
900  * as the place to put a breakpoint when the `break' command is
901  * invoked with no arguments.  */
902
903 static void
904 set_last_displayed_sal (int valid, struct program_space *pspace,
905                         CORE_ADDR addr, struct symtab *symtab,
906                         int line)
907 {
908   last_displayed_sal_valid = valid;
909   last_displayed_pspace = pspace;
910   last_displayed_addr = addr;
911   last_displayed_symtab = symtab;
912   last_displayed_line = line;
913   if (valid && pspace == NULL)
914     {
915       clear_last_displayed_sal ();
916       internal_error (__FILE__, __LINE__,
917                       _("Trying to set NULL pspace."));
918     }
919 }
920
921 /* Forget the last sal we displayed.  */
922
923 void
924 clear_last_displayed_sal (void)
925 {
926   last_displayed_sal_valid = 0;
927   last_displayed_pspace = 0;
928   last_displayed_addr = 0;
929   last_displayed_symtab = 0;
930   last_displayed_line = 0;
931 }
932
933 /* Is our record of the last sal we displayed valid?  If not,
934  * the get_last_displayed_* functions will return NULL or 0, as
935  * appropriate.  */
936
937 int
938 last_displayed_sal_is_valid (void)
939 {
940   return last_displayed_sal_valid;
941 }
942
943 /* Get the pspace of the last sal we displayed, if it's valid.  */
944
945 struct program_space *
946 get_last_displayed_pspace (void)
947 {
948   if (last_displayed_sal_valid)
949     return last_displayed_pspace;
950   return 0;
951 }
952
953 /* Get the address of the last sal we displayed, if it's valid.  */
954
955 CORE_ADDR
956 get_last_displayed_addr (void)
957 {
958   if (last_displayed_sal_valid)
959     return last_displayed_addr;
960   return 0;
961 }
962
963 /* Get the symtab of the last sal we displayed, if it's valid.  */
964
965 struct symtab*
966 get_last_displayed_symtab (void)
967 {
968   if (last_displayed_sal_valid)
969     return last_displayed_symtab;
970   return 0;
971 }
972
973 /* Get the line of the last sal we displayed, if it's valid.  */
974
975 int
976 get_last_displayed_line (void)
977 {
978   if (last_displayed_sal_valid)
979     return last_displayed_line;
980   return 0;
981 }
982
983 /* Get the last sal we displayed, if it's valid.  */
984
985 void
986 get_last_displayed_sal (struct symtab_and_line *sal)
987 {
988   if (last_displayed_sal_valid)
989     {
990       sal->pspace = last_displayed_pspace;
991       sal->pc = last_displayed_addr;
992       sal->symtab = last_displayed_symtab;
993       sal->line = last_displayed_line;
994     }
995   else
996     {
997       sal->pspace = 0;
998       sal->pc = 0;
999       sal->symtab = 0;
1000       sal->line = 0;
1001     }
1002 }
1003
1004
1005 /* Attempt to obtain the FUNNAME, FUNLANG and optionally FUNCP of the function
1006    corresponding to FRAME.  */
1007
1008 void
1009 find_frame_funname (struct frame_info *frame, const char **funname,
1010                     enum language *funlang, struct symbol **funcp)
1011 {
1012   struct symbol *func;
1013
1014   *funname = NULL;
1015   *funlang = language_unknown;
1016   if (funcp)
1017     *funcp = NULL;
1018
1019   func = get_frame_function (frame);
1020   if (func)
1021     {
1022       /* In certain pathological cases, the symtabs give the wrong
1023          function (when we are in the first function in a file which
1024          is compiled without debugging symbols, the previous function
1025          is compiled with debugging symbols, and the "foo.o" symbol
1026          that is supposed to tell us where the file with debugging
1027          symbols ends has been truncated by ar because it is longer
1028          than 15 characters).  This also occurs if the user uses asm()
1029          to create a function but not stabs for it (in a file compiled
1030          with -g).
1031
1032          So look in the minimal symbol tables as well, and if it comes
1033          up with a larger address for the function use that instead.
1034          I don't think this can ever cause any problems; there
1035          shouldn't be any minimal symbols in the middle of a function;
1036          if this is ever changed many parts of GDB will need to be
1037          changed (and we'll create a find_pc_minimal_function or some
1038          such).  */
1039
1040       struct bound_minimal_symbol msymbol;
1041
1042       /* Don't attempt to do this for inlined functions, which do not
1043          have a corresponding minimal symbol.  */
1044       if (!block_inlined_p (SYMBOL_BLOCK_VALUE (func)))
1045         msymbol
1046           = lookup_minimal_symbol_by_pc (get_frame_address_in_block (frame));
1047       else
1048         memset (&msymbol, 0, sizeof (msymbol));
1049
1050       if (msymbol.minsym != NULL
1051           && (SYMBOL_VALUE_ADDRESS (msymbol.minsym)
1052               > BLOCK_START (SYMBOL_BLOCK_VALUE (func))))
1053         {
1054           /* We also don't know anything about the function besides
1055              its address and name.  */
1056           func = 0;
1057           *funname = SYMBOL_PRINT_NAME (msymbol.minsym);
1058           *funlang = SYMBOL_LANGUAGE (msymbol.minsym);
1059         }
1060       else
1061         {
1062           *funname = SYMBOL_PRINT_NAME (func);
1063           *funlang = SYMBOL_LANGUAGE (func);
1064           if (funcp)
1065             *funcp = func;
1066           if (*funlang == language_cplus)
1067             {
1068               /* It seems appropriate to use SYMBOL_PRINT_NAME() here,
1069                  to display the demangled name that we already have
1070                  stored in the symbol table, but we stored a version
1071                  with DMGL_PARAMS turned on, and here we don't want to
1072                  display parameters.  So remove the parameters.  */
1073               char *func_only = cp_remove_params (*funname);
1074
1075               if (func_only)
1076                 {
1077                   *funname = func_only;
1078                   make_cleanup (xfree, func_only);
1079                 }
1080             }
1081         }
1082     }
1083   else
1084     {
1085       struct bound_minimal_symbol msymbol;
1086       CORE_ADDR pc;
1087
1088       if (!get_frame_address_in_block_if_available (frame, &pc))
1089         return;
1090
1091       msymbol = lookup_minimal_symbol_by_pc (pc);
1092       if (msymbol.minsym != NULL)
1093         {
1094           *funname = SYMBOL_PRINT_NAME (msymbol.minsym);
1095           *funlang = SYMBOL_LANGUAGE (msymbol.minsym);
1096         }
1097     }
1098 }
1099
1100 static void
1101 print_frame (struct frame_info *frame, int print_level,
1102              enum print_what print_what, int print_args,
1103              struct symtab_and_line sal)
1104 {
1105   struct gdbarch *gdbarch = get_frame_arch (frame);
1106   struct ui_out *uiout = current_uiout;
1107   const char *funname = NULL;
1108   enum language funlang = language_unknown;
1109   struct ui_file *stb;
1110   struct cleanup *old_chain, *list_chain;
1111   struct value_print_options opts;
1112   struct symbol *func;
1113   CORE_ADDR pc = 0;
1114   int pc_p;
1115
1116   pc_p = get_frame_pc_if_available (frame, &pc);
1117
1118   stb = mem_fileopen ();
1119   old_chain = make_cleanup_ui_file_delete (stb);
1120
1121   find_frame_funname (frame, &funname, &funlang, &func);
1122
1123   annotate_frame_begin (print_level ? frame_relative_level (frame) : 0,
1124                         gdbarch, pc);
1125
1126   list_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "frame");
1127
1128   if (print_level)
1129     {
1130       ui_out_text (uiout, "#");
1131       ui_out_field_fmt_int (uiout, 2, ui_left, "level",
1132                             frame_relative_level (frame));
1133     }
1134   get_user_print_options (&opts);
1135   if (opts.addressprint)
1136     if (!sal.symtab
1137         || frame_show_address (frame, sal)
1138         || print_what == LOC_AND_ADDRESS)
1139       {
1140         annotate_frame_address ();
1141         if (pc_p)
1142           ui_out_field_core_addr (uiout, "addr", gdbarch, pc);
1143         else
1144           ui_out_field_string (uiout, "addr", "<unavailable>");
1145         annotate_frame_address_end ();
1146         ui_out_text (uiout, " in ");
1147       }
1148   annotate_frame_function_name ();
1149   fprintf_symbol_filtered (stb, funname ? funname : "??",
1150                            funlang, DMGL_ANSI);
1151   ui_out_field_stream (uiout, "func", stb);
1152   ui_out_wrap_hint (uiout, "   ");
1153   annotate_frame_args ();
1154       
1155   ui_out_text (uiout, " (");
1156   if (print_args)
1157     {
1158       struct gdbarch *gdbarch = get_frame_arch (frame);
1159       int numargs;
1160       struct cleanup *args_list_chain;
1161       volatile struct gdb_exception e;
1162
1163       if (gdbarch_frame_num_args_p (gdbarch))
1164         {
1165           numargs = gdbarch_frame_num_args (gdbarch, frame);
1166           gdb_assert (numargs >= 0);
1167         }
1168       else
1169         numargs = -1;
1170     
1171       args_list_chain = make_cleanup_ui_out_list_begin_end (uiout, "args");
1172       TRY_CATCH (e, RETURN_MASK_ERROR)
1173         {
1174           print_frame_args (func, frame, numargs, gdb_stdout);
1175         }
1176       /* FIXME: ARGS must be a list.  If one argument is a string it
1177           will have " that will not be properly escaped.  */
1178       /* Invoke ui_out_tuple_end.  */
1179       do_cleanups (args_list_chain);
1180       QUIT;
1181     }
1182   ui_out_text (uiout, ")");
1183   if (sal.symtab)
1184     {
1185       const char *filename_display;
1186       
1187       filename_display = symtab_to_filename_for_display (sal.symtab);
1188       annotate_frame_source_begin ();
1189       ui_out_wrap_hint (uiout, "   ");
1190       ui_out_text (uiout, " at ");
1191       annotate_frame_source_file ();
1192       ui_out_field_string (uiout, "file", filename_display);
1193       if (ui_out_is_mi_like_p (uiout))
1194         {
1195           const char *fullname = symtab_to_fullname (sal.symtab);
1196
1197           ui_out_field_string (uiout, "fullname", fullname);
1198         }
1199       annotate_frame_source_file_end ();
1200       ui_out_text (uiout, ":");
1201       annotate_frame_source_line ();
1202       ui_out_field_int (uiout, "line", sal.line);
1203       annotate_frame_source_end ();
1204     }
1205
1206   if (pc_p && (funname == NULL || sal.symtab == NULL))
1207     {
1208 #ifdef PC_SOLIB
1209       char *lib = PC_SOLIB (get_frame_pc (frame));
1210 #else
1211       char *lib = solib_name_from_address (get_frame_program_space (frame),
1212                                            get_frame_pc (frame));
1213 #endif
1214       if (lib)
1215         {
1216           annotate_frame_where ();
1217           ui_out_wrap_hint (uiout, "  ");
1218           ui_out_text (uiout, " from ");
1219           ui_out_field_string (uiout, "from", lib);
1220         }
1221     }
1222
1223   /* do_cleanups will call ui_out_tuple_end() for us.  */
1224   do_cleanups (list_chain);
1225   ui_out_text (uiout, "\n");
1226   do_cleanups (old_chain);
1227 }
1228 \f
1229
1230 /* Read a frame specification in whatever the appropriate format is
1231    from FRAME_EXP.  Call error(), printing MESSAGE, if the
1232    specification is in any way invalid (so this function never returns
1233    NULL).  When SEPECTED_P is non-NULL set its target to indicate that
1234    the default selected frame was used.  */
1235
1236 static struct frame_info *
1237 parse_frame_specification_1 (const char *frame_exp, const char *message,
1238                              int *selected_frame_p)
1239 {
1240   int numargs;
1241   struct value *args[4];
1242   CORE_ADDR addrs[ARRAY_SIZE (args)];
1243
1244   if (frame_exp == NULL)
1245     numargs = 0;
1246   else
1247     {
1248       numargs = 0;
1249       while (1)
1250         {
1251           char *addr_string;
1252           struct cleanup *cleanup;
1253           const char *p;
1254
1255           /* Skip leading white space, bail of EOL.  */
1256           frame_exp = skip_spaces_const (frame_exp);
1257           if (!*frame_exp)
1258             break;
1259
1260           /* Parse the argument, extract it, save it.  */
1261           for (p = frame_exp;
1262                *p && !isspace (*p);
1263                p++);
1264           addr_string = savestring (frame_exp, p - frame_exp);
1265           frame_exp = p;
1266           cleanup = make_cleanup (xfree, addr_string);
1267           
1268           /* NOTE: Parse and evaluate expression, but do not use
1269              functions such as parse_and_eval_long or
1270              parse_and_eval_address to also extract the value.
1271              Instead value_as_long and value_as_address are used.
1272              This avoids problems with expressions that contain
1273              side-effects.  */
1274           if (numargs >= ARRAY_SIZE (args))
1275             error (_("Too many args in frame specification"));
1276           args[numargs++] = parse_and_eval (addr_string);
1277
1278           do_cleanups (cleanup);
1279         }
1280     }
1281
1282   /* If no args, default to the selected frame.  */
1283   if (numargs == 0)
1284     {
1285       if (selected_frame_p != NULL)
1286         (*selected_frame_p) = 1;
1287       return get_selected_frame (message);
1288     }
1289
1290   /* None of the remaining use the selected frame.  */
1291   if (selected_frame_p != NULL)
1292     (*selected_frame_p) = 0;
1293
1294   /* Assume the single arg[0] is an integer, and try using that to
1295      select a frame relative to current.  */
1296   if (numargs == 1)
1297     {
1298       struct frame_info *fid;
1299       int level = value_as_long (args[0]);
1300
1301       fid = find_relative_frame (get_current_frame (), &level);
1302       if (level == 0)
1303         /* find_relative_frame was successful.  */
1304         return fid;
1305     }
1306
1307   /* Convert each value into a corresponding address.  */
1308   {
1309     int i;
1310
1311     for (i = 0; i < numargs; i++)
1312       addrs[i] = value_as_address (args[i]);
1313   }
1314
1315   /* Assume that the single arg[0] is an address, use that to identify
1316      a frame with a matching ID.  Should this also accept stack/pc or
1317      stack/pc/special.  */
1318   if (numargs == 1)
1319     {
1320       struct frame_id id = frame_id_build_wild (addrs[0]);
1321       struct frame_info *fid;
1322
1323       /* If (s)he specifies the frame with an address, he deserves
1324          what (s)he gets.  Still, give the highest one that matches.
1325          (NOTE: cagney/2004-10-29: Why highest, or outer-most, I don't
1326          know).  */
1327       for (fid = get_current_frame ();
1328            fid != NULL;
1329            fid = get_prev_frame (fid))
1330         {
1331           if (frame_id_eq (id, get_frame_id (fid)))
1332             {
1333               struct frame_info *prev_frame;
1334
1335               while (1)
1336                 {
1337                   prev_frame = get_prev_frame (fid);
1338                   if (!prev_frame
1339                       || !frame_id_eq (id, get_frame_id (prev_frame)))
1340                     break;
1341                   fid = prev_frame;
1342                 }
1343               return fid;
1344             }
1345         }
1346       }
1347
1348   /* We couldn't identify the frame as an existing frame, but
1349      perhaps we can create one with a single argument.  */
1350   if (numargs == 1)
1351     return create_new_frame (addrs[0], 0);
1352   else if (numargs == 2)
1353     return create_new_frame (addrs[0], addrs[1]);
1354   else
1355     error (_("Too many args in frame specification"));
1356 }
1357
1358 static struct frame_info *
1359 parse_frame_specification (char *frame_exp)
1360 {
1361   return parse_frame_specification_1 (frame_exp, NULL, NULL);
1362 }
1363
1364 /* Print verbosely the selected frame or the frame at address
1365    ADDR_EXP.  Absolutely all information in the frame is printed.  */
1366
1367 static void
1368 frame_info (char *addr_exp, int from_tty)
1369 {
1370   struct frame_info *fi;
1371   struct symtab_and_line sal;
1372   struct symbol *func;
1373   struct symtab *s;
1374   struct frame_info *calling_frame_info;
1375   int numregs;
1376   const char *funname = 0;
1377   enum language funlang = language_unknown;
1378   const char *pc_regname;
1379   int selected_frame_p;
1380   struct gdbarch *gdbarch;
1381   struct cleanup *back_to = make_cleanup (null_cleanup, NULL);
1382   CORE_ADDR frame_pc;
1383   int frame_pc_p;
1384   CORE_ADDR caller_pc;
1385
1386   fi = parse_frame_specification_1 (addr_exp, "No stack.", &selected_frame_p);
1387   gdbarch = get_frame_arch (fi);
1388
1389   /* Name of the value returned by get_frame_pc().  Per comments, "pc"
1390      is not a good name.  */
1391   if (gdbarch_pc_regnum (gdbarch) >= 0)
1392     /* OK, this is weird.  The gdbarch_pc_regnum hardware register's value can
1393        easily not match that of the internal value returned by
1394        get_frame_pc().  */
1395     pc_regname = gdbarch_register_name (gdbarch, gdbarch_pc_regnum (gdbarch));
1396   else
1397     /* But then, this is weird to.  Even without gdbarch_pc_regnum, an
1398        architectures will often have a hardware register called "pc",
1399        and that register's value, again, can easily not match
1400        get_frame_pc().  */
1401     pc_regname = "pc";
1402
1403   frame_pc_p = get_frame_pc_if_available (fi, &frame_pc);
1404   find_frame_sal (fi, &sal);
1405   func = get_frame_function (fi);
1406   s = sal.symtab;
1407   if (func)
1408     {
1409       funname = SYMBOL_PRINT_NAME (func);
1410       funlang = SYMBOL_LANGUAGE (func);
1411       if (funlang == language_cplus)
1412         {
1413           /* It seems appropriate to use SYMBOL_PRINT_NAME() here,
1414              to display the demangled name that we already have
1415              stored in the symbol table, but we stored a version
1416              with DMGL_PARAMS turned on, and here we don't want to
1417              display parameters.  So remove the parameters.  */
1418           char *func_only = cp_remove_params (funname);
1419
1420           if (func_only)
1421             {
1422               funname = func_only;
1423               make_cleanup (xfree, func_only);
1424             }
1425         }
1426     }
1427   else if (frame_pc_p)
1428     {
1429       struct bound_minimal_symbol msymbol;
1430
1431       msymbol = lookup_minimal_symbol_by_pc (frame_pc);
1432       if (msymbol.minsym != NULL)
1433         {
1434           funname = SYMBOL_PRINT_NAME (msymbol.minsym);
1435           funlang = SYMBOL_LANGUAGE (msymbol.minsym);
1436         }
1437     }
1438   calling_frame_info = get_prev_frame (fi);
1439
1440   if (selected_frame_p && frame_relative_level (fi) >= 0)
1441     {
1442       printf_filtered (_("Stack level %d, frame at "),
1443                        frame_relative_level (fi));
1444     }
1445   else
1446     {
1447       printf_filtered (_("Stack frame at "));
1448     }
1449   fputs_filtered (paddress (gdbarch, get_frame_base (fi)), gdb_stdout);
1450   printf_filtered (":\n");
1451   printf_filtered (" %s = ", pc_regname);
1452   if (frame_pc_p)
1453     fputs_filtered (paddress (gdbarch, get_frame_pc (fi)), gdb_stdout);
1454   else
1455     fputs_filtered ("<unavailable>", gdb_stdout);
1456
1457   wrap_here ("   ");
1458   if (funname)
1459     {
1460       printf_filtered (" in ");
1461       fprintf_symbol_filtered (gdb_stdout, funname, funlang,
1462                                DMGL_ANSI | DMGL_PARAMS);
1463     }
1464   wrap_here ("   ");
1465   if (sal.symtab)
1466     printf_filtered (" (%s:%d)", symtab_to_filename_for_display (sal.symtab),
1467                      sal.line);
1468   puts_filtered ("; ");
1469   wrap_here ("    ");
1470   printf_filtered ("saved %s ", pc_regname);
1471   if (frame_unwind_caller_pc_if_available (fi, &caller_pc))
1472     fputs_filtered (paddress (gdbarch, caller_pc), gdb_stdout);
1473   else
1474     fputs_filtered ("<unavailable>", gdb_stdout);
1475   printf_filtered ("\n");
1476
1477   if (calling_frame_info == NULL)
1478     {
1479       enum unwind_stop_reason reason;
1480
1481       reason = get_frame_unwind_stop_reason (fi);
1482       if (reason != UNWIND_NO_REASON)
1483         printf_filtered (_(" Outermost frame: %s\n"),
1484                          frame_stop_reason_string (reason));
1485     }
1486   else if (get_frame_type (fi) == TAILCALL_FRAME)
1487     puts_filtered (" tail call frame");
1488   else if (get_frame_type (fi) == INLINE_FRAME)
1489     printf_filtered (" inlined into frame %d",
1490                      frame_relative_level (get_prev_frame (fi)));
1491   else
1492     {
1493       printf_filtered (" called by frame at ");
1494       fputs_filtered (paddress (gdbarch, get_frame_base (calling_frame_info)),
1495                       gdb_stdout);
1496     }
1497   if (get_next_frame (fi) && calling_frame_info)
1498     puts_filtered (",");
1499   wrap_here ("   ");
1500   if (get_next_frame (fi))
1501     {
1502       printf_filtered (" caller of frame at ");
1503       fputs_filtered (paddress (gdbarch, get_frame_base (get_next_frame (fi))),
1504                       gdb_stdout);
1505     }
1506   if (get_next_frame (fi) || calling_frame_info)
1507     puts_filtered ("\n");
1508
1509   if (s)
1510     printf_filtered (" source language %s.\n",
1511                      language_str (s->language));
1512
1513   {
1514     /* Address of the argument list for this frame, or 0.  */
1515     CORE_ADDR arg_list = get_frame_args_address (fi);
1516     /* Number of args for this frame, or -1 if unknown.  */
1517     int numargs;
1518
1519     if (arg_list == 0)
1520       printf_filtered (" Arglist at unknown address.\n");
1521     else
1522       {
1523         printf_filtered (" Arglist at ");
1524         fputs_filtered (paddress (gdbarch, arg_list), gdb_stdout);
1525         printf_filtered (",");
1526
1527         if (!gdbarch_frame_num_args_p (gdbarch))
1528           {
1529             numargs = -1;
1530             puts_filtered (" args: ");
1531           }
1532         else
1533           {
1534             numargs = gdbarch_frame_num_args (gdbarch, fi);
1535             gdb_assert (numargs >= 0);
1536             if (numargs == 0)
1537               puts_filtered (" no args.");
1538             else if (numargs == 1)
1539               puts_filtered (" 1 arg: ");
1540             else
1541               printf_filtered (" %d args: ", numargs);
1542           }
1543         print_frame_args (func, fi, numargs, gdb_stdout);
1544         puts_filtered ("\n");
1545       }
1546   }
1547   {
1548     /* Address of the local variables for this frame, or 0.  */
1549     CORE_ADDR arg_list = get_frame_locals_address (fi);
1550
1551     if (arg_list == 0)
1552       printf_filtered (" Locals at unknown address,");
1553     else
1554       {
1555         printf_filtered (" Locals at ");
1556         fputs_filtered (paddress (gdbarch, arg_list), gdb_stdout);
1557         printf_filtered (",");
1558       }
1559   }
1560
1561   /* Print as much information as possible on the location of all the
1562      registers.  */
1563   {
1564     enum lval_type lval;
1565     int optimized;
1566     int unavailable;
1567     CORE_ADDR addr;
1568     int realnum;
1569     int count;
1570     int i;
1571     int need_nl = 1;
1572
1573     /* The sp is special; what's displayed isn't the save address, but
1574        the value of the previous frame's sp.  This is a legacy thing,
1575        at one stage the frame cached the previous frame's SP instead
1576        of its address, hence it was easiest to just display the cached
1577        value.  */
1578     if (gdbarch_sp_regnum (gdbarch) >= 0)
1579       {
1580         /* Find out the location of the saved stack pointer with out
1581            actually evaluating it.  */
1582         frame_register_unwind (fi, gdbarch_sp_regnum (gdbarch),
1583                                &optimized, &unavailable, &lval, &addr,
1584                                &realnum, NULL);
1585         if (!optimized && !unavailable && lval == not_lval)
1586           {
1587             enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
1588             int sp_size = register_size (gdbarch, gdbarch_sp_regnum (gdbarch));
1589             gdb_byte value[MAX_REGISTER_SIZE];
1590             CORE_ADDR sp;
1591
1592             frame_register_unwind (fi, gdbarch_sp_regnum (gdbarch),
1593                                    &optimized, &unavailable, &lval, &addr,
1594                                    &realnum, value);
1595             /* NOTE: cagney/2003-05-22: This is assuming that the
1596                stack pointer was packed as an unsigned integer.  That
1597                may or may not be valid.  */
1598             sp = extract_unsigned_integer (value, sp_size, byte_order);
1599             printf_filtered (" Previous frame's sp is ");
1600             fputs_filtered (paddress (gdbarch, sp), gdb_stdout);
1601             printf_filtered ("\n");
1602             need_nl = 0;
1603           }
1604         else if (!optimized && !unavailable && lval == lval_memory)
1605           {
1606             printf_filtered (" Previous frame's sp at ");
1607             fputs_filtered (paddress (gdbarch, addr), gdb_stdout);
1608             printf_filtered ("\n");
1609             need_nl = 0;
1610           }
1611         else if (!optimized && !unavailable && lval == lval_register)
1612           {
1613             printf_filtered (" Previous frame's sp in %s\n",
1614                              gdbarch_register_name (gdbarch, realnum));
1615             need_nl = 0;
1616           }
1617         /* else keep quiet.  */
1618       }
1619
1620     count = 0;
1621     numregs = gdbarch_num_regs (gdbarch)
1622               + gdbarch_num_pseudo_regs (gdbarch);
1623     for (i = 0; i < numregs; i++)
1624       if (i != gdbarch_sp_regnum (gdbarch)
1625           && gdbarch_register_reggroup_p (gdbarch, i, all_reggroup))
1626         {
1627           /* Find out the location of the saved register without
1628              fetching the corresponding value.  */
1629           frame_register_unwind (fi, i, &optimized, &unavailable,
1630                                  &lval, &addr, &realnum, NULL);
1631           /* For moment, only display registers that were saved on the
1632              stack.  */
1633           if (!optimized && !unavailable && lval == lval_memory)
1634             {
1635               if (count == 0)
1636                 puts_filtered (" Saved registers:\n ");
1637               else
1638                 puts_filtered (",");
1639               wrap_here (" ");
1640               printf_filtered (" %s at ",
1641                                gdbarch_register_name (gdbarch, i));
1642               fputs_filtered (paddress (gdbarch, addr), gdb_stdout);
1643               count++;
1644             }
1645         }
1646     if (count || need_nl)
1647       puts_filtered ("\n");
1648   }
1649
1650   do_cleanups (back_to);
1651 }
1652
1653 /* Print briefly all stack frames or just the innermost COUNT_EXP
1654    frames.  */
1655
1656 static void
1657 backtrace_command_1 (char *count_exp, int show_locals, int from_tty)
1658 {
1659   struct frame_info *fi;
1660   int count;
1661   int i;
1662   struct frame_info *trailing;
1663   int trailing_level;
1664
1665   if (!target_has_stack)
1666     error (_("No stack."));
1667
1668   /* The following code must do two things.  First, it must set the
1669      variable TRAILING to the frame from which we should start
1670      printing.  Second, it must set the variable count to the number
1671      of frames which we should print, or -1 if all of them.  */
1672   trailing = get_current_frame ();
1673
1674   trailing_level = 0;
1675   if (count_exp)
1676     {
1677       count = parse_and_eval_long (count_exp);
1678       if (count < 0)
1679         {
1680           struct frame_info *current;
1681
1682           count = -count;
1683
1684           current = trailing;
1685           while (current && count--)
1686             {
1687               QUIT;
1688               current = get_prev_frame (current);
1689             }
1690
1691           /* Will stop when CURRENT reaches the top of the stack.
1692              TRAILING will be COUNT below it.  */
1693           while (current)
1694             {
1695               QUIT;
1696               trailing = get_prev_frame (trailing);
1697               current = get_prev_frame (current);
1698               trailing_level++;
1699             }
1700
1701           count = -1;
1702         }
1703     }
1704   else
1705     count = -1;
1706
1707   if (info_verbose)
1708     {
1709       /* Read in symbols for all of the frames.  Need to do this in a
1710          separate pass so that "Reading in symbols for xxx" messages
1711          don't screw up the appearance of the backtrace.  Also if
1712          people have strong opinions against reading symbols for
1713          backtrace this may have to be an option.  */
1714       i = count;
1715       for (fi = trailing; fi != NULL && i--; fi = get_prev_frame (fi))
1716         {
1717           CORE_ADDR pc;
1718
1719           QUIT;
1720           pc = get_frame_address_in_block (fi);
1721           find_pc_sect_symtab_via_partial (pc, find_pc_mapped_section (pc));
1722         }
1723     }
1724
1725   for (i = 0, fi = trailing; fi && count--; i++, fi = get_prev_frame (fi))
1726     {
1727       QUIT;
1728
1729       /* Don't use print_stack_frame; if an error() occurs it probably
1730          means further attempts to backtrace would fail (on the other
1731          hand, perhaps the code does or could be fixed to make sure
1732          the frame->prev field gets set to NULL in that case).  */
1733       print_frame_info (fi, 1, LOCATION, 1);
1734       if (show_locals)
1735         {
1736           struct frame_id frame_id = get_frame_id (fi);
1737
1738           print_frame_local_vars (fi, 1, gdb_stdout);
1739
1740           /* print_frame_local_vars invalidates FI.  */
1741           fi = frame_find_by_id (frame_id);
1742           if (fi == NULL)
1743             {
1744               trailing = NULL;
1745               warning (_("Unable to restore previously selected frame."));
1746               break;
1747             }
1748         }
1749
1750       /* Save the last frame to check for error conditions.  */
1751       trailing = fi;
1752     }
1753
1754   /* If we've stopped before the end, mention that.  */
1755   if (fi && from_tty)
1756     printf_filtered (_("(More stack frames follow...)\n"));
1757
1758   /* If we've run out of frames, and the reason appears to be an error
1759      condition, print it.  */
1760   if (fi == NULL && trailing != NULL)
1761     {
1762       enum unwind_stop_reason reason;
1763
1764       reason = get_frame_unwind_stop_reason (trailing);
1765       if (reason >= UNWIND_FIRST_ERROR)
1766         printf_filtered (_("Backtrace stopped: %s\n"),
1767                          frame_stop_reason_string (reason));
1768     }
1769 }
1770
1771 static void
1772 backtrace_command (char *arg, int from_tty)
1773 {
1774   struct cleanup *old_chain = make_cleanup (null_cleanup, NULL);
1775   int fulltrace_arg = -1, arglen = 0, argc = 0;
1776
1777   if (arg)
1778     {
1779       char **argv;
1780       int i;
1781
1782       argv = gdb_buildargv (arg);
1783       make_cleanup_freeargv (argv);
1784       argc = 0;
1785       for (i = 0; argv[i]; i++)
1786         {
1787           unsigned int j;
1788
1789           for (j = 0; j < strlen (argv[i]); j++)
1790             argv[i][j] = tolower (argv[i][j]);
1791
1792           if (fulltrace_arg < 0 && subset_compare (argv[i], "full"))
1793             fulltrace_arg = argc;
1794           else
1795             {
1796               arglen += strlen (argv[i]);
1797               argc++;
1798             }
1799         }
1800       arglen += argc;
1801       if (fulltrace_arg >= 0)
1802         {
1803           if (arglen > 0)
1804             {
1805               arg = xmalloc (arglen + 1);
1806               make_cleanup (xfree, arg);
1807               arg[0] = 0;
1808               for (i = 0; i < (argc + 1); i++)
1809                 {
1810                   if (i != fulltrace_arg)
1811                     {
1812                       strcat (arg, argv[i]);
1813                       strcat (arg, " ");
1814                     }
1815                 }
1816             }
1817           else
1818             arg = NULL;
1819         }
1820     }
1821
1822   backtrace_command_1 (arg, fulltrace_arg >= 0 /* show_locals */, from_tty);
1823
1824   do_cleanups (old_chain);
1825 }
1826
1827 static void
1828 backtrace_full_command (char *arg, int from_tty)
1829 {
1830   backtrace_command_1 (arg, 1 /* show_locals */, from_tty);
1831 }
1832 \f
1833
1834 /* Iterate over the local variables of a block B, calling CB with
1835    CB_DATA.  */
1836
1837 static void
1838 iterate_over_block_locals (struct block *b,
1839                            iterate_over_block_arg_local_vars_cb cb,
1840                            void *cb_data)
1841 {
1842   struct block_iterator iter;
1843   struct symbol *sym;
1844
1845   ALL_BLOCK_SYMBOLS (b, iter, sym)
1846     {
1847       switch (SYMBOL_CLASS (sym))
1848         {
1849         case LOC_LOCAL:
1850         case LOC_REGISTER:
1851         case LOC_STATIC:
1852         case LOC_COMPUTED:
1853           if (SYMBOL_IS_ARGUMENT (sym))
1854             break;
1855           if (SYMBOL_DOMAIN (sym) == COMMON_BLOCK_DOMAIN)
1856             break;
1857           (*cb) (SYMBOL_PRINT_NAME (sym), sym, cb_data);
1858           break;
1859
1860         default:
1861           /* Ignore symbols which are not locals.  */
1862           break;
1863         }
1864     }
1865 }
1866
1867
1868 /* Same, but print labels.  */
1869
1870 #if 0
1871 /* Commented out, as the code using this function has also been
1872    commented out.  FIXME:brobecker/2009-01-13: Find out why the code
1873    was commented out in the first place.  The discussion introducing
1874    this change (2007-12-04: Support lexical blocks and function bodies
1875    that occupy non-contiguous address ranges) did not explain why
1876    this change was made.  */
1877 static int
1878 print_block_frame_labels (struct gdbarch *gdbarch, struct block *b,
1879                           int *have_default, struct ui_file *stream)
1880 {
1881   struct block_iterator iter;
1882   struct symbol *sym;
1883   int values_printed = 0;
1884
1885   ALL_BLOCK_SYMBOLS (b, iter, sym)
1886     {
1887       if (strcmp (SYMBOL_LINKAGE_NAME (sym), "default") == 0)
1888         {
1889           if (*have_default)
1890             continue;
1891           *have_default = 1;
1892         }
1893       if (SYMBOL_CLASS (sym) == LOC_LABEL)
1894         {
1895           struct symtab_and_line sal;
1896           struct value_print_options opts;
1897
1898           sal = find_pc_line (SYMBOL_VALUE_ADDRESS (sym), 0);
1899           values_printed = 1;
1900           fputs_filtered (SYMBOL_PRINT_NAME (sym), stream);
1901           get_user_print_options (&opts);
1902           if (opts.addressprint)
1903             {
1904               fprintf_filtered (stream, " ");
1905               fputs_filtered (paddress (gdbarch, SYMBOL_VALUE_ADDRESS (sym)),
1906                               stream);
1907             }
1908           fprintf_filtered (stream, " in file %s, line %d\n",
1909                             sal.symtab->filename, sal.line);
1910         }
1911     }
1912
1913   return values_printed;
1914 }
1915 #endif
1916
1917 /* Iterate over all the local variables in block B, including all its
1918    superblocks, stopping when the top-level block is reached.  */
1919
1920 void
1921 iterate_over_block_local_vars (struct block *block,
1922                                iterate_over_block_arg_local_vars_cb cb,
1923                                void *cb_data)
1924 {
1925   while (block)
1926     {
1927       iterate_over_block_locals (block, cb, cb_data);
1928       /* After handling the function's top-level block, stop.  Don't
1929          continue to its superblock, the block of per-file
1930          symbols.  */
1931       if (BLOCK_FUNCTION (block))
1932         break;
1933       block = BLOCK_SUPERBLOCK (block);
1934     }
1935 }
1936
1937 /* Data to be passed around in the calls to the locals and args
1938    iterators.  */
1939
1940 struct print_variable_and_value_data
1941 {
1942   struct frame_id frame_id;
1943   int num_tabs;
1944   struct ui_file *stream;
1945   int values_printed;
1946 };
1947
1948 /* The callback for the locals and args iterators.  */
1949
1950 static void
1951 do_print_variable_and_value (const char *print_name,
1952                              struct symbol *sym,
1953                              void *cb_data)
1954 {
1955   struct print_variable_and_value_data *p = cb_data;
1956   struct frame_info *frame;
1957
1958   frame = frame_find_by_id (p->frame_id);
1959   if (frame == NULL)
1960     {
1961       warning (_("Unable to restore previously selected frame."));
1962       return;
1963     }
1964
1965   print_variable_and_value (print_name, sym, frame, p->stream, p->num_tabs);
1966
1967   /* print_variable_and_value invalidates FRAME.  */
1968   frame = NULL;
1969
1970   p->values_printed = 1;
1971 }
1972
1973 /* Print all variables from the innermost up to the function block of FRAME.
1974    Print them with values to STREAM indented by NUM_TABS.
1975
1976    This function will invalidate FRAME.  */
1977
1978 static void
1979 print_frame_local_vars (struct frame_info *frame, int num_tabs,
1980                         struct ui_file *stream)
1981 {
1982   struct print_variable_and_value_data cb_data;
1983   struct block *block;
1984   CORE_ADDR pc;
1985
1986   if (!get_frame_pc_if_available (frame, &pc))
1987     {
1988       fprintf_filtered (stream,
1989                         _("PC unavailable, cannot determine locals.\n"));
1990       return;
1991     }
1992
1993   block = get_frame_block (frame, 0);
1994   if (block == 0)
1995     {
1996       fprintf_filtered (stream, "No symbol table info available.\n");
1997       return;
1998     }
1999
2000   cb_data.frame_id = get_frame_id (frame);
2001   cb_data.num_tabs = 4 * num_tabs;
2002   cb_data.stream = stream;
2003   cb_data.values_printed = 0;
2004
2005   iterate_over_block_local_vars (block,
2006                                  do_print_variable_and_value,
2007                                  &cb_data);
2008
2009   /* do_print_variable_and_value invalidates FRAME.  */
2010   frame = NULL;
2011
2012   if (!cb_data.values_printed)
2013     fprintf_filtered (stream, _("No locals.\n"));
2014 }
2015
2016 void
2017 locals_info (char *args, int from_tty)
2018 {
2019   print_frame_local_vars (get_selected_frame (_("No frame selected.")),
2020                           0, gdb_stdout);
2021 }
2022
2023 /* Iterate over all the argument variables in block B.
2024
2025    Returns 1 if any argument was walked; 0 otherwise.  */
2026
2027 void
2028 iterate_over_block_arg_vars (struct block *b,
2029                              iterate_over_block_arg_local_vars_cb cb,
2030                              void *cb_data)
2031 {
2032   struct block_iterator iter;
2033   struct symbol *sym, *sym2;
2034
2035   ALL_BLOCK_SYMBOLS (b, iter, sym)
2036     {
2037       /* Don't worry about things which aren't arguments.  */
2038       if (SYMBOL_IS_ARGUMENT (sym))
2039         {
2040           /* We have to look up the symbol because arguments can have
2041              two entries (one a parameter, one a local) and the one we
2042              want is the local, which lookup_symbol will find for us.
2043              This includes gcc1 (not gcc2) on the sparc when passing a
2044              small structure and gcc2 when the argument type is float
2045              and it is passed as a double and converted to float by
2046              the prologue (in the latter case the type of the LOC_ARG
2047              symbol is double and the type of the LOC_LOCAL symbol is
2048              float).  There are also LOC_ARG/LOC_REGISTER pairs which
2049              are not combined in symbol-reading.  */
2050
2051           sym2 = lookup_symbol (SYMBOL_LINKAGE_NAME (sym),
2052                                 b, VAR_DOMAIN, NULL);
2053           (*cb) (SYMBOL_PRINT_NAME (sym), sym2, cb_data);
2054         }
2055     }
2056 }
2057
2058 /* Print all argument variables of the function of FRAME.
2059    Print them with values to STREAM.
2060
2061    This function will invalidate FRAME.  */
2062
2063 static void
2064 print_frame_arg_vars (struct frame_info *frame, struct ui_file *stream)
2065 {
2066   struct print_variable_and_value_data cb_data;
2067   struct symbol *func;
2068   CORE_ADDR pc;
2069
2070   if (!get_frame_pc_if_available (frame, &pc))
2071     {
2072       fprintf_filtered (stream, _("PC unavailable, cannot determine args.\n"));
2073       return;
2074     }
2075
2076   func = get_frame_function (frame);
2077   if (func == NULL)
2078     {
2079       fprintf_filtered (stream, _("No symbol table info available.\n"));
2080       return;
2081     }
2082
2083   cb_data.frame_id = get_frame_id (frame);
2084   cb_data.num_tabs = 0;
2085   cb_data.stream = gdb_stdout;
2086   cb_data.values_printed = 0;
2087
2088   iterate_over_block_arg_vars (SYMBOL_BLOCK_VALUE (func),
2089                                do_print_variable_and_value, &cb_data);
2090
2091   /* do_print_variable_and_value invalidates FRAME.  */
2092   frame = NULL;
2093
2094   if (!cb_data.values_printed)
2095     fprintf_filtered (stream, _("No arguments.\n"));
2096 }
2097
2098 void
2099 args_info (char *ignore, int from_tty)
2100 {
2101   print_frame_arg_vars (get_selected_frame (_("No frame selected.")),
2102                         gdb_stdout);
2103 }
2104
2105
2106 static void
2107 args_plus_locals_info (char *ignore, int from_tty)
2108 {
2109   args_info (ignore, from_tty);
2110   locals_info (ignore, from_tty);
2111 }
2112 \f
2113
2114 /* Select frame FRAME.  Also print the stack frame and show the source
2115    if this is the tui version.  */
2116 static void
2117 select_and_print_frame (struct frame_info *frame)
2118 {
2119   select_frame (frame);
2120   if (frame)
2121     print_stack_frame (frame, 1, SRC_AND_LOC);
2122 }
2123 \f
2124 /* Return the symbol-block in which the selected frame is executing.
2125    Can return zero under various legitimate circumstances.
2126
2127    If ADDR_IN_BLOCK is non-zero, set *ADDR_IN_BLOCK to the relevant
2128    code address within the block returned.  We use this to decide
2129    which macros are in scope.  */
2130
2131 struct block *
2132 get_selected_block (CORE_ADDR *addr_in_block)
2133 {
2134   if (!has_stack_frames ())
2135     return 0;
2136
2137   return get_frame_block (get_selected_frame (NULL), addr_in_block);
2138 }
2139
2140 /* Find a frame a certain number of levels away from FRAME.
2141    LEVEL_OFFSET_PTR points to an int containing the number of levels.
2142    Positive means go to earlier frames (up); negative, the reverse.
2143    The int that contains the number of levels is counted toward
2144    zero as the frames for those levels are found.
2145    If the top or bottom frame is reached, that frame is returned,
2146    but the final value of *LEVEL_OFFSET_PTR is nonzero and indicates
2147    how much farther the original request asked to go.  */
2148
2149 struct frame_info *
2150 find_relative_frame (struct frame_info *frame, int *level_offset_ptr)
2151 {
2152   /* Going up is simple: just call get_prev_frame enough times or
2153      until the initial frame is reached.  */
2154   while (*level_offset_ptr > 0)
2155     {
2156       struct frame_info *prev = get_prev_frame (frame);
2157
2158       if (!prev)
2159         break;
2160       (*level_offset_ptr)--;
2161       frame = prev;
2162     }
2163
2164   /* Going down is just as simple.  */
2165   while (*level_offset_ptr < 0)
2166     {
2167       struct frame_info *next = get_next_frame (frame);
2168
2169       if (!next)
2170         break;
2171       (*level_offset_ptr)++;
2172       frame = next;
2173     }
2174
2175   return frame;
2176 }
2177
2178 /* The "select_frame" command.  With no argument this is a NOP.
2179    Select the frame at level LEVEL_EXP if it is a valid level.
2180    Otherwise, treat LEVEL_EXP as an address expression and select it.
2181
2182    See parse_frame_specification for more info on proper frame
2183    expressions.  */
2184
2185 void
2186 select_frame_command (char *level_exp, int from_tty)
2187 {
2188   select_frame (parse_frame_specification_1 (level_exp, "No stack.", NULL));
2189 }
2190
2191 /* The "frame" command.  With no argument, print the selected frame
2192    briefly.  With an argument, behave like select_frame and then print
2193    the selected frame.  */
2194
2195 static void
2196 frame_command (char *level_exp, int from_tty)
2197 {
2198   select_frame_command (level_exp, from_tty);
2199   print_stack_frame (get_selected_frame (NULL), 1, SRC_AND_LOC);
2200 }
2201
2202 /* The XDB Compatibility command to print the current frame.  */
2203
2204 static void
2205 current_frame_command (char *level_exp, int from_tty)
2206 {
2207   print_stack_frame (get_selected_frame (_("No stack.")), 1, SRC_AND_LOC);
2208 }
2209
2210 /* Select the frame up one or COUNT_EXP stack levels from the
2211    previously selected frame, and print it briefly.  */
2212
2213 static void
2214 up_silently_base (char *count_exp)
2215 {
2216   struct frame_info *frame;
2217   int count = 1;
2218
2219   if (count_exp)
2220     count = parse_and_eval_long (count_exp);
2221
2222   frame = find_relative_frame (get_selected_frame ("No stack."), &count);
2223   if (count != 0 && count_exp == NULL)
2224     error (_("Initial frame selected; you cannot go up."));
2225   select_frame (frame);
2226 }
2227
2228 static void
2229 up_silently_command (char *count_exp, int from_tty)
2230 {
2231   up_silently_base (count_exp);
2232 }
2233
2234 static void
2235 up_command (char *count_exp, int from_tty)
2236 {
2237   up_silently_base (count_exp);
2238   print_stack_frame (get_selected_frame (NULL), 1, SRC_AND_LOC);
2239 }
2240
2241 /* Select the frame down one or COUNT_EXP stack levels from the previously
2242    selected frame, and print it briefly.  */
2243
2244 static void
2245 down_silently_base (char *count_exp)
2246 {
2247   struct frame_info *frame;
2248   int count = -1;
2249
2250   if (count_exp)
2251     count = -parse_and_eval_long (count_exp);
2252
2253   frame = find_relative_frame (get_selected_frame ("No stack."), &count);
2254   if (count != 0 && count_exp == NULL)
2255     {
2256       /* We only do this if COUNT_EXP is not specified.  That way
2257          "down" means to really go down (and let me know if that is
2258          impossible), but "down 9999" can be used to mean go all the
2259          way down without getting an error.  */
2260
2261       error (_("Bottom (innermost) frame selected; you cannot go down."));
2262     }
2263
2264   select_frame (frame);
2265 }
2266
2267 static void
2268 down_silently_command (char *count_exp, int from_tty)
2269 {
2270   down_silently_base (count_exp);
2271 }
2272
2273 static void
2274 down_command (char *count_exp, int from_tty)
2275 {
2276   down_silently_base (count_exp);
2277   print_stack_frame (get_selected_frame (NULL), 1, SRC_AND_LOC);
2278 }
2279 \f
2280
2281 void
2282 return_command (char *retval_exp, int from_tty)
2283 {
2284   /* Initialize it just to avoid a GCC false warning.  */
2285   enum return_value_convention rv_conv = RETURN_VALUE_STRUCT_CONVENTION;
2286   struct frame_info *thisframe;
2287   struct gdbarch *gdbarch;
2288   struct symbol *thisfun;
2289   struct value *return_value = NULL;
2290   struct value *function = NULL;
2291   const char *query_prefix = "";
2292
2293   thisframe = get_selected_frame ("No selected frame.");
2294   thisfun = get_frame_function (thisframe);
2295   gdbarch = get_frame_arch (thisframe);
2296
2297   if (get_frame_type (get_current_frame ()) == INLINE_FRAME)
2298     error (_("Can not force return from an inlined function."));
2299
2300   /* Compute the return value.  If the computation triggers an error,
2301      let it bail.  If the return type can't be handled, set
2302      RETURN_VALUE to NULL, and QUERY_PREFIX to an informational
2303      message.  */
2304   if (retval_exp)
2305     {
2306       struct expression *retval_expr = parse_expression (retval_exp);
2307       struct cleanup *old_chain = make_cleanup (xfree, retval_expr);
2308       struct type *return_type = NULL;
2309
2310       /* Compute the return value.  Should the computation fail, this
2311          call throws an error.  */
2312       return_value = evaluate_expression (retval_expr);
2313
2314       /* Cast return value to the return type of the function.  Should
2315          the cast fail, this call throws an error.  */
2316       if (thisfun != NULL)
2317         return_type = TYPE_TARGET_TYPE (SYMBOL_TYPE (thisfun));
2318       if (return_type == NULL)
2319         {
2320           if (retval_expr->elts[0].opcode != UNOP_CAST
2321               && retval_expr->elts[0].opcode != UNOP_CAST_TYPE)
2322             error (_("Return value type not available for selected "
2323                      "stack frame.\n"
2324                      "Please use an explicit cast of the value to return."));
2325           return_type = value_type (return_value);
2326         }
2327       do_cleanups (old_chain);
2328       CHECK_TYPEDEF (return_type);
2329       return_value = value_cast (return_type, return_value);
2330
2331       /* Make sure the value is fully evaluated.  It may live in the
2332          stack frame we're about to pop.  */
2333       if (value_lazy (return_value))
2334         value_fetch_lazy (return_value);
2335
2336       if (thisfun != NULL)
2337         function = read_var_value (thisfun, thisframe);
2338
2339       rv_conv = RETURN_VALUE_REGISTER_CONVENTION;
2340       if (TYPE_CODE (return_type) == TYPE_CODE_VOID)
2341         /* If the return-type is "void", don't try to find the
2342            return-value's location.  However, do still evaluate the
2343            return expression so that, even when the expression result
2344            is discarded, side effects such as "return i++" still
2345            occur.  */
2346         return_value = NULL;
2347       else if (thisfun != NULL)
2348         {
2349           rv_conv = struct_return_convention (gdbarch, function, return_type);
2350           if (rv_conv == RETURN_VALUE_STRUCT_CONVENTION
2351               || rv_conv == RETURN_VALUE_ABI_RETURNS_ADDRESS)
2352             {
2353               query_prefix = "The location at which to store the "
2354                 "function's return value is unknown.\n"
2355                 "If you continue, the return value "
2356                 "that you specified will be ignored.\n";
2357               return_value = NULL;
2358             }
2359         }
2360     }
2361
2362   /* Does an interactive user really want to do this?  Include
2363      information, such as how well GDB can handle the return value, in
2364      the query message.  */
2365   if (from_tty)
2366     {
2367       int confirmed;
2368
2369       if (thisfun == NULL)
2370         confirmed = query (_("%sMake selected stack frame return now? "),
2371                            query_prefix);
2372       else
2373         confirmed = query (_("%sMake %s return now? "), query_prefix,
2374                            SYMBOL_PRINT_NAME (thisfun));
2375       if (!confirmed)
2376         error (_("Not confirmed"));
2377     }
2378
2379   /* Discard the selected frame and all frames inner-to it.  */
2380   frame_pop (get_selected_frame (NULL));
2381
2382   /* Store RETURN_VALUE in the just-returned register set.  */
2383   if (return_value != NULL)
2384     {
2385       struct type *return_type = value_type (return_value);
2386       struct gdbarch *gdbarch = get_regcache_arch (get_current_regcache ());
2387
2388       gdb_assert (rv_conv != RETURN_VALUE_STRUCT_CONVENTION
2389                   && rv_conv != RETURN_VALUE_ABI_RETURNS_ADDRESS);
2390       gdbarch_return_value (gdbarch, function, return_type,
2391                             get_current_regcache (), NULL /*read*/,
2392                             value_contents (return_value) /*write*/);
2393     }
2394
2395   /* If we are at the end of a call dummy now, pop the dummy frame
2396      too.  */
2397   if (get_frame_type (get_current_frame ()) == DUMMY_FRAME)
2398     frame_pop (get_current_frame ());
2399
2400   /* If interactive, print the frame that is now current.  */
2401   if (from_tty)
2402     frame_command ("0", 1);
2403   else
2404     select_frame_command ("0", 0);
2405 }
2406
2407 /* Sets the scope to input function name, provided that the function
2408    is within the current stack frame.  */
2409
2410 struct function_bounds
2411 {
2412   CORE_ADDR low, high;
2413 };
2414
2415 static void
2416 func_command (char *arg, int from_tty)
2417 {
2418   struct frame_info *frame;
2419   int found = 0;
2420   struct symtabs_and_lines sals;
2421   int i;
2422   int level = 1;
2423   struct function_bounds *func_bounds = NULL;
2424   struct cleanup *cleanups;
2425
2426   if (arg != NULL)
2427     return;
2428
2429   frame = parse_frame_specification ("0");
2430   sals = decode_line_with_current_source (arg, DECODE_LINE_FUNFIRSTLINE);
2431   cleanups = make_cleanup (xfree, sals.sals);
2432   func_bounds = (struct function_bounds *) xmalloc (
2433                               sizeof (struct function_bounds) * sals.nelts);
2434   make_cleanup (xfree, func_bounds);
2435   for (i = 0; (i < sals.nelts && !found); i++)
2436     {
2437       if (sals.sals[i].pspace != current_program_space)
2438         func_bounds[i].low = func_bounds[i].high = 0;
2439       else if (sals.sals[i].pc == 0
2440                || find_pc_partial_function (sals.sals[i].pc, NULL,
2441                                             &func_bounds[i].low,
2442                                             &func_bounds[i].high) == 0)
2443         {
2444           func_bounds[i].low = func_bounds[i].high = 0;
2445         }
2446     }
2447
2448   do
2449     {
2450       for (i = 0; (i < sals.nelts && !found); i++)
2451         found = (get_frame_pc (frame) >= func_bounds[i].low
2452                  && get_frame_pc (frame) < func_bounds[i].high);
2453       if (!found)
2454         {
2455           level = 1;
2456           frame = find_relative_frame (frame, &level);
2457         }
2458     }
2459   while (!found && level == 0);
2460
2461   do_cleanups (cleanups);
2462
2463   if (!found)
2464     printf_filtered (_("'%s' not within current stack frame.\n"), arg);
2465   else if (frame != get_selected_frame (NULL))
2466     select_and_print_frame (frame);
2467 }
2468
2469 /* Gets the language of the current frame.  */
2470
2471 enum language
2472 get_frame_language (void)
2473 {
2474   struct frame_info *frame = deprecated_safe_get_selected_frame ();
2475
2476   if (frame)
2477     {
2478       volatile struct gdb_exception ex;
2479       CORE_ADDR pc = 0;
2480       struct symtab *s;
2481
2482       /* We determine the current frame language by looking up its
2483          associated symtab.  To retrieve this symtab, we use the frame
2484          PC.  However we cannot use the frame PC as is, because it
2485          usually points to the instruction following the "call", which
2486          is sometimes the first instruction of another function.  So
2487          we rely on get_frame_address_in_block(), it provides us with
2488          a PC that is guaranteed to be inside the frame's code
2489          block.  */
2490
2491       TRY_CATCH (ex, RETURN_MASK_ERROR)
2492         {
2493           pc = get_frame_address_in_block (frame);
2494         }
2495       if (ex.reason < 0)
2496         {
2497           if (ex.error != NOT_AVAILABLE_ERROR)
2498             throw_exception (ex);
2499         }
2500       else
2501         {
2502           s = find_pc_symtab (pc);
2503           if (s != NULL)
2504             return s->language;
2505         }
2506     }
2507
2508   return language_unknown;
2509 }
2510 \f
2511
2512 /* Provide a prototype to silence -Wmissing-prototypes.  */
2513 void _initialize_stack (void);
2514
2515 void
2516 _initialize_stack (void)
2517 {
2518   add_com ("return", class_stack, return_command, _("\
2519 Make selected stack frame return to its caller.\n\
2520 Control remains in the debugger, but when you continue\n\
2521 execution will resume in the frame above the one now selected.\n\
2522 If an argument is given, it is an expression for the value to return."));
2523
2524   add_com ("up", class_stack, up_command, _("\
2525 Select and print stack frame that called this one.\n\
2526 An argument says how many frames up to go."));
2527   add_com ("up-silently", class_support, up_silently_command, _("\
2528 Same as the `up' command, but does not print anything.\n\
2529 This is useful in command scripts."));
2530
2531   add_com ("down", class_stack, down_command, _("\
2532 Select and print stack frame called by this one.\n\
2533 An argument says how many frames down to go."));
2534   add_com_alias ("do", "down", class_stack, 1);
2535   add_com_alias ("dow", "down", class_stack, 1);
2536   add_com ("down-silently", class_support, down_silently_command, _("\
2537 Same as the `down' command, but does not print anything.\n\
2538 This is useful in command scripts."));
2539
2540   add_com ("frame", class_stack, frame_command, _("\
2541 Select and print a stack frame.\nWith no argument, \
2542 print the selected stack frame.  (See also \"info frame\").\n\
2543 An argument specifies the frame to select.\n\
2544 It can be a stack frame number or the address of the frame.\n\
2545 With argument, nothing is printed if input is coming from\n\
2546 a command file or a user-defined command."));
2547
2548   add_com_alias ("f", "frame", class_stack, 1);
2549
2550   if (xdb_commands)
2551     {
2552       add_com ("L", class_stack, current_frame_command,
2553                _("Print the current stack frame.\n"));
2554       add_com_alias ("V", "frame", class_stack, 1);
2555     }
2556   add_com ("select-frame", class_stack, select_frame_command, _("\
2557 Select a stack frame without printing anything.\n\
2558 An argument specifies the frame to select.\n\
2559 It can be a stack frame number or the address of the frame.\n"));
2560
2561   add_com ("backtrace", class_stack, backtrace_command, _("\
2562 Print backtrace of all stack frames, or innermost COUNT frames.\n\
2563 With a negative argument, print outermost -COUNT frames.\nUse of the \
2564 'full' qualifier also prints the values of the local variables.\n"));
2565   add_com_alias ("bt", "backtrace", class_stack, 0);
2566   if (xdb_commands)
2567     {
2568       add_com_alias ("t", "backtrace", class_stack, 0);
2569       add_com ("T", class_stack, backtrace_full_command, _("\
2570 Print backtrace of all stack frames, or innermost COUNT frames\n\
2571 and the values of the local variables.\n\
2572 With a negative argument, print outermost -COUNT frames.\n\
2573 Usage: T <count>\n"));
2574     }
2575
2576   add_com_alias ("where", "backtrace", class_alias, 0);
2577   add_info ("stack", backtrace_command,
2578             _("Backtrace of the stack, or innermost COUNT frames."));
2579   add_info_alias ("s", "stack", 1);
2580   add_info ("frame", frame_info,
2581             _("All about selected stack frame, or frame at ADDR."));
2582   add_info_alias ("f", "frame", 1);
2583   add_info ("locals", locals_info,
2584             _("Local variables of current stack frame."));
2585   add_info ("args", args_info,
2586             _("Argument variables of current stack frame."));
2587   if (xdb_commands)
2588     add_com ("l", class_info, args_plus_locals_info,
2589              _("Argument and local variables of current stack frame."));
2590
2591   if (dbx_commands)
2592     add_com ("func", class_stack, func_command, _("\
2593 Select the stack frame that contains <func>.\n\
2594 Usage: func <name>\n"));
2595
2596   add_setshow_enum_cmd ("frame-arguments", class_stack,
2597                         print_frame_arguments_choices, &print_frame_arguments,
2598                         _("Set printing of non-scalar frame arguments"),
2599                         _("Show printing of non-scalar frame arguments"),
2600                         NULL, NULL, NULL, &setprintlist, &showprintlist);
2601
2602   add_setshow_auto_boolean_cmd ("disassemble-next-line", class_stack,
2603                                 &disassemble_next_line, _("\
2604 Set whether to disassemble next source line or insn when execution stops."),
2605                                 _("\
2606 Show whether to disassemble next source line or insn when execution stops."),
2607                                 _("\
2608 If ON, GDB will display disassembly of the next source line, in addition\n\
2609 to displaying the source line itself.  If the next source line cannot\n\
2610 be displayed (e.g., source is unavailable or there's no line info), GDB\n\
2611 will display disassembly of next instruction instead of showing the\n\
2612 source line.\n\
2613 If AUTO, display disassembly of next instruction only if the source line\n\
2614 cannot be displayed.\n\
2615 If OFF (which is the default), never display the disassembly of the next\n\
2616 source line."),
2617                                 NULL,
2618                                 show_disassemble_next_line,
2619                                 &setlist, &showlist);
2620   disassemble_next_line = AUTO_BOOLEAN_FALSE;
2621
2622   add_setshow_enum_cmd ("entry-values", class_stack,
2623                         print_entry_values_choices, &print_entry_values,
2624                         _("Set printing of function arguments at function "
2625                           "entry"),
2626                         _("Show printing of function arguments at function "
2627                           "entry"),
2628                         _("\
2629 GDB can sometimes determine the values of function arguments at entry,\n\
2630 in addition to their current values.  This option tells GDB whether\n\
2631 to print the current value, the value at entry (marked as val@entry),\n\
2632 or both.  Note that one or both of these values may be <optimized out>."),
2633                         NULL, NULL, &setprintlist, &showprintlist);
2634 }