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