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