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