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