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