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