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