OSDN Git Service

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