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