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