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