OSDN Git Service

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