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