Use containers to avoid cleanups
[external/binutils.git] / gdb / printcmd.c
1 /* Print values for GNU debugger GDB.
2
3    Copyright (C) 1986-2017 Free Software Foundation, Inc.
4
5    This file is part of GDB.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19
20 #include "defs.h"
21 #include "frame.h"
22 #include "symtab.h"
23 #include "gdbtypes.h"
24 #include "value.h"
25 #include "language.h"
26 #include "expression.h"
27 #include "gdbcore.h"
28 #include "gdbcmd.h"
29 #include "target.h"
30 #include "breakpoint.h"
31 #include "demangle.h"
32 #include "gdb-demangle.h"
33 #include "valprint.h"
34 #include "annotate.h"
35 #include "symfile.h"            /* for overlay functions */
36 #include "objfiles.h"           /* ditto */
37 #include "completer.h"          /* for completion functions */
38 #include "ui-out.h"
39 #include "block.h"
40 #include "disasm.h"
41 #include "dfp.h"
42 #include "observer.h"
43 #include "solist.h"
44 #include "parser-defs.h"
45 #include "charset.h"
46 #include "arch-utils.h"
47 #include "cli/cli-utils.h"
48 #include "cli/cli-script.h"
49 #include "format.h"
50 #include "source.h"
51 #include "common/byte-vector.h"
52
53 #ifdef TUI
54 #include "tui/tui.h"            /* For tui_active et al.   */
55 #endif
56
57 /* Last specified output format.  */
58
59 static char last_format = 0;
60
61 /* Last specified examination size.  'b', 'h', 'w' or `q'.  */
62
63 static char last_size = 'w';
64
65 /* Default address to examine next, and associated architecture.  */
66
67 static struct gdbarch *next_gdbarch;
68 static CORE_ADDR next_address;
69
70 /* Number of delay instructions following current disassembled insn.  */
71
72 static int branch_delay_insns;
73
74 /* Last address examined.  */
75
76 static CORE_ADDR last_examine_address;
77
78 /* Contents of last address examined.
79    This is not valid past the end of the `x' command!  */
80
81 static struct value *last_examine_value;
82
83 /* Largest offset between a symbolic value and an address, that will be
84    printed as `0x1234 <symbol+offset>'.  */
85
86 static unsigned int max_symbolic_offset = UINT_MAX;
87 static void
88 show_max_symbolic_offset (struct ui_file *file, int from_tty,
89                           struct cmd_list_element *c, const char *value)
90 {
91   fprintf_filtered (file,
92                     _("The largest offset that will be "
93                       "printed in <symbol+1234> form is %s.\n"),
94                     value);
95 }
96
97 /* Append the source filename and linenumber of the symbol when
98    printing a symbolic value as `<symbol at filename:linenum>' if set.  */
99 static int print_symbol_filename = 0;
100 static void
101 show_print_symbol_filename (struct ui_file *file, int from_tty,
102                             struct cmd_list_element *c, const char *value)
103 {
104   fprintf_filtered (file, _("Printing of source filename and "
105                             "line number with <symbol> is %s.\n"),
106                     value);
107 }
108
109 /* Number of auto-display expression currently being displayed.
110    So that we can disable it if we get a signal within it.
111    -1 when not doing one.  */
112
113 static int current_display_number;
114
115 struct display
116   {
117     /* Chain link to next auto-display item.  */
118     struct display *next;
119
120     /* The expression as the user typed it.  */
121     char *exp_string;
122
123     /* Expression to be evaluated and displayed.  */
124     expression_up exp;
125
126     /* Item number of this auto-display item.  */
127     int number;
128
129     /* Display format specified.  */
130     struct format_data format;
131
132     /* Program space associated with `block'.  */
133     struct program_space *pspace;
134
135     /* Innermost block required by this expression when evaluated.  */
136     const struct block *block;
137
138     /* Status of this display (enabled or disabled).  */
139     int enabled_p;
140   };
141
142 /* Chain of expressions whose values should be displayed
143    automatically each time the program stops.  */
144
145 static struct display *display_chain;
146
147 static int display_number;
148
149 /* Walk the following statement or block through all displays.
150    ALL_DISPLAYS_SAFE does so even if the statement deletes the current
151    display.  */
152
153 #define ALL_DISPLAYS(B)                         \
154   for (B = display_chain; B; B = B->next)
155
156 #define ALL_DISPLAYS_SAFE(B,TMP)                \
157   for (B = display_chain;                       \
158        B ? (TMP = B->next, 1): 0;               \
159        B = TMP)
160
161 /* Prototypes for exported functions.  */
162
163 void _initialize_printcmd (void);
164
165 /* Prototypes for local functions.  */
166
167 static void do_one_display (struct display *);
168 \f
169
170 /* Decode a format specification.  *STRING_PTR should point to it.
171    OFORMAT and OSIZE are used as defaults for the format and size
172    if none are given in the format specification.
173    If OSIZE is zero, then the size field of the returned value
174    should be set only if a size is explicitly specified by the
175    user.
176    The structure returned describes all the data
177    found in the specification.  In addition, *STRING_PTR is advanced
178    past the specification and past all whitespace following it.  */
179
180 static struct format_data
181 decode_format (const char **string_ptr, int oformat, int osize)
182 {
183   struct format_data val;
184   const char *p = *string_ptr;
185
186   val.format = '?';
187   val.size = '?';
188   val.count = 1;
189   val.raw = 0;
190
191   if (*p == '-')
192     {
193       val.count = -1;
194       p++;
195     }
196   if (*p >= '0' && *p <= '9')
197     val.count *= atoi (p);
198   while (*p >= '0' && *p <= '9')
199     p++;
200
201   /* Now process size or format letters that follow.  */
202
203   while (1)
204     {
205       if (*p == 'b' || *p == 'h' || *p == 'w' || *p == 'g')
206         val.size = *p++;
207       else if (*p == 'r')
208         {
209           val.raw = 1;
210           p++;
211         }
212       else if (*p >= 'a' && *p <= 'z')
213         val.format = *p++;
214       else
215         break;
216     }
217
218   while (*p == ' ' || *p == '\t')
219     p++;
220   *string_ptr = p;
221
222   /* Set defaults for format and size if not specified.  */
223   if (val.format == '?')
224     {
225       if (val.size == '?')
226         {
227           /* Neither has been specified.  */
228           val.format = oformat;
229           val.size = osize;
230         }
231       else
232         /* If a size is specified, any format makes a reasonable
233            default except 'i'.  */
234         val.format = oformat == 'i' ? 'x' : oformat;
235     }
236   else if (val.size == '?')
237     switch (val.format)
238       {
239       case 'a':
240         /* Pick the appropriate size for an address.  This is deferred
241            until do_examine when we know the actual architecture to use.
242            A special size value of 'a' is used to indicate this case.  */
243         val.size = osize ? 'a' : osize;
244         break;
245       case 'f':
246         /* Floating point has to be word or giantword.  */
247         if (osize == 'w' || osize == 'g')
248           val.size = osize;
249         else
250           /* Default it to giantword if the last used size is not
251              appropriate.  */
252           val.size = osize ? 'g' : osize;
253         break;
254       case 'c':
255         /* Characters default to one byte.  */
256         val.size = osize ? 'b' : osize;
257         break;
258       case 's':
259         /* Display strings with byte size chars unless explicitly
260            specified.  */
261         val.size = '\0';
262         break;
263
264       default:
265         /* The default is the size most recently specified.  */
266         val.size = osize;
267       }
268
269   return val;
270 }
271 \f
272 /* Print value VAL on stream according to OPTIONS.
273    Do not end with a newline.
274    SIZE is the letter for the size of datum being printed.
275    This is used to pad hex numbers so they line up.  SIZE is 0
276    for print / output and set for examine.  */
277
278 static void
279 print_formatted (struct value *val, int size,
280                  const struct value_print_options *options,
281                  struct ui_file *stream)
282 {
283   struct type *type = check_typedef (value_type (val));
284   int len = TYPE_LENGTH (type);
285
286   if (VALUE_LVAL (val) == lval_memory)
287     next_address = value_address (val) + len;
288
289   if (size)
290     {
291       switch (options->format)
292         {
293         case 's':
294           {
295             struct type *elttype = value_type (val);
296
297             next_address = (value_address (val)
298                             + val_print_string (elttype, NULL,
299                                                 value_address (val), -1,
300                                                 stream, options) * len);
301           }
302           return;
303
304         case 'i':
305           /* We often wrap here if there are long symbolic names.  */
306           wrap_here ("    ");
307           next_address = (value_address (val)
308                           + gdb_print_insn (get_type_arch (type),
309                                             value_address (val), stream,
310                                             &branch_delay_insns));
311           return;
312         }
313     }
314
315   if (options->format == 0 || options->format == 's'
316       || TYPE_CODE (type) == TYPE_CODE_REF
317       || TYPE_CODE (type) == TYPE_CODE_ARRAY
318       || TYPE_CODE (type) == TYPE_CODE_STRING
319       || TYPE_CODE (type) == TYPE_CODE_STRUCT
320       || TYPE_CODE (type) == TYPE_CODE_UNION
321       || TYPE_CODE (type) == TYPE_CODE_NAMESPACE)
322     value_print (val, stream, options);
323   else
324     /* User specified format, so don't look to the type to tell us
325        what to do.  */
326     val_print_scalar_formatted (type,
327                                 value_embedded_offset (val),
328                                 val,
329                                 options, size, stream);
330 }
331
332 /* Return builtin floating point type of same length as TYPE.
333    If no such type is found, return TYPE itself.  */
334 static struct type *
335 float_type_from_length (struct type *type)
336 {
337   struct gdbarch *gdbarch = get_type_arch (type);
338   const struct builtin_type *builtin = builtin_type (gdbarch);
339
340   if (TYPE_LENGTH (type) == TYPE_LENGTH (builtin->builtin_float))
341     type = builtin->builtin_float;
342   else if (TYPE_LENGTH (type) == TYPE_LENGTH (builtin->builtin_double))
343     type = builtin->builtin_double;
344   else if (TYPE_LENGTH (type) == TYPE_LENGTH (builtin->builtin_long_double))
345     type = builtin->builtin_long_double;
346
347   return type;
348 }
349
350 /* Print a scalar of data of type TYPE, pointed to in GDB by VALADDR,
351    according to OPTIONS and SIZE on STREAM.  Formats s and i are not
352    supported at this level.  */
353
354 void
355 print_scalar_formatted (const gdb_byte *valaddr, struct type *type,
356                         const struct value_print_options *options,
357                         int size, struct ui_file *stream)
358 {
359   struct gdbarch *gdbarch = get_type_arch (type);
360   unsigned int len = TYPE_LENGTH (type);
361   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
362
363   /* String printing should go through val_print_scalar_formatted.  */
364   gdb_assert (options->format != 's');
365
366   /* If the value is a pointer, and pointers and addresses are not the
367      same, then at this point, the value's length (in target bytes) is
368      gdbarch_addr_bit/TARGET_CHAR_BIT, not TYPE_LENGTH (type).  */
369   if (TYPE_CODE (type) == TYPE_CODE_PTR)
370     len = gdbarch_addr_bit (gdbarch) / TARGET_CHAR_BIT;
371
372   /* If we are printing it as unsigned, truncate it in case it is actually
373      a negative signed value (e.g. "print/u (short)-1" should print 65535
374      (if shorts are 16 bits) instead of 4294967295).  */
375   if (options->format != 'c'
376       && (options->format != 'd' || TYPE_UNSIGNED (type)))
377     {
378       if (len < TYPE_LENGTH (type) && byte_order == BFD_ENDIAN_BIG)
379         valaddr += TYPE_LENGTH (type) - len;
380     }
381
382   if (size != 0 && (options->format == 'x' || options->format == 't'))
383     {
384       /* Truncate to fit.  */
385       unsigned newlen;
386       switch (size)
387         {
388         case 'b':
389           newlen = 1;
390           break;
391         case 'h':
392           newlen = 2;
393           break;
394         case 'w':
395           newlen = 4;
396           break;
397         case 'g':
398           newlen = 8;
399           break;
400         default:
401           error (_("Undefined output size \"%c\"."), size);
402         }
403       if (newlen < len && byte_order == BFD_ENDIAN_BIG)
404         valaddr += len - newlen;
405       len = newlen;
406     }
407
408   /* Historically gdb has printed floats by first casting them to a
409      long, and then printing the long.  PR cli/16242 suggests changing
410      this to using C-style hex float format.  */
411   gdb::byte_vector converted_float_bytes;
412   if (TYPE_CODE (type) == TYPE_CODE_FLT
413       && (options->format == 'o'
414           || options->format == 'x'
415           || options->format == 't'
416           || options->format == 'z'))
417     {
418       LONGEST val_long = unpack_long (type, valaddr);
419       converted_float_bytes.resize (TYPE_LENGTH (type));
420       store_signed_integer (converted_float_bytes.data (), TYPE_LENGTH (type),
421                             byte_order, val_long);
422       valaddr = converted_float_bytes.data ();
423     }
424
425   switch (options->format)
426     {
427     case 'o':
428       print_octal_chars (stream, valaddr, len, byte_order);
429       break;
430     case 'u':
431       print_decimal_chars (stream, valaddr, len, false, byte_order);
432       break;
433     case 0:
434     case 'd':
435       if (TYPE_CODE (type) != TYPE_CODE_FLT)
436         {
437           print_decimal_chars (stream, valaddr, len, !TYPE_UNSIGNED (type),
438                                byte_order);
439           break;
440         }
441       /* FALLTHROUGH */
442     case 'f':
443       type = float_type_from_length (type);
444       print_floating (valaddr, type, stream);
445       break;
446
447     case 't':
448       print_binary_chars (stream, valaddr, len, byte_order, size > 0);
449       break;
450     case 'x':
451       print_hex_chars (stream, valaddr, len, byte_order, size > 0);
452       break;
453     case 'z':
454       print_hex_chars (stream, valaddr, len, byte_order, true);
455       break;
456     case 'c':
457       {
458         struct value_print_options opts = *options;
459
460         LONGEST val_long = unpack_long (type, valaddr);
461
462         opts.format = 0;
463         if (TYPE_UNSIGNED (type))
464           type = builtin_type (gdbarch)->builtin_true_unsigned_char;
465         else
466           type = builtin_type (gdbarch)->builtin_true_char;
467
468         value_print (value_from_longest (type, val_long), stream, &opts);
469       }
470       break;
471
472     case 'a':
473       {
474         CORE_ADDR addr = unpack_pointer (type, valaddr);
475
476         print_address (gdbarch, addr, stream);
477       }
478       break;
479
480     default:
481       error (_("Undefined output format \"%c\"."), options->format);
482     }
483 }
484
485 /* Specify default address for `x' command.
486    The `info lines' command uses this.  */
487
488 void
489 set_next_address (struct gdbarch *gdbarch, CORE_ADDR addr)
490 {
491   struct type *ptr_type = builtin_type (gdbarch)->builtin_data_ptr;
492
493   next_gdbarch = gdbarch;
494   next_address = addr;
495
496   /* Make address available to the user as $_.  */
497   set_internalvar (lookup_internalvar ("_"),
498                    value_from_pointer (ptr_type, addr));
499 }
500
501 /* Optionally print address ADDR symbolically as <SYMBOL+OFFSET> on STREAM,
502    after LEADIN.  Print nothing if no symbolic name is found nearby.
503    Optionally also print source file and line number, if available.
504    DO_DEMANGLE controls whether to print a symbol in its native "raw" form,
505    or to interpret it as a possible C++ name and convert it back to source
506    form.  However note that DO_DEMANGLE can be overridden by the specific
507    settings of the demangle and asm_demangle variables.  Returns
508    non-zero if anything was printed; zero otherwise.  */
509
510 int
511 print_address_symbolic (struct gdbarch *gdbarch, CORE_ADDR addr,
512                         struct ui_file *stream,
513                         int do_demangle, const char *leadin)
514 {
515   char *name = NULL;
516   char *filename = NULL;
517   int unmapped = 0;
518   int offset = 0;
519   int line = 0;
520
521   /* Throw away both name and filename.  */
522   struct cleanup *cleanup_chain = make_cleanup (free_current_contents, &name);
523   make_cleanup (free_current_contents, &filename);
524
525   if (build_address_symbolic (gdbarch, addr, do_demangle, &name, &offset,
526                               &filename, &line, &unmapped))
527     {
528       do_cleanups (cleanup_chain);
529       return 0;
530     }
531
532   fputs_filtered (leadin, stream);
533   if (unmapped)
534     fputs_filtered ("<*", stream);
535   else
536     fputs_filtered ("<", stream);
537   fputs_filtered (name, stream);
538   if (offset != 0)
539     fprintf_filtered (stream, "+%u", (unsigned int) offset);
540
541   /* Append source filename and line number if desired.  Give specific
542      line # of this addr, if we have it; else line # of the nearest symbol.  */
543   if (print_symbol_filename && filename != NULL)
544     {
545       if (line != -1)
546         fprintf_filtered (stream, " at %s:%d", filename, line);
547       else
548         fprintf_filtered (stream, " in %s", filename);
549     }
550   if (unmapped)
551     fputs_filtered ("*>", stream);
552   else
553     fputs_filtered (">", stream);
554
555   do_cleanups (cleanup_chain);
556   return 1;
557 }
558
559 /* Given an address ADDR return all the elements needed to print the
560    address in a symbolic form.  NAME can be mangled or not depending
561    on DO_DEMANGLE (and also on the asm_demangle global variable,
562    manipulated via ''set print asm-demangle'').  Return 0 in case of
563    success, when all the info in the OUT paramters is valid.  Return 1
564    otherwise.  */
565 int
566 build_address_symbolic (struct gdbarch *gdbarch,
567                         CORE_ADDR addr,  /* IN */
568                         int do_demangle, /* IN */
569                         char **name,     /* OUT */
570                         int *offset,     /* OUT */
571                         char **filename, /* OUT */
572                         int *line,       /* OUT */
573                         int *unmapped)   /* OUT */
574 {
575   struct bound_minimal_symbol msymbol;
576   struct symbol *symbol;
577   CORE_ADDR name_location = 0;
578   struct obj_section *section = NULL;
579   const char *name_temp = "";
580   
581   /* Let's say it is mapped (not unmapped).  */
582   *unmapped = 0;
583
584   /* Determine if the address is in an overlay, and whether it is
585      mapped.  */
586   if (overlay_debugging)
587     {
588       section = find_pc_overlay (addr);
589       if (pc_in_unmapped_range (addr, section))
590         {
591           *unmapped = 1;
592           addr = overlay_mapped_address (addr, section);
593         }
594     }
595
596   /* First try to find the address in the symbol table, then
597      in the minsyms.  Take the closest one.  */
598
599   /* This is defective in the sense that it only finds text symbols.  So
600      really this is kind of pointless--we should make sure that the
601      minimal symbols have everything we need (by changing that we could
602      save some memory, but for many debug format--ELF/DWARF or
603      anything/stabs--it would be inconvenient to eliminate those minimal
604      symbols anyway).  */
605   msymbol = lookup_minimal_symbol_by_pc_section (addr, section);
606   symbol = find_pc_sect_function (addr, section);
607
608   if (symbol)
609     {
610       /* If this is a function (i.e. a code address), strip out any
611          non-address bits.  For instance, display a pointer to the
612          first instruction of a Thumb function as <function>; the
613          second instruction will be <function+2>, even though the
614          pointer is <function+3>.  This matches the ISA behavior.  */
615       addr = gdbarch_addr_bits_remove (gdbarch, addr);
616
617       name_location = BLOCK_START (SYMBOL_BLOCK_VALUE (symbol));
618       if (do_demangle || asm_demangle)
619         name_temp = SYMBOL_PRINT_NAME (symbol);
620       else
621         name_temp = SYMBOL_LINKAGE_NAME (symbol);
622     }
623
624   if (msymbol.minsym != NULL
625       && MSYMBOL_HAS_SIZE (msymbol.minsym)
626       && MSYMBOL_SIZE (msymbol.minsym) == 0
627       && MSYMBOL_TYPE (msymbol.minsym) != mst_text
628       && MSYMBOL_TYPE (msymbol.minsym) != mst_text_gnu_ifunc
629       && MSYMBOL_TYPE (msymbol.minsym) != mst_file_text)
630     msymbol.minsym = NULL;
631
632   if (msymbol.minsym != NULL)
633     {
634       if (BMSYMBOL_VALUE_ADDRESS (msymbol) > name_location || symbol == NULL)
635         {
636           /* If this is a function (i.e. a code address), strip out any
637              non-address bits.  For instance, display a pointer to the
638              first instruction of a Thumb function as <function>; the
639              second instruction will be <function+2>, even though the
640              pointer is <function+3>.  This matches the ISA behavior.  */
641           if (MSYMBOL_TYPE (msymbol.minsym) == mst_text
642               || MSYMBOL_TYPE (msymbol.minsym) == mst_text_gnu_ifunc
643               || MSYMBOL_TYPE (msymbol.minsym) == mst_file_text
644               || MSYMBOL_TYPE (msymbol.minsym) == mst_solib_trampoline)
645             addr = gdbarch_addr_bits_remove (gdbarch, addr);
646
647           /* The msymbol is closer to the address than the symbol;
648              use the msymbol instead.  */
649           symbol = 0;
650           name_location = BMSYMBOL_VALUE_ADDRESS (msymbol);
651           if (do_demangle || asm_demangle)
652             name_temp = MSYMBOL_PRINT_NAME (msymbol.minsym);
653           else
654             name_temp = MSYMBOL_LINKAGE_NAME (msymbol.minsym);
655         }
656     }
657   if (symbol == NULL && msymbol.minsym == NULL)
658     return 1;
659
660   /* If the nearest symbol is too far away, don't print anything symbolic.  */
661
662   /* For when CORE_ADDR is larger than unsigned int, we do math in
663      CORE_ADDR.  But when we detect unsigned wraparound in the
664      CORE_ADDR math, we ignore this test and print the offset,
665      because addr+max_symbolic_offset has wrapped through the end
666      of the address space back to the beginning, giving bogus comparison.  */
667   if (addr > name_location + max_symbolic_offset
668       && name_location + max_symbolic_offset > name_location)
669     return 1;
670
671   *offset = addr - name_location;
672
673   *name = xstrdup (name_temp);
674
675   if (print_symbol_filename)
676     {
677       struct symtab_and_line sal;
678
679       sal = find_pc_sect_line (addr, section, 0);
680
681       if (sal.symtab)
682         {
683           *filename = xstrdup (symtab_to_filename_for_display (sal.symtab));
684           *line = sal.line;
685         }
686     }
687   return 0;
688 }
689
690
691 /* Print address ADDR symbolically on STREAM.
692    First print it as a number.  Then perhaps print
693    <SYMBOL + OFFSET> after the number.  */
694
695 void
696 print_address (struct gdbarch *gdbarch,
697                CORE_ADDR addr, struct ui_file *stream)
698 {
699   fputs_filtered (paddress (gdbarch, addr), stream);
700   print_address_symbolic (gdbarch, addr, stream, asm_demangle, " ");
701 }
702
703 /* Return a prefix for instruction address:
704    "=> " for current instruction, else "   ".  */
705
706 const char *
707 pc_prefix (CORE_ADDR addr)
708 {
709   if (has_stack_frames ())
710     {
711       struct frame_info *frame;
712       CORE_ADDR pc;
713
714       frame = get_selected_frame (NULL);
715       if (get_frame_pc_if_available (frame, &pc) && pc == addr)
716         return "=> ";
717     }
718   return "   ";
719 }
720
721 /* Print address ADDR symbolically on STREAM.  Parameter DEMANGLE
722    controls whether to print the symbolic name "raw" or demangled.
723    Return non-zero if anything was printed; zero otherwise.  */
724
725 int
726 print_address_demangle (const struct value_print_options *opts,
727                         struct gdbarch *gdbarch, CORE_ADDR addr,
728                         struct ui_file *stream, int do_demangle)
729 {
730   if (opts->addressprint)
731     {
732       fputs_filtered (paddress (gdbarch, addr), stream);
733       print_address_symbolic (gdbarch, addr, stream, do_demangle, " ");
734     }
735   else
736     {
737       return print_address_symbolic (gdbarch, addr, stream, do_demangle, "");
738     }
739   return 1;
740 }
741 \f
742
743 /* Find the address of the instruction that is INST_COUNT instructions before
744    the instruction at ADDR.
745    Since some architectures have variable-length instructions, we can't just
746    simply subtract INST_COUNT * INSN_LEN from ADDR.  Instead, we use line
747    number information to locate the nearest known instruction boundary,
748    and disassemble forward from there.  If we go out of the symbol range
749    during disassembling, we return the lowest address we've got so far and
750    set the number of instructions read to INST_READ.  */
751
752 static CORE_ADDR
753 find_instruction_backward (struct gdbarch *gdbarch, CORE_ADDR addr,
754                            int inst_count, int *inst_read)
755 {
756   /* The vector PCS is used to store instruction addresses within
757      a pc range.  */
758   CORE_ADDR loop_start, loop_end, p;
759   std::vector<CORE_ADDR> pcs;
760   struct symtab_and_line sal;
761
762   *inst_read = 0;
763   loop_start = loop_end = addr;
764
765   /* In each iteration of the outer loop, we get a pc range that ends before
766      LOOP_START, then we count and store every instruction address of the range
767      iterated in the loop.
768      If the number of instructions counted reaches INST_COUNT, return the
769      stored address that is located INST_COUNT instructions back from ADDR.
770      If INST_COUNT is not reached, we subtract the number of counted
771      instructions from INST_COUNT, and go to the next iteration.  */
772   do
773     {
774       pcs.clear ();
775       sal = find_pc_sect_line (loop_start, NULL, 1);
776       if (sal.line <= 0)
777         {
778           /* We reach here when line info is not available.  In this case,
779              we print a message and just exit the loop.  The return value
780              is calculated after the loop.  */
781           printf_filtered (_("No line number information available "
782                              "for address "));
783           wrap_here ("  ");
784           print_address (gdbarch, loop_start - 1, gdb_stdout);
785           printf_filtered ("\n");
786           break;
787         }
788
789       loop_end = loop_start;
790       loop_start = sal.pc;
791
792       /* This loop pushes instruction addresses in the range from
793          LOOP_START to LOOP_END.  */
794       for (p = loop_start; p < loop_end;)
795         {
796           pcs.push_back (p);
797           p += gdb_insn_length (gdbarch, p);
798         }
799
800       inst_count -= pcs.size ();
801       *inst_read += pcs.size ();
802     }
803   while (inst_count > 0);
804
805   /* After the loop, the vector PCS has instruction addresses of the last
806      source line we processed, and INST_COUNT has a negative value.
807      We return the address at the index of -INST_COUNT in the vector for
808      the reason below.
809      Let's assume the following instruction addresses and run 'x/-4i 0x400e'.
810        Line X of File
811           0x4000
812           0x4001
813           0x4005
814        Line Y of File
815           0x4009
816           0x400c
817        => 0x400e
818           0x4011
819      find_instruction_backward is called with INST_COUNT = 4 and expected to
820      return 0x4001.  When we reach here, INST_COUNT is set to -1 because
821      it was subtracted by 2 (from Line Y) and 3 (from Line X).  The value
822      4001 is located at the index 1 of the last iterated line (= Line X),
823      which is simply calculated by -INST_COUNT.
824      The case when the length of PCS is 0 means that we reached an area for
825      which line info is not available.  In such case, we return LOOP_START,
826      which was the lowest instruction address that had line info.  */
827   p = pcs.size () > 0 ? pcs[-inst_count] : loop_start;
828
829   /* INST_READ includes all instruction addresses in a pc range.  Need to
830      exclude the beginning part up to the address we're returning.  That
831      is, exclude {0x4000} in the example above.  */
832   if (inst_count < 0)
833     *inst_read += inst_count;
834
835   return p;
836 }
837
838 /* Backward read LEN bytes of target memory from address MEMADDR + LEN,
839    placing the results in GDB's memory from MYADDR + LEN.  Returns
840    a count of the bytes actually read.  */
841
842 static int
843 read_memory_backward (struct gdbarch *gdbarch,
844                       CORE_ADDR memaddr, gdb_byte *myaddr, int len)
845 {
846   int errcode;
847   int nread;      /* Number of bytes actually read.  */
848
849   /* First try a complete read.  */
850   errcode = target_read_memory (memaddr, myaddr, len);
851   if (errcode == 0)
852     {
853       /* Got it all.  */
854       nread = len;
855     }
856   else
857     {
858       /* Loop, reading one byte at a time until we get as much as we can.  */
859       memaddr += len;
860       myaddr += len;
861       for (nread = 0; nread < len; ++nread)
862         {
863           errcode = target_read_memory (--memaddr, --myaddr, 1);
864           if (errcode != 0)
865             {
866               /* The read was unsuccessful, so exit the loop.  */
867               printf_filtered (_("Cannot access memory at address %s\n"),
868                                paddress (gdbarch, memaddr));
869               break;
870             }
871         }
872     }
873   return nread;
874 }
875
876 /* Returns true if X (which is LEN bytes wide) is the number zero.  */
877
878 static int
879 integer_is_zero (const gdb_byte *x, int len)
880 {
881   int i = 0;
882
883   while (i < len && x[i] == 0)
884     ++i;
885   return (i == len);
886 }
887
888 /* Find the start address of a string in which ADDR is included.
889    Basically we search for '\0' and return the next address,
890    but if OPTIONS->PRINT_MAX is smaller than the length of a string,
891    we stop searching and return the address to print characters as many as
892    PRINT_MAX from the string.  */
893
894 static CORE_ADDR
895 find_string_backward (struct gdbarch *gdbarch,
896                       CORE_ADDR addr, int count, int char_size,
897                       const struct value_print_options *options,
898                       int *strings_counted)
899 {
900   const int chunk_size = 0x20;
901   int read_error = 0;
902   int chars_read = 0;
903   int chars_to_read = chunk_size;
904   int chars_counted = 0;
905   int count_original = count;
906   CORE_ADDR string_start_addr = addr;
907
908   gdb_assert (char_size == 1 || char_size == 2 || char_size == 4);
909   gdb::byte_vector buffer (chars_to_read * char_size);
910   while (count > 0 && read_error == 0)
911     {
912       int i;
913
914       addr -= chars_to_read * char_size;
915       chars_read = read_memory_backward (gdbarch, addr, buffer.data (),
916                                          chars_to_read * char_size);
917       chars_read /= char_size;
918       read_error = (chars_read == chars_to_read) ? 0 : 1;
919       /* Searching for '\0' from the end of buffer in backward direction.  */
920       for (i = 0; i < chars_read && count > 0 ; ++i, ++chars_counted)
921         {
922           int offset = (chars_to_read - i - 1) * char_size;
923
924           if (integer_is_zero (&buffer[offset], char_size)
925               || chars_counted == options->print_max)
926             {
927               /* Found '\0' or reached print_max.  As OFFSET is the offset to
928                  '\0', we add CHAR_SIZE to return the start address of
929                  a string.  */
930               --count;
931               string_start_addr = addr + offset + char_size;
932               chars_counted = 0;
933             }
934         }
935     }
936
937   /* Update STRINGS_COUNTED with the actual number of loaded strings.  */
938   *strings_counted = count_original - count;
939
940   if (read_error != 0)
941     {
942       /* In error case, STRING_START_ADDR is pointing to the string that
943          was last successfully loaded.  Rewind the partially loaded string.  */
944       string_start_addr -= chars_counted * char_size;
945     }
946
947   return string_start_addr;
948 }
949
950 /* Examine data at address ADDR in format FMT.
951    Fetch it from memory and print on gdb_stdout.  */
952
953 static void
954 do_examine (struct format_data fmt, struct gdbarch *gdbarch, CORE_ADDR addr)
955 {
956   char format = 0;
957   char size;
958   int count = 1;
959   struct type *val_type = NULL;
960   int i;
961   int maxelts;
962   struct value_print_options opts;
963   int need_to_update_next_address = 0;
964   CORE_ADDR addr_rewound = 0;
965
966   format = fmt.format;
967   size = fmt.size;
968   count = fmt.count;
969   next_gdbarch = gdbarch;
970   next_address = addr;
971
972   /* Instruction format implies fetch single bytes
973      regardless of the specified size.
974      The case of strings is handled in decode_format, only explicit
975      size operator are not changed to 'b'.  */
976   if (format == 'i')
977     size = 'b';
978
979   if (size == 'a')
980     {
981       /* Pick the appropriate size for an address.  */
982       if (gdbarch_ptr_bit (next_gdbarch) == 64)
983         size = 'g';
984       else if (gdbarch_ptr_bit (next_gdbarch) == 32)
985         size = 'w';
986       else if (gdbarch_ptr_bit (next_gdbarch) == 16)
987         size = 'h';
988       else
989         /* Bad value for gdbarch_ptr_bit.  */
990         internal_error (__FILE__, __LINE__,
991                         _("failed internal consistency check"));
992     }
993
994   if (size == 'b')
995     val_type = builtin_type (next_gdbarch)->builtin_int8;
996   else if (size == 'h')
997     val_type = builtin_type (next_gdbarch)->builtin_int16;
998   else if (size == 'w')
999     val_type = builtin_type (next_gdbarch)->builtin_int32;
1000   else if (size == 'g')
1001     val_type = builtin_type (next_gdbarch)->builtin_int64;
1002
1003   if (format == 's')
1004     {
1005       struct type *char_type = NULL;
1006
1007       /* Search for "char16_t"  or "char32_t" types or fall back to 8-bit char
1008          if type is not found.  */
1009       if (size == 'h')
1010         char_type = builtin_type (next_gdbarch)->builtin_char16;
1011       else if (size == 'w')
1012         char_type = builtin_type (next_gdbarch)->builtin_char32;
1013       if (char_type)
1014         val_type = char_type;
1015       else
1016         {
1017           if (size != '\0' && size != 'b')
1018             warning (_("Unable to display strings with "
1019                        "size '%c', using 'b' instead."), size);
1020           size = 'b';
1021           val_type = builtin_type (next_gdbarch)->builtin_int8;
1022         }
1023     }
1024
1025   maxelts = 8;
1026   if (size == 'w')
1027     maxelts = 4;
1028   if (size == 'g')
1029     maxelts = 2;
1030   if (format == 's' || format == 'i')
1031     maxelts = 1;
1032
1033   get_formatted_print_options (&opts, format);
1034
1035   if (count < 0)
1036     {
1037       /* This is the negative repeat count case.
1038          We rewind the address based on the given repeat count and format,
1039          then examine memory from there in forward direction.  */
1040
1041       count = -count;
1042       if (format == 'i')
1043         {
1044           next_address = find_instruction_backward (gdbarch, addr, count,
1045                                                     &count);
1046         }
1047       else if (format == 's')
1048         {
1049           next_address = find_string_backward (gdbarch, addr, count,
1050                                                TYPE_LENGTH (val_type),
1051                                                &opts, &count);
1052         }
1053       else
1054         {
1055           next_address = addr - count * TYPE_LENGTH (val_type);
1056         }
1057
1058       /* The following call to print_formatted updates next_address in every
1059          iteration.  In backward case, we store the start address here
1060          and update next_address with it before exiting the function.  */
1061       addr_rewound = (format == 's'
1062                       ? next_address - TYPE_LENGTH (val_type)
1063                       : next_address);
1064       need_to_update_next_address = 1;
1065     }
1066
1067   /* Print as many objects as specified in COUNT, at most maxelts per line,
1068      with the address of the next one at the start of each line.  */
1069
1070   while (count > 0)
1071     {
1072       QUIT;
1073       if (format == 'i')
1074         fputs_filtered (pc_prefix (next_address), gdb_stdout);
1075       print_address (next_gdbarch, next_address, gdb_stdout);
1076       printf_filtered (":");
1077       for (i = maxelts;
1078            i > 0 && count > 0;
1079            i--, count--)
1080         {
1081           printf_filtered ("\t");
1082           /* Note that print_formatted sets next_address for the next
1083              object.  */
1084           last_examine_address = next_address;
1085
1086           if (last_examine_value)
1087             value_free (last_examine_value);
1088
1089           /* The value to be displayed is not fetched greedily.
1090              Instead, to avoid the possibility of a fetched value not
1091              being used, its retrieval is delayed until the print code
1092              uses it.  When examining an instruction stream, the
1093              disassembler will perform its own memory fetch using just
1094              the address stored in LAST_EXAMINE_VALUE.  FIXME: Should
1095              the disassembler be modified so that LAST_EXAMINE_VALUE
1096              is left with the byte sequence from the last complete
1097              instruction fetched from memory?  */
1098           last_examine_value = value_at_lazy (val_type, next_address);
1099
1100           if (last_examine_value)
1101             release_value (last_examine_value);
1102
1103           print_formatted (last_examine_value, size, &opts, gdb_stdout);
1104
1105           /* Display any branch delay slots following the final insn.  */
1106           if (format == 'i' && count == 1)
1107             count += branch_delay_insns;
1108         }
1109       printf_filtered ("\n");
1110       gdb_flush (gdb_stdout);
1111     }
1112
1113   if (need_to_update_next_address)
1114     next_address = addr_rewound;
1115 }
1116 \f
1117 static void
1118 validate_format (struct format_data fmt, const char *cmdname)
1119 {
1120   if (fmt.size != 0)
1121     error (_("Size letters are meaningless in \"%s\" command."), cmdname);
1122   if (fmt.count != 1)
1123     error (_("Item count other than 1 is meaningless in \"%s\" command."),
1124            cmdname);
1125   if (fmt.format == 'i')
1126     error (_("Format letter \"%c\" is meaningless in \"%s\" command."),
1127            fmt.format, cmdname);
1128 }
1129
1130 /* Parse print command format string into *FMTP and update *EXPP.
1131    CMDNAME should name the current command.  */
1132
1133 void
1134 print_command_parse_format (const char **expp, const char *cmdname,
1135                             struct format_data *fmtp)
1136 {
1137   const char *exp = *expp;
1138
1139   if (exp && *exp == '/')
1140     {
1141       exp++;
1142       *fmtp = decode_format (&exp, last_format, 0);
1143       validate_format (*fmtp, cmdname);
1144       last_format = fmtp->format;
1145     }
1146   else
1147     {
1148       fmtp->count = 1;
1149       fmtp->format = 0;
1150       fmtp->size = 0;
1151       fmtp->raw = 0;
1152     }
1153
1154   *expp = exp;
1155 }
1156
1157 /* Print VAL to console according to *FMTP, including recording it to
1158    the history.  */
1159
1160 void
1161 print_value (struct value *val, const struct format_data *fmtp)
1162 {
1163   struct value_print_options opts;
1164   int histindex = record_latest_value (val);
1165
1166   annotate_value_history_begin (histindex, value_type (val));
1167
1168   printf_filtered ("$%d = ", histindex);
1169
1170   annotate_value_history_value ();
1171
1172   get_formatted_print_options (&opts, fmtp->format);
1173   opts.raw = fmtp->raw;
1174
1175   print_formatted (val, fmtp->size, &opts, gdb_stdout);
1176   printf_filtered ("\n");
1177
1178   annotate_value_history_end ();
1179 }
1180
1181 /* Evaluate string EXP as an expression in the current language and
1182    print the resulting value.  EXP may contain a format specifier as the
1183    first argument ("/x myvar" for example, to print myvar in hex).  */
1184
1185 static void
1186 print_command_1 (const char *exp, int voidprint)
1187 {
1188   struct value *val;
1189   struct format_data fmt;
1190
1191   print_command_parse_format (&exp, "print", &fmt);
1192
1193   if (exp && *exp)
1194     {
1195       expression_up expr = parse_expression (exp);
1196       val = evaluate_expression (expr.get ());
1197     }
1198   else
1199     val = access_value_history (0);
1200
1201   if (voidprint || (val && value_type (val) &&
1202                     TYPE_CODE (value_type (val)) != TYPE_CODE_VOID))
1203     print_value (val, &fmt);
1204 }
1205
1206 static void
1207 print_command (char *exp, int from_tty)
1208 {
1209   print_command_1 (exp, 1);
1210 }
1211
1212 /* Same as print, except it doesn't print void results.  */
1213 static void
1214 call_command (char *exp, int from_tty)
1215 {
1216   print_command_1 (exp, 0);
1217 }
1218
1219 /* Implementation of the "output" command.  */
1220
1221 static void
1222 output_command (char *exp, int from_tty)
1223 {
1224   output_command_const (exp, from_tty);
1225 }
1226
1227 /* Like output_command, but takes a const string as argument.  */
1228
1229 void
1230 output_command_const (const char *exp, int from_tty)
1231 {
1232   char format = 0;
1233   struct value *val;
1234   struct format_data fmt;
1235   struct value_print_options opts;
1236
1237   fmt.size = 0;
1238   fmt.raw = 0;
1239
1240   if (exp && *exp == '/')
1241     {
1242       exp++;
1243       fmt = decode_format (&exp, 0, 0);
1244       validate_format (fmt, "output");
1245       format = fmt.format;
1246     }
1247
1248   expression_up expr = parse_expression (exp);
1249
1250   val = evaluate_expression (expr.get ());
1251
1252   annotate_value_begin (value_type (val));
1253
1254   get_formatted_print_options (&opts, format);
1255   opts.raw = fmt.raw;
1256   print_formatted (val, fmt.size, &opts, gdb_stdout);
1257
1258   annotate_value_end ();
1259
1260   wrap_here ("");
1261   gdb_flush (gdb_stdout);
1262 }
1263
1264 static void
1265 set_command (char *exp, int from_tty)
1266 {
1267   expression_up expr = parse_expression (exp);
1268
1269   if (expr->nelts >= 1)
1270     switch (expr->elts[0].opcode)
1271       {
1272       case UNOP_PREINCREMENT:
1273       case UNOP_POSTINCREMENT:
1274       case UNOP_PREDECREMENT:
1275       case UNOP_POSTDECREMENT:
1276       case BINOP_ASSIGN:
1277       case BINOP_ASSIGN_MODIFY:
1278       case BINOP_COMMA:
1279         break;
1280       default:
1281         warning
1282           (_("Expression is not an assignment (and might have no effect)"));
1283       }
1284
1285   evaluate_expression (expr.get ());
1286 }
1287
1288 static void
1289 sym_info (char *arg, int from_tty)
1290 {
1291   struct minimal_symbol *msymbol;
1292   struct objfile *objfile;
1293   struct obj_section *osect;
1294   CORE_ADDR addr, sect_addr;
1295   int matches = 0;
1296   unsigned int offset;
1297
1298   if (!arg)
1299     error_no_arg (_("address"));
1300
1301   addr = parse_and_eval_address (arg);
1302   ALL_OBJSECTIONS (objfile, osect)
1303   {
1304     /* Only process each object file once, even if there's a separate
1305        debug file.  */
1306     if (objfile->separate_debug_objfile_backlink)
1307       continue;
1308
1309     sect_addr = overlay_mapped_address (addr, osect);
1310
1311     if (obj_section_addr (osect) <= sect_addr
1312         && sect_addr < obj_section_endaddr (osect)
1313         && (msymbol
1314             = lookup_minimal_symbol_by_pc_section (sect_addr, osect).minsym))
1315       {
1316         const char *obj_name, *mapped, *sec_name, *msym_name;
1317         char *loc_string;
1318         struct cleanup *old_chain;
1319
1320         matches = 1;
1321         offset = sect_addr - MSYMBOL_VALUE_ADDRESS (objfile, msymbol);
1322         mapped = section_is_mapped (osect) ? _("mapped") : _("unmapped");
1323         sec_name = osect->the_bfd_section->name;
1324         msym_name = MSYMBOL_PRINT_NAME (msymbol);
1325
1326         /* Don't print the offset if it is zero.
1327            We assume there's no need to handle i18n of "sym + offset".  */
1328         if (offset)
1329           loc_string = xstrprintf ("%s + %u", msym_name, offset);
1330         else
1331           loc_string = xstrprintf ("%s", msym_name);
1332
1333         /* Use a cleanup to free loc_string in case the user quits
1334            a pagination request inside printf_filtered.  */
1335         old_chain = make_cleanup (xfree, loc_string);
1336
1337         gdb_assert (osect->objfile && objfile_name (osect->objfile));
1338         obj_name = objfile_name (osect->objfile);
1339
1340         if (MULTI_OBJFILE_P ())
1341           if (pc_in_unmapped_range (addr, osect))
1342             if (section_is_overlay (osect))
1343               printf_filtered (_("%s in load address range of "
1344                                  "%s overlay section %s of %s\n"),
1345                                loc_string, mapped, sec_name, obj_name);
1346             else
1347               printf_filtered (_("%s in load address range of "
1348                                  "section %s of %s\n"),
1349                                loc_string, sec_name, obj_name);
1350           else
1351             if (section_is_overlay (osect))
1352               printf_filtered (_("%s in %s overlay section %s of %s\n"),
1353                                loc_string, mapped, sec_name, obj_name);
1354             else
1355               printf_filtered (_("%s in section %s of %s\n"),
1356                                loc_string, sec_name, obj_name);
1357         else
1358           if (pc_in_unmapped_range (addr, osect))
1359             if (section_is_overlay (osect))
1360               printf_filtered (_("%s in load address range of %s overlay "
1361                                  "section %s\n"),
1362                                loc_string, mapped, sec_name);
1363             else
1364               printf_filtered (_("%s in load address range of section %s\n"),
1365                                loc_string, sec_name);
1366           else
1367             if (section_is_overlay (osect))
1368               printf_filtered (_("%s in %s overlay section %s\n"),
1369                                loc_string, mapped, sec_name);
1370             else
1371               printf_filtered (_("%s in section %s\n"),
1372                                loc_string, sec_name);
1373
1374         do_cleanups (old_chain);
1375       }
1376   }
1377   if (matches == 0)
1378     printf_filtered (_("No symbol matches %s.\n"), arg);
1379 }
1380
1381 static void
1382 address_info (char *exp, int from_tty)
1383 {
1384   struct gdbarch *gdbarch;
1385   int regno;
1386   struct symbol *sym;
1387   struct bound_minimal_symbol msymbol;
1388   long val;
1389   struct obj_section *section;
1390   CORE_ADDR load_addr, context_pc = 0;
1391   struct field_of_this_result is_a_field_of_this;
1392
1393   if (exp == 0)
1394     error (_("Argument required."));
1395
1396   sym = lookup_symbol (exp, get_selected_block (&context_pc), VAR_DOMAIN,
1397                        &is_a_field_of_this).symbol;
1398   if (sym == NULL)
1399     {
1400       if (is_a_field_of_this.type != NULL)
1401         {
1402           printf_filtered ("Symbol \"");
1403           fprintf_symbol_filtered (gdb_stdout, exp,
1404                                    current_language->la_language, DMGL_ANSI);
1405           printf_filtered ("\" is a field of the local class variable ");
1406           if (current_language->la_language == language_objc)
1407             printf_filtered ("`self'\n");       /* ObjC equivalent of "this" */
1408           else
1409             printf_filtered ("`this'\n");
1410           return;
1411         }
1412
1413       msymbol = lookup_bound_minimal_symbol (exp);
1414
1415       if (msymbol.minsym != NULL)
1416         {
1417           struct objfile *objfile = msymbol.objfile;
1418
1419           gdbarch = get_objfile_arch (objfile);
1420           load_addr = BMSYMBOL_VALUE_ADDRESS (msymbol);
1421
1422           printf_filtered ("Symbol \"");
1423           fprintf_symbol_filtered (gdb_stdout, exp,
1424                                    current_language->la_language, DMGL_ANSI);
1425           printf_filtered ("\" is at ");
1426           fputs_filtered (paddress (gdbarch, load_addr), gdb_stdout);
1427           printf_filtered (" in a file compiled without debugging");
1428           section = MSYMBOL_OBJ_SECTION (objfile, msymbol.minsym);
1429           if (section_is_overlay (section))
1430             {
1431               load_addr = overlay_unmapped_address (load_addr, section);
1432               printf_filtered (",\n -- loaded at ");
1433               fputs_filtered (paddress (gdbarch, load_addr), gdb_stdout);
1434               printf_filtered (" in overlay section %s",
1435                                section->the_bfd_section->name);
1436             }
1437           printf_filtered (".\n");
1438         }
1439       else
1440         error (_("No symbol \"%s\" in current context."), exp);
1441       return;
1442     }
1443
1444   printf_filtered ("Symbol \"");
1445   fprintf_symbol_filtered (gdb_stdout, SYMBOL_PRINT_NAME (sym),
1446                            current_language->la_language, DMGL_ANSI);
1447   printf_filtered ("\" is ");
1448   val = SYMBOL_VALUE (sym);
1449   if (SYMBOL_OBJFILE_OWNED (sym))
1450     section = SYMBOL_OBJ_SECTION (symbol_objfile (sym), sym);
1451   else
1452     section = NULL;
1453   gdbarch = symbol_arch (sym);
1454
1455   if (SYMBOL_COMPUTED_OPS (sym) != NULL)
1456     {
1457       SYMBOL_COMPUTED_OPS (sym)->describe_location (sym, context_pc,
1458                                                     gdb_stdout);
1459       printf_filtered (".\n");
1460       return;
1461     }
1462
1463   switch (SYMBOL_CLASS (sym))
1464     {
1465     case LOC_CONST:
1466     case LOC_CONST_BYTES:
1467       printf_filtered ("constant");
1468       break;
1469
1470     case LOC_LABEL:
1471       printf_filtered ("a label at address ");
1472       load_addr = SYMBOL_VALUE_ADDRESS (sym);
1473       fputs_filtered (paddress (gdbarch, load_addr), gdb_stdout);
1474       if (section_is_overlay (section))
1475         {
1476           load_addr = overlay_unmapped_address (load_addr, section);
1477           printf_filtered (",\n -- loaded at ");
1478           fputs_filtered (paddress (gdbarch, load_addr), gdb_stdout);
1479           printf_filtered (" in overlay section %s",
1480                            section->the_bfd_section->name);
1481         }
1482       break;
1483
1484     case LOC_COMPUTED:
1485       gdb_assert_not_reached (_("LOC_COMPUTED variable missing a method"));
1486
1487     case LOC_REGISTER:
1488       /* GDBARCH is the architecture associated with the objfile the symbol
1489          is defined in; the target architecture may be different, and may
1490          provide additional registers.  However, we do not know the target
1491          architecture at this point.  We assume the objfile architecture
1492          will contain all the standard registers that occur in debug info
1493          in that objfile.  */
1494       regno = SYMBOL_REGISTER_OPS (sym)->register_number (sym, gdbarch);
1495
1496       if (SYMBOL_IS_ARGUMENT (sym))
1497         printf_filtered (_("an argument in register %s"),
1498                          gdbarch_register_name (gdbarch, regno));
1499       else
1500         printf_filtered (_("a variable in register %s"),
1501                          gdbarch_register_name (gdbarch, regno));
1502       break;
1503
1504     case LOC_STATIC:
1505       printf_filtered (_("static storage at address "));
1506       load_addr = SYMBOL_VALUE_ADDRESS (sym);
1507       fputs_filtered (paddress (gdbarch, load_addr), gdb_stdout);
1508       if (section_is_overlay (section))
1509         {
1510           load_addr = overlay_unmapped_address (load_addr, section);
1511           printf_filtered (_(",\n -- loaded at "));
1512           fputs_filtered (paddress (gdbarch, load_addr), gdb_stdout);
1513           printf_filtered (_(" in overlay section %s"),
1514                            section->the_bfd_section->name);
1515         }
1516       break;
1517
1518     case LOC_REGPARM_ADDR:
1519       /* Note comment at LOC_REGISTER.  */
1520       regno = SYMBOL_REGISTER_OPS (sym)->register_number (sym, gdbarch);
1521       printf_filtered (_("address of an argument in register %s"),
1522                        gdbarch_register_name (gdbarch, regno));
1523       break;
1524
1525     case LOC_ARG:
1526       printf_filtered (_("an argument at offset %ld"), val);
1527       break;
1528
1529     case LOC_LOCAL:
1530       printf_filtered (_("a local variable at frame offset %ld"), val);
1531       break;
1532
1533     case LOC_REF_ARG:
1534       printf_filtered (_("a reference argument at offset %ld"), val);
1535       break;
1536
1537     case LOC_TYPEDEF:
1538       printf_filtered (_("a typedef"));
1539       break;
1540
1541     case LOC_BLOCK:
1542       printf_filtered (_("a function at address "));
1543       load_addr = BLOCK_START (SYMBOL_BLOCK_VALUE (sym));
1544       fputs_filtered (paddress (gdbarch, load_addr), gdb_stdout);
1545       if (section_is_overlay (section))
1546         {
1547           load_addr = overlay_unmapped_address (load_addr, section);
1548           printf_filtered (_(",\n -- loaded at "));
1549           fputs_filtered (paddress (gdbarch, load_addr), gdb_stdout);
1550           printf_filtered (_(" in overlay section %s"),
1551                            section->the_bfd_section->name);
1552         }
1553       break;
1554
1555     case LOC_UNRESOLVED:
1556       {
1557         struct bound_minimal_symbol msym;
1558
1559         msym = lookup_minimal_symbol_and_objfile (SYMBOL_LINKAGE_NAME (sym));
1560         if (msym.minsym == NULL)
1561           printf_filtered ("unresolved");
1562         else
1563           {
1564             section = MSYMBOL_OBJ_SECTION (msym.objfile, msym.minsym);
1565
1566             if (section
1567                 && (section->the_bfd_section->flags & SEC_THREAD_LOCAL) != 0)
1568               {
1569                 load_addr = MSYMBOL_VALUE_RAW_ADDRESS (msym.minsym);
1570                 printf_filtered (_("a thread-local variable at offset %s "
1571                                    "in the thread-local storage for `%s'"),
1572                                  paddress (gdbarch, load_addr),
1573                                  objfile_name (section->objfile));
1574               }
1575             else
1576               {
1577                 load_addr = BMSYMBOL_VALUE_ADDRESS (msym);
1578                 printf_filtered (_("static storage at address "));
1579                 fputs_filtered (paddress (gdbarch, load_addr), gdb_stdout);
1580                 if (section_is_overlay (section))
1581                   {
1582                     load_addr = overlay_unmapped_address (load_addr, section);
1583                     printf_filtered (_(",\n -- loaded at "));
1584                     fputs_filtered (paddress (gdbarch, load_addr), gdb_stdout);
1585                     printf_filtered (_(" in overlay section %s"),
1586                                      section->the_bfd_section->name);
1587                   }
1588               }
1589           }
1590       }
1591       break;
1592
1593     case LOC_OPTIMIZED_OUT:
1594       printf_filtered (_("optimized out"));
1595       break;
1596
1597     default:
1598       printf_filtered (_("of unknown (botched) type"));
1599       break;
1600     }
1601   printf_filtered (".\n");
1602 }
1603 \f
1604
1605 static void
1606 x_command (char *exp, int from_tty)
1607 {
1608   struct format_data fmt;
1609   struct cleanup *old_chain;
1610   struct value *val;
1611
1612   fmt.format = last_format ? last_format : 'x';
1613   fmt.size = last_size;
1614   fmt.count = 1;
1615   fmt.raw = 0;
1616
1617   if (exp && *exp == '/')
1618     {
1619       const char *tmp = exp + 1;
1620
1621       fmt = decode_format (&tmp, last_format, last_size);
1622       exp = (char *) tmp;
1623     }
1624
1625   /* If we have an expression, evaluate it and use it as the address.  */
1626
1627   if (exp != 0 && *exp != 0)
1628     {
1629       expression_up expr = parse_expression (exp);
1630       /* Cause expression not to be there any more if this command is
1631          repeated with Newline.  But don't clobber a user-defined
1632          command's definition.  */
1633       if (from_tty)
1634         *exp = 0;
1635       val = evaluate_expression (expr.get ());
1636       if (TYPE_IS_REFERENCE (value_type (val)))
1637         val = coerce_ref (val);
1638       /* In rvalue contexts, such as this, functions are coerced into
1639          pointers to functions.  This makes "x/i main" work.  */
1640       if (/* last_format == 'i'  && */ 
1641           TYPE_CODE (value_type (val)) == TYPE_CODE_FUNC
1642            && VALUE_LVAL (val) == lval_memory)
1643         next_address = value_address (val);
1644       else
1645         next_address = value_as_address (val);
1646
1647       next_gdbarch = expr->gdbarch;
1648     }
1649
1650   if (!next_gdbarch)
1651     error_no_arg (_("starting display address"));
1652
1653   do_examine (fmt, next_gdbarch, next_address);
1654
1655   /* If the examine succeeds, we remember its size and format for next
1656      time.  Set last_size to 'b' for strings.  */
1657   if (fmt.format == 's')
1658     last_size = 'b';
1659   else
1660     last_size = fmt.size;
1661   last_format = fmt.format;
1662
1663   /* Set a couple of internal variables if appropriate.  */
1664   if (last_examine_value)
1665     {
1666       /* Make last address examined available to the user as $_.  Use
1667          the correct pointer type.  */
1668       struct type *pointer_type
1669         = lookup_pointer_type (value_type (last_examine_value));
1670       set_internalvar (lookup_internalvar ("_"),
1671                        value_from_pointer (pointer_type,
1672                                            last_examine_address));
1673
1674       /* Make contents of last address examined available to the user
1675          as $__.  If the last value has not been fetched from memory
1676          then don't fetch it now; instead mark it by voiding the $__
1677          variable.  */
1678       if (value_lazy (last_examine_value))
1679         clear_internalvar (lookup_internalvar ("__"));
1680       else
1681         set_internalvar (lookup_internalvar ("__"), last_examine_value);
1682     }
1683 }
1684 \f
1685
1686 /* Add an expression to the auto-display chain.
1687    Specify the expression.  */
1688
1689 static void
1690 display_command (char *arg, int from_tty)
1691 {
1692   struct format_data fmt;
1693   struct display *newobj;
1694   const char *exp = arg;
1695
1696   if (exp == 0)
1697     {
1698       do_displays ();
1699       return;
1700     }
1701
1702   if (*exp == '/')
1703     {
1704       exp++;
1705       fmt = decode_format (&exp, 0, 0);
1706       if (fmt.size && fmt.format == 0)
1707         fmt.format = 'x';
1708       if (fmt.format == 'i' || fmt.format == 's')
1709         fmt.size = 'b';
1710     }
1711   else
1712     {
1713       fmt.format = 0;
1714       fmt.size = 0;
1715       fmt.count = 0;
1716       fmt.raw = 0;
1717     }
1718
1719   innermost_block = NULL;
1720   expression_up expr = parse_expression (exp);
1721
1722   newobj = new display ();
1723
1724   newobj->exp_string = xstrdup (exp);
1725   newobj->exp = std::move (expr);
1726   newobj->block = innermost_block;
1727   newobj->pspace = current_program_space;
1728   newobj->number = ++display_number;
1729   newobj->format = fmt;
1730   newobj->enabled_p = 1;
1731   newobj->next = NULL;
1732
1733   if (display_chain == NULL)
1734     display_chain = newobj;
1735   else
1736     {
1737       struct display *last;
1738
1739       for (last = display_chain; last->next != NULL; last = last->next)
1740         ;
1741       last->next = newobj;
1742     }
1743
1744   if (from_tty)
1745     do_one_display (newobj);
1746
1747   dont_repeat ();
1748 }
1749
1750 static void
1751 free_display (struct display *d)
1752 {
1753   xfree (d->exp_string);
1754   delete d;
1755 }
1756
1757 /* Clear out the display_chain.  Done when new symtabs are loaded,
1758    since this invalidates the types stored in many expressions.  */
1759
1760 void
1761 clear_displays (void)
1762 {
1763   struct display *d;
1764
1765   while ((d = display_chain) != NULL)
1766     {
1767       display_chain = d->next;
1768       free_display (d);
1769     }
1770 }
1771
1772 /* Delete the auto-display DISPLAY.  */
1773
1774 static void
1775 delete_display (struct display *display)
1776 {
1777   struct display *d;
1778
1779   gdb_assert (display != NULL);
1780
1781   if (display_chain == display)
1782     display_chain = display->next;
1783
1784   ALL_DISPLAYS (d)
1785     if (d->next == display)
1786       {
1787         d->next = display->next;
1788         break;
1789       }
1790
1791   free_display (display);
1792 }
1793
1794 /* Call FUNCTION on each of the displays whose numbers are given in
1795    ARGS.  DATA is passed unmodified to FUNCTION.  */
1796
1797 static void
1798 map_display_numbers (char *args,
1799                      void (*function) (struct display *,
1800                                        void *),
1801                      void *data)
1802 {
1803   int num;
1804
1805   if (args == NULL)
1806     error_no_arg (_("one or more display numbers"));
1807
1808   number_or_range_parser parser (args);
1809
1810   while (!parser.finished ())
1811     {
1812       const char *p = parser.cur_tok ();
1813
1814       num = parser.get_number ();
1815       if (num == 0)
1816         warning (_("bad display number at or near '%s'"), p);
1817       else
1818         {
1819           struct display *d, *tmp;
1820
1821           ALL_DISPLAYS_SAFE (d, tmp)
1822             if (d->number == num)
1823               break;
1824           if (d == NULL)
1825             printf_unfiltered (_("No display number %d.\n"), num);
1826           else
1827             function (d, data);
1828         }
1829     }
1830 }
1831
1832 /* Callback for map_display_numbers, that deletes a display.  */
1833
1834 static void
1835 do_delete_display (struct display *d, void *data)
1836 {
1837   delete_display (d);
1838 }
1839
1840 /* "undisplay" command.  */
1841
1842 static void
1843 undisplay_command (char *args, int from_tty)
1844 {
1845   if (args == NULL)
1846     {
1847       if (query (_("Delete all auto-display expressions? ")))
1848         clear_displays ();
1849       dont_repeat ();
1850       return;
1851     }
1852
1853   map_display_numbers (args, do_delete_display, NULL);
1854   dont_repeat ();
1855 }
1856
1857 /* Display a single auto-display.  
1858    Do nothing if the display cannot be printed in the current context,
1859    or if the display is disabled.  */
1860
1861 static void
1862 do_one_display (struct display *d)
1863 {
1864   int within_current_scope;
1865
1866   if (d->enabled_p == 0)
1867     return;
1868
1869   /* The expression carries the architecture that was used at parse time.
1870      This is a problem if the expression depends on architecture features
1871      (e.g. register numbers), and the current architecture is now different.
1872      For example, a display statement like "display/i $pc" is expected to
1873      display the PC register of the current architecture, not the arch at
1874      the time the display command was given.  Therefore, we re-parse the
1875      expression if the current architecture has changed.  */
1876   if (d->exp != NULL && d->exp->gdbarch != get_current_arch ())
1877     {
1878       d->exp.reset ();
1879       d->block = NULL;
1880     }
1881
1882   if (d->exp == NULL)
1883     {
1884
1885       TRY
1886         {
1887           innermost_block = NULL;
1888           d->exp = parse_expression (d->exp_string);
1889           d->block = innermost_block;
1890         }
1891       CATCH (ex, RETURN_MASK_ALL)
1892         {
1893           /* Can't re-parse the expression.  Disable this display item.  */
1894           d->enabled_p = 0;
1895           warning (_("Unable to display \"%s\": %s"),
1896                    d->exp_string, ex.message);
1897           return;
1898         }
1899       END_CATCH
1900     }
1901
1902   if (d->block)
1903     {
1904       if (d->pspace == current_program_space)
1905         within_current_scope = contained_in (get_selected_block (0), d->block);
1906       else
1907         within_current_scope = 0;
1908     }
1909   else
1910     within_current_scope = 1;
1911   if (!within_current_scope)
1912     return;
1913
1914   scoped_restore save_display_number
1915     = make_scoped_restore (&current_display_number, d->number);
1916
1917   annotate_display_begin ();
1918   printf_filtered ("%d", d->number);
1919   annotate_display_number_end ();
1920   printf_filtered (": ");
1921   if (d->format.size)
1922     {
1923
1924       annotate_display_format ();
1925
1926       printf_filtered ("x/");
1927       if (d->format.count != 1)
1928         printf_filtered ("%d", d->format.count);
1929       printf_filtered ("%c", d->format.format);
1930       if (d->format.format != 'i' && d->format.format != 's')
1931         printf_filtered ("%c", d->format.size);
1932       printf_filtered (" ");
1933
1934       annotate_display_expression ();
1935
1936       puts_filtered (d->exp_string);
1937       annotate_display_expression_end ();
1938
1939       if (d->format.count != 1 || d->format.format == 'i')
1940         printf_filtered ("\n");
1941       else
1942         printf_filtered ("  ");
1943
1944       annotate_display_value ();
1945
1946       TRY
1947         {
1948           struct value *val;
1949           CORE_ADDR addr;
1950
1951           val = evaluate_expression (d->exp.get ());
1952           addr = value_as_address (val);
1953           if (d->format.format == 'i')
1954             addr = gdbarch_addr_bits_remove (d->exp->gdbarch, addr);
1955           do_examine (d->format, d->exp->gdbarch, addr);
1956         }
1957       CATCH (ex, RETURN_MASK_ERROR)
1958         {
1959           fprintf_filtered (gdb_stdout, _("<error: %s>\n"), ex.message);
1960         }
1961       END_CATCH
1962     }
1963   else
1964     {
1965       struct value_print_options opts;
1966
1967       annotate_display_format ();
1968
1969       if (d->format.format)
1970         printf_filtered ("/%c ", d->format.format);
1971
1972       annotate_display_expression ();
1973
1974       puts_filtered (d->exp_string);
1975       annotate_display_expression_end ();
1976
1977       printf_filtered (" = ");
1978
1979       annotate_display_expression ();
1980
1981       get_formatted_print_options (&opts, d->format.format);
1982       opts.raw = d->format.raw;
1983
1984       TRY
1985         {
1986           struct value *val;
1987
1988           val = evaluate_expression (d->exp.get ());
1989           print_formatted (val, d->format.size, &opts, gdb_stdout);
1990         }
1991       CATCH (ex, RETURN_MASK_ERROR)
1992         {
1993           fprintf_filtered (gdb_stdout, _("<error: %s>"), ex.message);
1994         }
1995       END_CATCH
1996
1997       printf_filtered ("\n");
1998     }
1999
2000   annotate_display_end ();
2001
2002   gdb_flush (gdb_stdout);
2003 }
2004
2005 /* Display all of the values on the auto-display chain which can be
2006    evaluated in the current scope.  */
2007
2008 void
2009 do_displays (void)
2010 {
2011   struct display *d;
2012
2013   for (d = display_chain; d; d = d->next)
2014     do_one_display (d);
2015 }
2016
2017 /* Delete the auto-display which we were in the process of displaying.
2018    This is done when there is an error or a signal.  */
2019
2020 void
2021 disable_display (int num)
2022 {
2023   struct display *d;
2024
2025   for (d = display_chain; d; d = d->next)
2026     if (d->number == num)
2027       {
2028         d->enabled_p = 0;
2029         return;
2030       }
2031   printf_unfiltered (_("No display number %d.\n"), num);
2032 }
2033
2034 void
2035 disable_current_display (void)
2036 {
2037   if (current_display_number >= 0)
2038     {
2039       disable_display (current_display_number);
2040       fprintf_unfiltered (gdb_stderr,
2041                           _("Disabling display %d to "
2042                             "avoid infinite recursion.\n"),
2043                           current_display_number);
2044     }
2045   current_display_number = -1;
2046 }
2047
2048 static void
2049 display_info (char *ignore, int from_tty)
2050 {
2051   struct display *d;
2052
2053   if (!display_chain)
2054     printf_unfiltered (_("There are no auto-display expressions now.\n"));
2055   else
2056     printf_filtered (_("Auto-display expressions now in effect:\n\
2057 Num Enb Expression\n"));
2058
2059   for (d = display_chain; d; d = d->next)
2060     {
2061       printf_filtered ("%d:   %c  ", d->number, "ny"[(int) d->enabled_p]);
2062       if (d->format.size)
2063         printf_filtered ("/%d%c%c ", d->format.count, d->format.size,
2064                          d->format.format);
2065       else if (d->format.format)
2066         printf_filtered ("/%c ", d->format.format);
2067       puts_filtered (d->exp_string);
2068       if (d->block && !contained_in (get_selected_block (0), d->block))
2069         printf_filtered (_(" (cannot be evaluated in the current context)"));
2070       printf_filtered ("\n");
2071       gdb_flush (gdb_stdout);
2072     }
2073 }
2074
2075 /* Callback fo map_display_numbers, that enables or disables the
2076    passed in display D.  */
2077
2078 static void
2079 do_enable_disable_display (struct display *d, void *data)
2080 {
2081   d->enabled_p = *(int *) data;
2082 }
2083
2084 /* Implamentation of both the "disable display" and "enable display"
2085    commands.  ENABLE decides what to do.  */
2086
2087 static void
2088 enable_disable_display_command (char *args, int from_tty, int enable)
2089 {
2090   if (args == NULL)
2091     {
2092       struct display *d;
2093
2094       ALL_DISPLAYS (d)
2095         d->enabled_p = enable;
2096       return;
2097     }
2098
2099   map_display_numbers (args, do_enable_disable_display, &enable);
2100 }
2101
2102 /* The "enable display" command.  */
2103
2104 static void
2105 enable_display_command (char *args, int from_tty)
2106 {
2107   enable_disable_display_command (args, from_tty, 1);
2108 }
2109
2110 /* The "disable display" command.  */
2111
2112 static void
2113 disable_display_command (char *args, int from_tty)
2114 {
2115   enable_disable_display_command (args, from_tty, 0);
2116 }
2117
2118 /* display_chain items point to blocks and expressions.  Some expressions in
2119    turn may point to symbols.
2120    Both symbols and blocks are obstack_alloc'd on objfile_stack, and are
2121    obstack_free'd when a shared library is unloaded.
2122    Clear pointers that are about to become dangling.
2123    Both .exp and .block fields will be restored next time we need to display
2124    an item by re-parsing .exp_string field in the new execution context.  */
2125
2126 static void
2127 clear_dangling_display_expressions (struct objfile *objfile)
2128 {
2129   struct display *d;
2130   struct program_space *pspace;
2131
2132   /* With no symbol file we cannot have a block or expression from it.  */
2133   if (objfile == NULL)
2134     return;
2135   pspace = objfile->pspace;
2136   if (objfile->separate_debug_objfile_backlink)
2137     {
2138       objfile = objfile->separate_debug_objfile_backlink;
2139       gdb_assert (objfile->pspace == pspace);
2140     }
2141
2142   for (d = display_chain; d != NULL; d = d->next)
2143     {
2144       if (d->pspace != pspace)
2145         continue;
2146
2147       if (lookup_objfile_from_block (d->block) == objfile
2148           || (d->exp != NULL && exp_uses_objfile (d->exp.get (), objfile)))
2149       {
2150         d->exp.reset ();
2151         d->block = NULL;
2152       }
2153     }
2154 }
2155 \f
2156
2157 /* Print the value in stack frame FRAME of a variable specified by a
2158    struct symbol.  NAME is the name to print; if NULL then VAR's print
2159    name will be used.  STREAM is the ui_file on which to print the
2160    value.  INDENT specifies the number of indent levels to print
2161    before printing the variable name.
2162
2163    This function invalidates FRAME.  */
2164
2165 void
2166 print_variable_and_value (const char *name, struct symbol *var,
2167                           struct frame_info *frame,
2168                           struct ui_file *stream, int indent)
2169 {
2170
2171   if (!name)
2172     name = SYMBOL_PRINT_NAME (var);
2173
2174   fprintf_filtered (stream, "%s%s = ", n_spaces (2 * indent), name);
2175   TRY
2176     {
2177       struct value *val;
2178       struct value_print_options opts;
2179
2180       /* READ_VAR_VALUE needs a block in order to deal with non-local
2181          references (i.e. to handle nested functions).  In this context, we
2182          print variables that are local to this frame, so we can avoid passing
2183          a block to it.  */
2184       val = read_var_value (var, NULL, frame);
2185       get_user_print_options (&opts);
2186       opts.deref_ref = 1;
2187       common_val_print (val, stream, indent, &opts, current_language);
2188
2189       /* common_val_print invalidates FRAME when a pretty printer calls inferior
2190          function.  */
2191       frame = NULL;
2192     }
2193   CATCH (except, RETURN_MASK_ERROR)
2194     {
2195       fprintf_filtered(stream, "<error reading variable %s (%s)>", name,
2196                        except.message);
2197     }
2198   END_CATCH
2199
2200   fprintf_filtered (stream, "\n");
2201 }
2202
2203 /* Subroutine of ui_printf to simplify it.
2204    Print VALUE to STREAM using FORMAT.
2205    VALUE is a C-style string on the target.  */
2206
2207 static void
2208 printf_c_string (struct ui_file *stream, const char *format,
2209                  struct value *value)
2210 {
2211   gdb_byte *str;
2212   CORE_ADDR tem;
2213   int j;
2214
2215   tem = value_as_address (value);
2216
2217   /* This is a %s argument.  Find the length of the string.  */
2218   for (j = 0;; j++)
2219     {
2220       gdb_byte c;
2221
2222       QUIT;
2223       read_memory (tem + j, &c, 1);
2224       if (c == 0)
2225         break;
2226     }
2227
2228   /* Copy the string contents into a string inside GDB.  */
2229   str = (gdb_byte *) alloca (j + 1);
2230   if (j != 0)
2231     read_memory (tem, str, j);
2232   str[j] = 0;
2233
2234   fprintf_filtered (stream, format, (char *) str);
2235 }
2236
2237 /* Subroutine of ui_printf to simplify it.
2238    Print VALUE to STREAM using FORMAT.
2239    VALUE is a wide C-style string on the target.  */
2240
2241 static void
2242 printf_wide_c_string (struct ui_file *stream, const char *format,
2243                       struct value *value)
2244 {
2245   gdb_byte *str;
2246   CORE_ADDR tem;
2247   int j;
2248   struct gdbarch *gdbarch = get_type_arch (value_type (value));
2249   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
2250   struct type *wctype = lookup_typename (current_language, gdbarch,
2251                                          "wchar_t", NULL, 0);
2252   int wcwidth = TYPE_LENGTH (wctype);
2253   gdb_byte *buf = (gdb_byte *) alloca (wcwidth);
2254
2255   tem = value_as_address (value);
2256
2257   /* This is a %s argument.  Find the length of the string.  */
2258   for (j = 0;; j += wcwidth)
2259     {
2260       QUIT;
2261       read_memory (tem + j, buf, wcwidth);
2262       if (extract_unsigned_integer (buf, wcwidth, byte_order) == 0)
2263         break;
2264     }
2265
2266   /* Copy the string contents into a string inside GDB.  */
2267   str = (gdb_byte *) alloca (j + wcwidth);
2268   if (j != 0)
2269     read_memory (tem, str, j);
2270   memset (&str[j], 0, wcwidth);
2271
2272   auto_obstack output;
2273
2274   convert_between_encodings (target_wide_charset (gdbarch),
2275                              host_charset (),
2276                              str, j, wcwidth,
2277                              &output, translit_char);
2278   obstack_grow_str0 (&output, "");
2279
2280   fprintf_filtered (stream, format, obstack_base (&output));
2281 }
2282
2283 /* Subroutine of ui_printf to simplify it.
2284    Print VALUE, a decimal floating point value, to STREAM using FORMAT.  */
2285
2286 static void
2287 printf_decfloat (struct ui_file *stream, const char *format,
2288                  struct value *value)
2289 {
2290   const gdb_byte *param_ptr = value_contents (value);
2291
2292 #if defined (PRINTF_HAS_DECFLOAT)
2293   /* If we have native support for Decimal floating
2294      printing, handle it here.  */
2295   fprintf_filtered (stream, format, param_ptr);
2296 #else
2297   /* As a workaround until vasprintf has native support for DFP
2298      we convert the DFP values to string and print them using
2299      the %s format specifier.  */
2300   const char *p;
2301
2302   /* Parameter data.  */
2303   struct type *param_type = value_type (value);
2304   struct gdbarch *gdbarch = get_type_arch (param_type);
2305   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
2306
2307   /* DFP output data.  */
2308   struct value *dfp_value = NULL;
2309   gdb_byte *dfp_ptr;
2310   int dfp_len = 16;
2311   gdb_byte dec[16];
2312   struct type *dfp_type = NULL;
2313   char decstr[MAX_DECIMAL_STRING];
2314
2315   /* Points to the end of the string so that we can go back
2316      and check for DFP length modifiers.  */
2317   p = format + strlen (format);
2318
2319   /* Look for the float/double format specifier.  */
2320   while (*p != 'f' && *p != 'e' && *p != 'E'
2321          && *p != 'g' && *p != 'G')
2322     p--;
2323
2324   /* Search for the '%' char and extract the size and type of
2325      the output decimal value based on its modifiers
2326      (%Hf, %Df, %DDf).  */
2327   while (*--p != '%')
2328     {
2329       if (*p == 'H')
2330         {
2331           dfp_len = 4;
2332           dfp_type = builtin_type (gdbarch)->builtin_decfloat;
2333         }
2334       else if (*p == 'D' && *(p - 1) == 'D')
2335         {
2336           dfp_len = 16;
2337           dfp_type = builtin_type (gdbarch)->builtin_declong;
2338           p--;
2339         }
2340       else
2341         {
2342           dfp_len = 8;
2343           dfp_type = builtin_type (gdbarch)->builtin_decdouble;
2344         }
2345     }
2346
2347   /* Conversion between different DFP types.  */
2348   if (TYPE_CODE (param_type) == TYPE_CODE_DECFLOAT)
2349     decimal_convert (param_ptr, TYPE_LENGTH (param_type),
2350                      byte_order, dec, dfp_len, byte_order);
2351   else
2352     /* If this is a non-trivial conversion, just output 0.
2353        A correct converted value can be displayed by explicitly
2354        casting to a DFP type.  */
2355     decimal_from_string (dec, dfp_len, byte_order, "0");
2356
2357   dfp_value = value_from_decfloat (dfp_type, dec);
2358
2359   dfp_ptr = (gdb_byte *) value_contents (dfp_value);
2360
2361   decimal_to_string (dfp_ptr, dfp_len, byte_order, decstr);
2362
2363   /* Print the DFP value.  */
2364   fprintf_filtered (stream, "%s", decstr);
2365 #endif
2366 }
2367
2368 /* Subroutine of ui_printf to simplify it.
2369    Print VALUE, a target pointer, to STREAM using FORMAT.  */
2370
2371 static void
2372 printf_pointer (struct ui_file *stream, const char *format,
2373                 struct value *value)
2374 {
2375   /* We avoid the host's %p because pointers are too
2376      likely to be the wrong size.  The only interesting
2377      modifier for %p is a width; extract that, and then
2378      handle %p as glibc would: %#x or a literal "(nil)".  */
2379
2380   const char *p;
2381   char *fmt, *fmt_p;
2382 #ifdef PRINTF_HAS_LONG_LONG
2383   long long val = value_as_long (value);
2384 #else
2385   long val = value_as_long (value);
2386 #endif
2387
2388   fmt = (char *) alloca (strlen (format) + 5);
2389
2390   /* Copy up to the leading %.  */
2391   p = format;
2392   fmt_p = fmt;
2393   while (*p)
2394     {
2395       int is_percent = (*p == '%');
2396
2397       *fmt_p++ = *p++;
2398       if (is_percent)
2399         {
2400           if (*p == '%')
2401             *fmt_p++ = *p++;
2402           else
2403             break;
2404         }
2405     }
2406
2407   if (val != 0)
2408     *fmt_p++ = '#';
2409
2410   /* Copy any width.  */
2411   while (*p >= '0' && *p < '9')
2412     *fmt_p++ = *p++;
2413
2414   gdb_assert (*p == 'p' && *(p + 1) == '\0');
2415   if (val != 0)
2416     {
2417 #ifdef PRINTF_HAS_LONG_LONG
2418       *fmt_p++ = 'l';
2419 #endif
2420       *fmt_p++ = 'l';
2421       *fmt_p++ = 'x';
2422       *fmt_p++ = '\0';
2423       fprintf_filtered (stream, fmt, val);
2424     }
2425   else
2426     {
2427       *fmt_p++ = 's';
2428       *fmt_p++ = '\0';
2429       fprintf_filtered (stream, fmt, "(nil)");
2430     }
2431 }
2432
2433 /* printf "printf format string" ARG to STREAM.  */
2434
2435 static void
2436 ui_printf (const char *arg, struct ui_file *stream)
2437 {
2438   struct format_piece *fpieces;
2439   const char *s = arg;
2440   struct value **val_args;
2441   int allocated_args = 20;
2442   struct cleanup *old_cleanups;
2443
2444   val_args = XNEWVEC (struct value *, allocated_args);
2445   old_cleanups = make_cleanup (free_current_contents, &val_args);
2446
2447   if (s == 0)
2448     error_no_arg (_("format-control string and values to print"));
2449
2450   s = skip_spaces_const (s);
2451
2452   /* A format string should follow, enveloped in double quotes.  */
2453   if (*s++ != '"')
2454     error (_("Bad format string, missing '\"'."));
2455
2456   fpieces = parse_format_string (&s);
2457
2458   make_cleanup (free_format_pieces_cleanup, &fpieces);
2459
2460   if (*s++ != '"')
2461     error (_("Bad format string, non-terminated '\"'."));
2462   
2463   s = skip_spaces_const (s);
2464
2465   if (*s != ',' && *s != 0)
2466     error (_("Invalid argument syntax"));
2467
2468   if (*s == ',')
2469     s++;
2470   s = skip_spaces_const (s);
2471
2472   {
2473     int nargs = 0;
2474     int nargs_wanted;
2475     int i, fr;
2476     char *current_substring;
2477
2478     nargs_wanted = 0;
2479     for (fr = 0; fpieces[fr].string != NULL; fr++)
2480       if (fpieces[fr].argclass != literal_piece)
2481         ++nargs_wanted;
2482
2483     /* Now, parse all arguments and evaluate them.
2484        Store the VALUEs in VAL_ARGS.  */
2485
2486     while (*s != '\0')
2487       {
2488         const char *s1;
2489
2490         if (nargs == allocated_args)
2491           val_args = (struct value **) xrealloc ((char *) val_args,
2492                                                  (allocated_args *= 2)
2493                                                  * sizeof (struct value *));
2494         s1 = s;
2495         val_args[nargs] = parse_to_comma_and_eval (&s1);
2496
2497         nargs++;
2498         s = s1;
2499         if (*s == ',')
2500           s++;
2501       }
2502
2503     if (nargs != nargs_wanted)
2504       error (_("Wrong number of arguments for specified format-string"));
2505
2506     /* Now actually print them.  */
2507     i = 0;
2508     for (fr = 0; fpieces[fr].string != NULL; fr++)
2509       {
2510         current_substring = fpieces[fr].string;
2511         switch (fpieces[fr].argclass)
2512           {
2513           case string_arg:
2514             printf_c_string (stream, current_substring, val_args[i]);
2515             break;
2516           case wide_string_arg:
2517             printf_wide_c_string (stream, current_substring, val_args[i]);
2518             break;
2519           case wide_char_arg:
2520             {
2521               struct gdbarch *gdbarch
2522                 = get_type_arch (value_type (val_args[i]));
2523               struct type *wctype = lookup_typename (current_language, gdbarch,
2524                                                      "wchar_t", NULL, 0);
2525               struct type *valtype;
2526               const gdb_byte *bytes;
2527
2528               valtype = value_type (val_args[i]);
2529               if (TYPE_LENGTH (valtype) != TYPE_LENGTH (wctype)
2530                   || TYPE_CODE (valtype) != TYPE_CODE_INT)
2531                 error (_("expected wchar_t argument for %%lc"));
2532
2533               bytes = value_contents (val_args[i]);
2534
2535               auto_obstack output;
2536
2537               convert_between_encodings (target_wide_charset (gdbarch),
2538                                          host_charset (),
2539                                          bytes, TYPE_LENGTH (valtype),
2540                                          TYPE_LENGTH (valtype),
2541                                          &output, translit_char);
2542               obstack_grow_str0 (&output, "");
2543
2544               fprintf_filtered (stream, current_substring,
2545                                 obstack_base (&output));
2546             }
2547             break;
2548           case double_arg:
2549             {
2550               struct type *type = value_type (val_args[i]);
2551               DOUBLEST val;
2552               int inv;
2553
2554               /* If format string wants a float, unchecked-convert the value
2555                  to floating point of the same size.  */
2556               type = float_type_from_length (type);
2557               val = unpack_double (type, value_contents (val_args[i]), &inv);
2558               if (inv)
2559                 error (_("Invalid floating value found in program."));
2560
2561               fprintf_filtered (stream, current_substring, (double) val);
2562               break;
2563             }
2564           case long_double_arg:
2565 #ifdef HAVE_LONG_DOUBLE
2566             {
2567               struct type *type = value_type (val_args[i]);
2568               DOUBLEST val;
2569               int inv;
2570
2571               /* If format string wants a float, unchecked-convert the value
2572                  to floating point of the same size.  */
2573               type = float_type_from_length (type);
2574               val = unpack_double (type, value_contents (val_args[i]), &inv);
2575               if (inv)
2576                 error (_("Invalid floating value found in program."));
2577
2578               fprintf_filtered (stream, current_substring,
2579                                 (long double) val);
2580               break;
2581             }
2582 #else
2583             error (_("long double not supported in printf"));
2584 #endif
2585           case long_long_arg:
2586 #ifdef PRINTF_HAS_LONG_LONG
2587             {
2588               long long val = value_as_long (val_args[i]);
2589
2590               fprintf_filtered (stream, current_substring, val);
2591               break;
2592             }
2593 #else
2594             error (_("long long not supported in printf"));
2595 #endif
2596           case int_arg:
2597             {
2598               int val = value_as_long (val_args[i]);
2599
2600               fprintf_filtered (stream, current_substring, val);
2601               break;
2602             }
2603           case long_arg:
2604             {
2605               long val = value_as_long (val_args[i]);
2606
2607               fprintf_filtered (stream, current_substring, val);
2608               break;
2609             }
2610           /* Handles decimal floating values.  */
2611           case decfloat_arg:
2612             printf_decfloat (stream, current_substring, val_args[i]);
2613             break;
2614           case ptr_arg:
2615             printf_pointer (stream, current_substring, val_args[i]);
2616             break;
2617           case literal_piece:
2618             /* Print a portion of the format string that has no
2619                directives.  Note that this will not include any
2620                ordinary %-specs, but it might include "%%".  That is
2621                why we use printf_filtered and not puts_filtered here.
2622                Also, we pass a dummy argument because some platforms
2623                have modified GCC to include -Wformat-security by
2624                default, which will warn here if there is no
2625                argument.  */
2626             fprintf_filtered (stream, current_substring, 0);
2627             break;
2628           default:
2629             internal_error (__FILE__, __LINE__,
2630                             _("failed internal consistency check"));
2631           }
2632         /* Maybe advance to the next argument.  */
2633         if (fpieces[fr].argclass != literal_piece)
2634           ++i;
2635       }
2636   }
2637   do_cleanups (old_cleanups);
2638 }
2639
2640 /* Implement the "printf" command.  */
2641
2642 static void
2643 printf_command (char *arg, int from_tty)
2644 {
2645   ui_printf (arg, gdb_stdout);
2646   gdb_flush (gdb_stdout);
2647 }
2648
2649 /* Implement the "eval" command.  */
2650
2651 static void
2652 eval_command (char *arg, int from_tty)
2653 {
2654   string_file stb;
2655
2656   ui_printf (arg, &stb);
2657
2658   std::string expanded = insert_user_defined_cmd_args (stb.c_str ());
2659
2660   execute_command (&expanded[0], from_tty);
2661 }
2662
2663 void
2664 _initialize_printcmd (void)
2665 {
2666   struct cmd_list_element *c;
2667
2668   current_display_number = -1;
2669
2670   observer_attach_free_objfile (clear_dangling_display_expressions);
2671
2672   add_info ("address", address_info,
2673             _("Describe where symbol SYM is stored."));
2674
2675   add_info ("symbol", sym_info, _("\
2676 Describe what symbol is at location ADDR.\n\
2677 Only for symbols with fixed locations (global or static scope)."));
2678
2679   add_com ("x", class_vars, x_command, _("\
2680 Examine memory: x/FMT ADDRESS.\n\
2681 ADDRESS is an expression for the memory address to examine.\n\
2682 FMT is a repeat count followed by a format letter and a size letter.\n\
2683 Format letters are o(octal), x(hex), d(decimal), u(unsigned decimal),\n\
2684   t(binary), f(float), a(address), i(instruction), c(char), s(string)\n\
2685   and z(hex, zero padded on the left).\n\
2686 Size letters are b(byte), h(halfword), w(word), g(giant, 8 bytes).\n\
2687 The specified number of objects of the specified size are printed\n\
2688 according to the format.  If a negative number is specified, memory is\n\
2689 examined backward from the address.\n\n\
2690 Defaults for format and size letters are those previously used.\n\
2691 Default count is 1.  Default address is following last thing printed\n\
2692 with this command or \"print\"."));
2693
2694 #if 0
2695   add_com ("whereis", class_vars, whereis_command,
2696            _("Print line number and file of definition of variable."));
2697 #endif
2698
2699   add_info ("display", display_info, _("\
2700 Expressions to display when program stops, with code numbers."));
2701
2702   add_cmd ("undisplay", class_vars, undisplay_command, _("\
2703 Cancel some expressions to be displayed when program stops.\n\
2704 Arguments are the code numbers of the expressions to stop displaying.\n\
2705 No argument means cancel all automatic-display expressions.\n\
2706 \"delete display\" has the same effect as this command.\n\
2707 Do \"info display\" to see current list of code numbers."),
2708            &cmdlist);
2709
2710   add_com ("display", class_vars, display_command, _("\
2711 Print value of expression EXP each time the program stops.\n\
2712 /FMT may be used before EXP as in the \"print\" command.\n\
2713 /FMT \"i\" or \"s\" or including a size-letter is allowed,\n\
2714 as in the \"x\" command, and then EXP is used to get the address to examine\n\
2715 and examining is done as in the \"x\" command.\n\n\
2716 With no argument, display all currently requested auto-display expressions.\n\
2717 Use \"undisplay\" to cancel display requests previously made."));
2718
2719   add_cmd ("display", class_vars, enable_display_command, _("\
2720 Enable some expressions to be displayed when program stops.\n\
2721 Arguments are the code numbers of the expressions to resume displaying.\n\
2722 No argument means enable all automatic-display expressions.\n\
2723 Do \"info display\" to see current list of code numbers."), &enablelist);
2724
2725   add_cmd ("display", class_vars, disable_display_command, _("\
2726 Disable some expressions to be displayed when program stops.\n\
2727 Arguments are the code numbers of the expressions to stop displaying.\n\
2728 No argument means disable all automatic-display expressions.\n\
2729 Do \"info display\" to see current list of code numbers."), &disablelist);
2730
2731   add_cmd ("display", class_vars, undisplay_command, _("\
2732 Cancel some expressions to be displayed when program stops.\n\
2733 Arguments are the code numbers of the expressions to stop displaying.\n\
2734 No argument means cancel all automatic-display expressions.\n\
2735 Do \"info display\" to see current list of code numbers."), &deletelist);
2736
2737   add_com ("printf", class_vars, printf_command, _("\
2738 printf \"printf format string\", arg1, arg2, arg3, ..., argn\n\
2739 This is useful for formatted output in user-defined commands."));
2740
2741   add_com ("output", class_vars, output_command, _("\
2742 Like \"print\" but don't put in value history and don't print newline.\n\
2743 This is useful in user-defined commands."));
2744
2745   add_prefix_cmd ("set", class_vars, set_command, _("\
2746 Evaluate expression EXP and assign result to variable VAR, using assignment\n\
2747 syntax appropriate for the current language (VAR = EXP or VAR := EXP for\n\
2748 example).  VAR may be a debugger \"convenience\" variable (names starting\n\
2749 with $), a register (a few standard names starting with $), or an actual\n\
2750 variable in the program being debugged.  EXP is any valid expression.\n\
2751 Use \"set variable\" for variables with names identical to set subcommands.\n\
2752 \n\
2753 With a subcommand, this command modifies parts of the gdb environment.\n\
2754 You can see these environment settings with the \"show\" command."),
2755                   &setlist, "set ", 1, &cmdlist);
2756   if (dbx_commands)
2757     add_com ("assign", class_vars, set_command, _("\
2758 Evaluate expression EXP and assign result to variable VAR, using assignment\n\
2759 syntax appropriate for the current language (VAR = EXP or VAR := EXP for\n\
2760 example).  VAR may be a debugger \"convenience\" variable (names starting\n\
2761 with $), a register (a few standard names starting with $), or an actual\n\
2762 variable in the program being debugged.  EXP is any valid expression.\n\
2763 Use \"set variable\" for variables with names identical to set subcommands.\n\
2764 \nWith a subcommand, this command modifies parts of the gdb environment.\n\
2765 You can see these environment settings with the \"show\" command."));
2766
2767   /* "call" is the same as "set", but handy for dbx users to call fns.  */
2768   c = add_com ("call", class_vars, call_command, _("\
2769 Call a function in the program.\n\
2770 The argument is the function name and arguments, in the notation of the\n\
2771 current working language.  The result is printed and saved in the value\n\
2772 history, if it is not void."));
2773   set_cmd_completer (c, expression_completer);
2774
2775   add_cmd ("variable", class_vars, set_command, _("\
2776 Evaluate expression EXP and assign result to variable VAR, using assignment\n\
2777 syntax appropriate for the current language (VAR = EXP or VAR := EXP for\n\
2778 example).  VAR may be a debugger \"convenience\" variable (names starting\n\
2779 with $), a register (a few standard names starting with $), or an actual\n\
2780 variable in the program being debugged.  EXP is any valid expression.\n\
2781 This may usually be abbreviated to simply \"set\"."),
2782            &setlist);
2783
2784   c = add_com ("print", class_vars, print_command, _("\
2785 Print value of expression EXP.\n\
2786 Variables accessible are those of the lexical environment of the selected\n\
2787 stack frame, plus all those whose scope is global or an entire file.\n\
2788 \n\
2789 $NUM gets previous value number NUM.  $ and $$ are the last two values.\n\
2790 $$NUM refers to NUM'th value back from the last one.\n\
2791 Names starting with $ refer to registers (with the values they would have\n\
2792 if the program were to return to the stack frame now selected, restoring\n\
2793 all registers saved by frames farther in) or else to debugger\n\
2794 \"convenience\" variables (any such name not a known register).\n\
2795 Use assignment expressions to give values to convenience variables.\n\
2796 \n\
2797 {TYPE}ADREXP refers to a datum of data type TYPE, located at address ADREXP.\n\
2798 @ is a binary operator for treating consecutive data objects\n\
2799 anywhere in memory as an array.  FOO@NUM gives an array whose first\n\
2800 element is FOO, whose second element is stored in the space following\n\
2801 where FOO is stored, etc.  FOO must be an expression whose value\n\
2802 resides in memory.\n\
2803 \n\
2804 EXP may be preceded with /FMT, where FMT is a format letter\n\
2805 but no count or size letter (see \"x\" command)."));
2806   set_cmd_completer (c, expression_completer);
2807   add_com_alias ("p", "print", class_vars, 1);
2808   add_com_alias ("inspect", "print", class_vars, 1);
2809
2810   add_setshow_uinteger_cmd ("max-symbolic-offset", no_class,
2811                             &max_symbolic_offset, _("\
2812 Set the largest offset that will be printed in <symbol+1234> form."), _("\
2813 Show the largest offset that will be printed in <symbol+1234> form."), _("\
2814 Tell GDB to only display the symbolic form of an address if the\n\
2815 offset between the closest earlier symbol and the address is less than\n\
2816 the specified maximum offset.  The default is \"unlimited\", which tells GDB\n\
2817 to always print the symbolic form of an address if any symbol precedes\n\
2818 it.  Zero is equivalent to \"unlimited\"."),
2819                             NULL,
2820                             show_max_symbolic_offset,
2821                             &setprintlist, &showprintlist);
2822   add_setshow_boolean_cmd ("symbol-filename", no_class,
2823                            &print_symbol_filename, _("\
2824 Set printing of source filename and line number with <symbol>."), _("\
2825 Show printing of source filename and line number with <symbol>."), NULL,
2826                            NULL,
2827                            show_print_symbol_filename,
2828                            &setprintlist, &showprintlist);
2829
2830   add_com ("eval", no_class, eval_command, _("\
2831 Convert \"printf format string\", arg1, arg2, arg3, ..., argn to\n\
2832 a command line, and call it."));
2833 }