]> Git Repo - binutils.git/blob - gdb/printcmd.c
gdb, gdbserver: make status_to_str display the signal name
[binutils.git] / gdb / printcmd.c
1 /* Print values for GNU debugger GDB.
2
3    Copyright (C) 1986-2021 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 "c-lang.h"
27 #include "expression.h"
28 #include "gdbcore.h"
29 #include "gdbcmd.h"
30 #include "target.h"
31 #include "breakpoint.h"
32 #include "demangle.h"
33 #include "gdb-demangle.h"
34 #include "valprint.h"
35 #include "annotate.h"
36 #include "symfile.h"            /* for overlay functions */
37 #include "objfiles.h"           /* ditto */
38 #include "completer.h"          /* for completion functions */
39 #include "ui-out.h"
40 #include "block.h"
41 #include "disasm.h"
42 #include "target-float.h"
43 #include "observable.h"
44 #include "solist.h"
45 #include "parser-defs.h"
46 #include "charset.h"
47 #include "arch-utils.h"
48 #include "cli/cli-utils.h"
49 #include "cli/cli-option.h"
50 #include "cli/cli-script.h"
51 #include "cli/cli-style.h"
52 #include "gdbsupport/format.h"
53 #include "source.h"
54 #include "gdbsupport/byte-vector.h"
55 #include "gdbsupport/gdb_optional.h"
56 #include "safe-ctype.h"
57 #include "gdbsupport/rsp-low.h"
58
59 /* Chain containing all defined memory-tag subcommands.  */
60
61 static struct cmd_list_element *memory_tag_list;
62
63 /* Last specified output format.  */
64
65 static char last_format = 0;
66
67 /* Last specified examination size.  'b', 'h', 'w' or `q'.  */
68
69 static char last_size = 'w';
70
71 /* Last specified count for the 'x' command.  */
72
73 static int last_count;
74
75 /* Last specified tag-printing option.  */
76
77 static bool last_print_tags = false;
78
79 /* Default address to examine next, and associated architecture.  */
80
81 static struct gdbarch *next_gdbarch;
82 static CORE_ADDR next_address;
83
84 /* Number of delay instructions following current disassembled insn.  */
85
86 static int branch_delay_insns;
87
88 /* Last address examined.  */
89
90 static CORE_ADDR last_examine_address;
91
92 /* Contents of last address examined.
93    This is not valid past the end of the `x' command!  */
94
95 static value_ref_ptr last_examine_value;
96
97 /* Largest offset between a symbolic value and an address, that will be
98    printed as `0x1234 <symbol+offset>'.  */
99
100 static unsigned int max_symbolic_offset = UINT_MAX;
101 static void
102 show_max_symbolic_offset (struct ui_file *file, int from_tty,
103                           struct cmd_list_element *c, const char *value)
104 {
105   fprintf_filtered (file,
106                     _("The largest offset that will be "
107                       "printed in <symbol+1234> form is %s.\n"),
108                     value);
109 }
110
111 /* Append the source filename and linenumber of the symbol when
112    printing a symbolic value as `<symbol at filename:linenum>' if set.  */
113 static bool print_symbol_filename = false;
114 static void
115 show_print_symbol_filename (struct ui_file *file, int from_tty,
116                             struct cmd_list_element *c, const char *value)
117 {
118   fprintf_filtered (file, _("Printing of source filename and "
119                             "line number with <symbol> is %s.\n"),
120                     value);
121 }
122
123 /* Number of auto-display expression currently being displayed.
124    So that we can disable it if we get a signal within it.
125    -1 when not doing one.  */
126
127 static int current_display_number;
128
129 /* Last allocated display number.  */
130
131 static int display_number;
132
133 struct display
134   {
135     display (const char *exp_string_, expression_up &&exp_,
136              const struct format_data &format_, struct program_space *pspace_,
137              const struct block *block_)
138       : exp_string (exp_string_),
139         exp (std::move (exp_)),
140         number (++display_number),
141         format (format_),
142         pspace (pspace_),
143         block (block_),
144         enabled_p (true)
145     {
146     }
147
148     /* The expression as the user typed it.  */
149     std::string exp_string;
150
151     /* Expression to be evaluated and displayed.  */
152     expression_up exp;
153
154     /* Item number of this auto-display item.  */
155     int number;
156
157     /* Display format specified.  */
158     struct format_data format;
159
160     /* Program space associated with `block'.  */
161     struct program_space *pspace;
162
163     /* Innermost block required by this expression when evaluated.  */
164     const struct block *block;
165
166     /* Status of this display (enabled or disabled).  */
167     bool enabled_p;
168   };
169
170 /* Expressions whose values should be displayed automatically each
171    time the program stops.  */
172
173 static std::vector<std::unique_ptr<struct display>> all_displays;
174
175 /* Prototypes for local functions.  */
176
177 static void do_one_display (struct display *);
178 \f
179
180 /* Decode a format specification.  *STRING_PTR should point to it.
181    OFORMAT and OSIZE are used as defaults for the format and size
182    if none are given in the format specification.
183    If OSIZE is zero, then the size field of the returned value
184    should be set only if a size is explicitly specified by the
185    user.
186    The structure returned describes all the data
187    found in the specification.  In addition, *STRING_PTR is advanced
188    past the specification and past all whitespace following it.  */
189
190 static struct format_data
191 decode_format (const char **string_ptr, int oformat, int osize)
192 {
193   struct format_data val;
194   const char *p = *string_ptr;
195
196   val.format = '?';
197   val.size = '?';
198   val.count = 1;
199   val.raw = 0;
200   val.print_tags = false;
201
202   if (*p == '-')
203     {
204       val.count = -1;
205       p++;
206     }
207   if (*p >= '0' && *p <= '9')
208     val.count *= atoi (p);
209   while (*p >= '0' && *p <= '9')
210     p++;
211
212   /* Now process size or format letters that follow.  */
213
214   while (1)
215     {
216       if (*p == 'b' || *p == 'h' || *p == 'w' || *p == 'g')
217         val.size = *p++;
218       else if (*p == 'r')
219         {
220           val.raw = 1;
221           p++;
222         }
223       else if (*p == 'm')
224         {
225           val.print_tags = true;
226           p++;
227         }
228       else if (*p >= 'a' && *p <= 'z')
229         val.format = *p++;
230       else
231         break;
232     }
233
234   *string_ptr = skip_spaces (p);
235
236   /* Set defaults for format and size if not specified.  */
237   if (val.format == '?')
238     {
239       if (val.size == '?')
240         {
241           /* Neither has been specified.  */
242           val.format = oformat;
243           val.size = osize;
244         }
245       else
246         /* If a size is specified, any format makes a reasonable
247            default except 'i'.  */
248         val.format = oformat == 'i' ? 'x' : oformat;
249     }
250   else if (val.size == '?')
251     switch (val.format)
252       {
253       case 'a':
254         /* Pick the appropriate size for an address.  This is deferred
255            until do_examine when we know the actual architecture to use.
256            A special size value of 'a' is used to indicate this case.  */
257         val.size = osize ? 'a' : osize;
258         break;
259       case 'f':
260         /* Floating point has to be word or giantword.  */
261         if (osize == 'w' || osize == 'g')
262           val.size = osize;
263         else
264           /* Default it to giantword if the last used size is not
265              appropriate.  */
266           val.size = osize ? 'g' : osize;
267         break;
268       case 'c':
269         /* Characters default to one byte.  */
270         val.size = osize ? 'b' : osize;
271         break;
272       case 's':
273         /* Display strings with byte size chars unless explicitly
274            specified.  */
275         val.size = '\0';
276         break;
277
278       default:
279         /* The default is the size most recently specified.  */
280         val.size = osize;
281       }
282
283   return val;
284 }
285 \f
286 /* Print value VAL on stream according to OPTIONS.
287    Do not end with a newline.
288    SIZE is the letter for the size of datum being printed.
289    This is used to pad hex numbers so they line up.  SIZE is 0
290    for print / output and set for examine.  */
291
292 static void
293 print_formatted (struct value *val, int size,
294                  const struct value_print_options *options,
295                  struct ui_file *stream)
296 {
297   struct type *type = check_typedef (value_type (val));
298   int len = TYPE_LENGTH (type);
299
300   if (VALUE_LVAL (val) == lval_memory)
301     next_address = value_address (val) + len;
302
303   if (size)
304     {
305       switch (options->format)
306         {
307         case 's':
308           {
309             struct type *elttype = value_type (val);
310
311             next_address = (value_address (val)
312                             + val_print_string (elttype, NULL,
313                                                 value_address (val), -1,
314                                                 stream, options) * len);
315           }
316           return;
317
318         case 'i':
319           /* We often wrap here if there are long symbolic names.  */
320           wrap_here ("    ");
321           next_address = (value_address (val)
322                           + gdb_print_insn (type->arch (),
323                                             value_address (val), stream,
324                                             &branch_delay_insns));
325           return;
326         }
327     }
328
329   if (options->format == 0 || options->format == 's'
330       || type->code () == TYPE_CODE_VOID
331       || type->code () == TYPE_CODE_REF
332       || type->code () == TYPE_CODE_ARRAY
333       || type->code () == TYPE_CODE_STRING
334       || type->code () == TYPE_CODE_STRUCT
335       || type->code () == TYPE_CODE_UNION
336       || type->code () == TYPE_CODE_NAMESPACE)
337     value_print (val, stream, options);
338   else
339     /* User specified format, so don't look to the type to tell us
340        what to do.  */
341     value_print_scalar_formatted (val, options, size, stream);
342 }
343
344 /* Return builtin floating point type of same length as TYPE.
345    If no such type is found, return TYPE itself.  */
346 static struct type *
347 float_type_from_length (struct type *type)
348 {
349   struct gdbarch *gdbarch = type->arch ();
350   const struct builtin_type *builtin = builtin_type (gdbarch);
351
352   if (TYPE_LENGTH (type) == TYPE_LENGTH (builtin->builtin_float))
353     type = builtin->builtin_float;
354   else if (TYPE_LENGTH (type) == TYPE_LENGTH (builtin->builtin_double))
355     type = builtin->builtin_double;
356   else if (TYPE_LENGTH (type) == TYPE_LENGTH (builtin->builtin_long_double))
357     type = builtin->builtin_long_double;
358
359   return type;
360 }
361
362 /* Print a scalar of data of type TYPE, pointed to in GDB by VALADDR,
363    according to OPTIONS and SIZE on STREAM.  Formats s and i are not
364    supported at this level.  */
365
366 void
367 print_scalar_formatted (const gdb_byte *valaddr, struct type *type,
368                         const struct value_print_options *options,
369                         int size, struct ui_file *stream)
370 {
371   struct gdbarch *gdbarch = type->arch ();
372   unsigned int len = TYPE_LENGTH (type);
373   enum bfd_endian byte_order = type_byte_order (type);
374
375   /* String printing should go through val_print_scalar_formatted.  */
376   gdb_assert (options->format != 's');
377
378   /* If the value is a pointer, and pointers and addresses are not the
379      same, then at this point, the value's length (in target bytes) is
380      gdbarch_addr_bit/TARGET_CHAR_BIT, not TYPE_LENGTH (type).  */
381   if (type->code () == TYPE_CODE_PTR)
382     len = gdbarch_addr_bit (gdbarch) / TARGET_CHAR_BIT;
383
384   /* If we are printing it as unsigned, truncate it in case it is actually
385      a negative signed value (e.g. "print/u (short)-1" should print 65535
386      (if shorts are 16 bits) instead of 4294967295).  */
387   if (options->format != 'c'
388       && (options->format != 'd' || type->is_unsigned ()))
389     {
390       if (len < TYPE_LENGTH (type) && byte_order == BFD_ENDIAN_BIG)
391         valaddr += TYPE_LENGTH (type) - len;
392     }
393
394   /* Allow LEN == 0, and in this case, don't assume that VALADDR is
395      valid.  */
396   const gdb_byte zero = 0;
397   if (len == 0)
398     {
399       len = 1;
400       valaddr = &zero;
401     }
402
403   if (size != 0 && (options->format == 'x' || options->format == 't'))
404     {
405       /* Truncate to fit.  */
406       unsigned newlen;
407       switch (size)
408         {
409         case 'b':
410           newlen = 1;
411           break;
412         case 'h':
413           newlen = 2;
414           break;
415         case 'w':
416           newlen = 4;
417           break;
418         case 'g':
419           newlen = 8;
420           break;
421         default:
422           error (_("Undefined output size \"%c\"."), size);
423         }
424       if (newlen < len && byte_order == BFD_ENDIAN_BIG)
425         valaddr += len - newlen;
426       len = newlen;
427     }
428
429   /* Historically gdb has printed floats by first casting them to a
430      long, and then printing the long.  PR cli/16242 suggests changing
431      this to using C-style hex float format.
432
433      Biased range types and sub-word scalar types must also be handled
434      here; the value is correctly computed by unpack_long.  */
435   gdb::byte_vector converted_bytes;
436   /* Some cases below will unpack the value again.  In the biased
437      range case, we want to avoid this, so we store the unpacked value
438      here for possible use later.  */
439   gdb::optional<LONGEST> val_long;
440   if (((type->code () == TYPE_CODE_FLT
441         || is_fixed_point_type (type))
442        && (options->format == 'o'
443            || options->format == 'x'
444            || options->format == 't'
445            || options->format == 'z'
446            || options->format == 'd'
447            || options->format == 'u'))
448       || (type->code () == TYPE_CODE_RANGE && type->bounds ()->bias != 0)
449       || type->bit_size_differs_p ())
450     {
451       val_long.emplace (unpack_long (type, valaddr));
452       converted_bytes.resize (TYPE_LENGTH (type));
453       store_signed_integer (converted_bytes.data (), TYPE_LENGTH (type),
454                             byte_order, *val_long);
455       valaddr = converted_bytes.data ();
456     }
457
458   /* Printing a non-float type as 'f' will interpret the data as if it were
459      of a floating-point type of the same length, if that exists.  Otherwise,
460      the data is printed as integer.  */
461   char format = options->format;
462   if (format == 'f' && type->code () != TYPE_CODE_FLT)
463     {
464       type = float_type_from_length (type);
465       if (type->code () != TYPE_CODE_FLT)
466         format = 0;
467     }
468
469   switch (format)
470     {
471     case 'o':
472       print_octal_chars (stream, valaddr, len, byte_order);
473       break;
474     case 'd':
475       print_decimal_chars (stream, valaddr, len, true, byte_order);
476       break;
477     case 'u':
478       print_decimal_chars (stream, valaddr, len, false, byte_order);
479       break;
480     case 0:
481       if (type->code () != TYPE_CODE_FLT)
482         {
483           print_decimal_chars (stream, valaddr, len, !type->is_unsigned (),
484                                byte_order);
485           break;
486         }
487       /* FALLTHROUGH */
488     case 'f':
489       print_floating (valaddr, type, stream);
490       break;
491
492     case 't':
493       print_binary_chars (stream, valaddr, len, byte_order, size > 0);
494       break;
495     case 'x':
496       print_hex_chars (stream, valaddr, len, byte_order, size > 0);
497       break;
498     case 'z':
499       print_hex_chars (stream, valaddr, len, byte_order, true);
500       break;
501     case 'c':
502       {
503         struct value_print_options opts = *options;
504
505         if (!val_long.has_value ())
506           val_long.emplace (unpack_long (type, valaddr));
507
508         opts.format = 0;
509         if (type->is_unsigned ())
510           type = builtin_type (gdbarch)->builtin_true_unsigned_char;
511         else
512           type = builtin_type (gdbarch)->builtin_true_char;
513
514         value_print (value_from_longest (type, *val_long), stream, &opts);
515       }
516       break;
517
518     case 'a':
519       {
520         if (!val_long.has_value ())
521           val_long.emplace (unpack_long (type, valaddr));
522         print_address (gdbarch, *val_long, stream);
523       }
524       break;
525
526     default:
527       error (_("Undefined output format \"%c\"."), format);
528     }
529 }
530
531 /* Specify default address for `x' command.
532    The `info lines' command uses this.  */
533
534 void
535 set_next_address (struct gdbarch *gdbarch, CORE_ADDR addr)
536 {
537   struct type *ptr_type = builtin_type (gdbarch)->builtin_data_ptr;
538
539   next_gdbarch = gdbarch;
540   next_address = addr;
541
542   /* Make address available to the user as $_.  */
543   set_internalvar (lookup_internalvar ("_"),
544                    value_from_pointer (ptr_type, addr));
545 }
546
547 /* Optionally print address ADDR symbolically as <SYMBOL+OFFSET> on STREAM,
548    after LEADIN.  Print nothing if no symbolic name is found nearby.
549    Optionally also print source file and line number, if available.
550    DO_DEMANGLE controls whether to print a symbol in its native "raw" form,
551    or to interpret it as a possible C++ name and convert it back to source
552    form.  However note that DO_DEMANGLE can be overridden by the specific
553    settings of the demangle and asm_demangle variables.  Returns
554    non-zero if anything was printed; zero otherwise.  */
555
556 int
557 print_address_symbolic (struct gdbarch *gdbarch, CORE_ADDR addr,
558                         struct ui_file *stream,
559                         int do_demangle, const char *leadin)
560 {
561   std::string name, filename;
562   int unmapped = 0;
563   int offset = 0;
564   int line = 0;
565
566   if (build_address_symbolic (gdbarch, addr, do_demangle, false, &name,
567                               &offset, &filename, &line, &unmapped))
568     return 0;
569
570   fputs_filtered (leadin, stream);
571   if (unmapped)
572     fputs_filtered ("<*", stream);
573   else
574     fputs_filtered ("<", stream);
575   fputs_styled (name.c_str (), function_name_style.style (), stream);
576   if (offset != 0)
577     fprintf_filtered (stream, "%+d", offset);
578
579   /* Append source filename and line number if desired.  Give specific
580      line # of this addr, if we have it; else line # of the nearest symbol.  */
581   if (print_symbol_filename && !filename.empty ())
582     {
583       fputs_filtered (line == -1 ? " in " : " at ", stream);
584       fputs_styled (filename.c_str (), file_name_style.style (), stream);
585       if (line != -1)
586         fprintf_filtered (stream, ":%d", line);
587     }
588   if (unmapped)
589     fputs_filtered ("*>", stream);
590   else
591     fputs_filtered (">", stream);
592
593   return 1;
594 }
595
596 /* See valprint.h.  */
597
598 int
599 build_address_symbolic (struct gdbarch *gdbarch,
600                         CORE_ADDR addr,  /* IN */
601                         bool do_demangle, /* IN */
602                         bool prefer_sym_over_minsym, /* IN */
603                         std::string *name, /* OUT */
604                         int *offset,     /* OUT */
605                         std::string *filename, /* OUT */
606                         int *line,       /* OUT */
607                         int *unmapped)   /* OUT */
608 {
609   struct bound_minimal_symbol msymbol;
610   struct symbol *symbol;
611   CORE_ADDR name_location = 0;
612   struct obj_section *section = NULL;
613   const char *name_temp = "";
614   
615   /* Let's say it is mapped (not unmapped).  */
616   *unmapped = 0;
617
618   /* Determine if the address is in an overlay, and whether it is
619      mapped.  */
620   if (overlay_debugging)
621     {
622       section = find_pc_overlay (addr);
623       if (pc_in_unmapped_range (addr, section))
624         {
625           *unmapped = 1;
626           addr = overlay_mapped_address (addr, section);
627         }
628     }
629
630   /* Try to find the address in both the symbol table and the minsyms. 
631      In most cases, we'll prefer to use the symbol instead of the
632      minsym.  However, there are cases (see below) where we'll choose
633      to use the minsym instead.  */
634
635   /* This is defective in the sense that it only finds text symbols.  So
636      really this is kind of pointless--we should make sure that the
637      minimal symbols have everything we need (by changing that we could
638      save some memory, but for many debug format--ELF/DWARF or
639      anything/stabs--it would be inconvenient to eliminate those minimal
640      symbols anyway).  */
641   msymbol = lookup_minimal_symbol_by_pc_section (addr, section);
642   symbol = find_pc_sect_function (addr, section);
643
644   if (symbol)
645     {
646       /* If this is a function (i.e. a code address), strip out any
647          non-address bits.  For instance, display a pointer to the
648          first instruction of a Thumb function as <function>; the
649          second instruction will be <function+2>, even though the
650          pointer is <function+3>.  This matches the ISA behavior.  */
651       addr = gdbarch_addr_bits_remove (gdbarch, addr);
652
653       name_location = BLOCK_ENTRY_PC (SYMBOL_BLOCK_VALUE (symbol));
654       if (do_demangle || asm_demangle)
655         name_temp = symbol->print_name ();
656       else
657         name_temp = symbol->linkage_name ();
658     }
659
660   if (msymbol.minsym != NULL
661       && MSYMBOL_HAS_SIZE (msymbol.minsym)
662       && MSYMBOL_SIZE (msymbol.minsym) == 0
663       && MSYMBOL_TYPE (msymbol.minsym) != mst_text
664       && MSYMBOL_TYPE (msymbol.minsym) != mst_text_gnu_ifunc
665       && MSYMBOL_TYPE (msymbol.minsym) != mst_file_text)
666     msymbol.minsym = NULL;
667
668   if (msymbol.minsym != NULL)
669     {
670       /* Use the minsym if no symbol is found.
671       
672          Additionally, use the minsym instead of a (found) symbol if
673          the following conditions all hold:
674            1) The prefer_sym_over_minsym flag is false.
675            2) The minsym address is identical to that of the address under
676               consideration.
677            3) The symbol address is not identical to that of the address
678               under consideration.  */
679       if (symbol == NULL ||
680            (!prefer_sym_over_minsym
681             && BMSYMBOL_VALUE_ADDRESS (msymbol) == addr
682             && name_location != addr))
683         {
684           /* If this is a function (i.e. a code address), strip out any
685              non-address bits.  For instance, display a pointer to the
686              first instruction of a Thumb function as <function>; the
687              second instruction will be <function+2>, even though the
688              pointer is <function+3>.  This matches the ISA behavior.  */
689           if (MSYMBOL_TYPE (msymbol.minsym) == mst_text
690               || MSYMBOL_TYPE (msymbol.minsym) == mst_text_gnu_ifunc
691               || MSYMBOL_TYPE (msymbol.minsym) == mst_file_text
692               || MSYMBOL_TYPE (msymbol.minsym) == mst_solib_trampoline)
693             addr = gdbarch_addr_bits_remove (gdbarch, addr);
694
695           symbol = 0;
696           name_location = BMSYMBOL_VALUE_ADDRESS (msymbol);
697           if (do_demangle || asm_demangle)
698             name_temp = msymbol.minsym->print_name ();
699           else
700             name_temp = msymbol.minsym->linkage_name ();
701         }
702     }
703   if (symbol == NULL && msymbol.minsym == NULL)
704     return 1;
705
706   /* If the nearest symbol is too far away, don't print anything symbolic.  */
707
708   /* For when CORE_ADDR is larger than unsigned int, we do math in
709      CORE_ADDR.  But when we detect unsigned wraparound in the
710      CORE_ADDR math, we ignore this test and print the offset,
711      because addr+max_symbolic_offset has wrapped through the end
712      of the address space back to the beginning, giving bogus comparison.  */
713   if (addr > name_location + max_symbolic_offset
714       && name_location + max_symbolic_offset > name_location)
715     return 1;
716
717   *offset = (LONGEST) addr - name_location;
718
719   *name = name_temp;
720
721   if (print_symbol_filename)
722     {
723       struct symtab_and_line sal;
724
725       sal = find_pc_sect_line (addr, section, 0);
726
727       if (sal.symtab)
728         {
729           *filename = symtab_to_filename_for_display (sal.symtab);
730           *line = sal.line;
731         }
732     }
733   return 0;
734 }
735
736
737 /* Print address ADDR symbolically on STREAM.
738    First print it as a number.  Then perhaps print
739    <SYMBOL + OFFSET> after the number.  */
740
741 void
742 print_address (struct gdbarch *gdbarch,
743                CORE_ADDR addr, struct ui_file *stream)
744 {
745   fputs_styled (paddress (gdbarch, addr), address_style.style (), stream);
746   print_address_symbolic (gdbarch, addr, stream, asm_demangle, " ");
747 }
748
749 /* Return a prefix for instruction address:
750    "=> " for current instruction, else "   ".  */
751
752 const char *
753 pc_prefix (CORE_ADDR addr)
754 {
755   if (has_stack_frames ())
756     {
757       struct frame_info *frame;
758       CORE_ADDR pc;
759
760       frame = get_selected_frame (NULL);
761       if (get_frame_pc_if_available (frame, &pc) && pc == addr)
762         return "=> ";
763     }
764   return "   ";
765 }
766
767 /* Print address ADDR symbolically on STREAM.  Parameter DEMANGLE
768    controls whether to print the symbolic name "raw" or demangled.
769    Return non-zero if anything was printed; zero otherwise.  */
770
771 int
772 print_address_demangle (const struct value_print_options *opts,
773                         struct gdbarch *gdbarch, CORE_ADDR addr,
774                         struct ui_file *stream, int do_demangle)
775 {
776   if (opts->addressprint)
777     {
778       fputs_styled (paddress (gdbarch, addr), address_style.style (), stream);
779       print_address_symbolic (gdbarch, addr, stream, do_demangle, " ");
780     }
781   else
782     {
783       return print_address_symbolic (gdbarch, addr, stream, do_demangle, "");
784     }
785   return 1;
786 }
787 \f
788
789 /* Find the address of the instruction that is INST_COUNT instructions before
790    the instruction at ADDR.
791    Since some architectures have variable-length instructions, we can't just
792    simply subtract INST_COUNT * INSN_LEN from ADDR.  Instead, we use line
793    number information to locate the nearest known instruction boundary,
794    and disassemble forward from there.  If we go out of the symbol range
795    during disassembling, we return the lowest address we've got so far and
796    set the number of instructions read to INST_READ.  */
797
798 static CORE_ADDR
799 find_instruction_backward (struct gdbarch *gdbarch, CORE_ADDR addr,
800                            int inst_count, int *inst_read)
801 {
802   /* The vector PCS is used to store instruction addresses within
803      a pc range.  */
804   CORE_ADDR loop_start, loop_end, p;
805   std::vector<CORE_ADDR> pcs;
806   struct symtab_and_line sal;
807
808   *inst_read = 0;
809   loop_start = loop_end = addr;
810
811   /* In each iteration of the outer loop, we get a pc range that ends before
812      LOOP_START, then we count and store every instruction address of the range
813      iterated in the loop.
814      If the number of instructions counted reaches INST_COUNT, return the
815      stored address that is located INST_COUNT instructions back from ADDR.
816      If INST_COUNT is not reached, we subtract the number of counted
817      instructions from INST_COUNT, and go to the next iteration.  */
818   do
819     {
820       pcs.clear ();
821       sal = find_pc_sect_line (loop_start, NULL, 1);
822       if (sal.line <= 0)
823         {
824           /* We reach here when line info is not available.  In this case,
825              we print a message and just exit the loop.  The return value
826              is calculated after the loop.  */
827           printf_filtered (_("No line number information available "
828                              "for address "));
829           wrap_here ("  ");
830           print_address (gdbarch, loop_start - 1, gdb_stdout);
831           printf_filtered ("\n");
832           break;
833         }
834
835       loop_end = loop_start;
836       loop_start = sal.pc;
837
838       /* This loop pushes instruction addresses in the range from
839          LOOP_START to LOOP_END.  */
840       for (p = loop_start; p < loop_end;)
841         {
842           pcs.push_back (p);
843           p += gdb_insn_length (gdbarch, p);
844         }
845
846       inst_count -= pcs.size ();
847       *inst_read += pcs.size ();
848     }
849   while (inst_count > 0);
850
851   /* After the loop, the vector PCS has instruction addresses of the last
852      source line we processed, and INST_COUNT has a negative value.
853      We return the address at the index of -INST_COUNT in the vector for
854      the reason below.
855      Let's assume the following instruction addresses and run 'x/-4i 0x400e'.
856        Line X of File
857           0x4000
858           0x4001
859           0x4005
860        Line Y of File
861           0x4009
862           0x400c
863        => 0x400e
864           0x4011
865      find_instruction_backward is called with INST_COUNT = 4 and expected to
866      return 0x4001.  When we reach here, INST_COUNT is set to -1 because
867      it was subtracted by 2 (from Line Y) and 3 (from Line X).  The value
868      4001 is located at the index 1 of the last iterated line (= Line X),
869      which is simply calculated by -INST_COUNT.
870      The case when the length of PCS is 0 means that we reached an area for
871      which line info is not available.  In such case, we return LOOP_START,
872      which was the lowest instruction address that had line info.  */
873   p = pcs.size () > 0 ? pcs[-inst_count] : loop_start;
874
875   /* INST_READ includes all instruction addresses in a pc range.  Need to
876      exclude the beginning part up to the address we're returning.  That
877      is, exclude {0x4000} in the example above.  */
878   if (inst_count < 0)
879     *inst_read += inst_count;
880
881   return p;
882 }
883
884 /* Backward read LEN bytes of target memory from address MEMADDR + LEN,
885    placing the results in GDB's memory from MYADDR + LEN.  Returns
886    a count of the bytes actually read.  */
887
888 static int
889 read_memory_backward (struct gdbarch *gdbarch,
890                       CORE_ADDR memaddr, gdb_byte *myaddr, int len)
891 {
892   int errcode;
893   int nread;      /* Number of bytes actually read.  */
894
895   /* First try a complete read.  */
896   errcode = target_read_memory (memaddr, myaddr, len);
897   if (errcode == 0)
898     {
899       /* Got it all.  */
900       nread = len;
901     }
902   else
903     {
904       /* Loop, reading one byte at a time until we get as much as we can.  */
905       memaddr += len;
906       myaddr += len;
907       for (nread = 0; nread < len; ++nread)
908         {
909           errcode = target_read_memory (--memaddr, --myaddr, 1);
910           if (errcode != 0)
911             {
912               /* The read was unsuccessful, so exit the loop.  */
913               printf_filtered (_("Cannot access memory at address %s\n"),
914                                paddress (gdbarch, memaddr));
915               break;
916             }
917         }
918     }
919   return nread;
920 }
921
922 /* Returns true if X (which is LEN bytes wide) is the number zero.  */
923
924 static int
925 integer_is_zero (const gdb_byte *x, int len)
926 {
927   int i = 0;
928
929   while (i < len && x[i] == 0)
930     ++i;
931   return (i == len);
932 }
933
934 /* Find the start address of a string in which ADDR is included.
935    Basically we search for '\0' and return the next address,
936    but if OPTIONS->PRINT_MAX is smaller than the length of a string,
937    we stop searching and return the address to print characters as many as
938    PRINT_MAX from the string.  */
939
940 static CORE_ADDR
941 find_string_backward (struct gdbarch *gdbarch,
942                       CORE_ADDR addr, int count, int char_size,
943                       const struct value_print_options *options,
944                       int *strings_counted)
945 {
946   const int chunk_size = 0x20;
947   int read_error = 0;
948   int chars_read = 0;
949   int chars_to_read = chunk_size;
950   int chars_counted = 0;
951   int count_original = count;
952   CORE_ADDR string_start_addr = addr;
953
954   gdb_assert (char_size == 1 || char_size == 2 || char_size == 4);
955   gdb::byte_vector buffer (chars_to_read * char_size);
956   while (count > 0 && read_error == 0)
957     {
958       int i;
959
960       addr -= chars_to_read * char_size;
961       chars_read = read_memory_backward (gdbarch, addr, buffer.data (),
962                                          chars_to_read * char_size);
963       chars_read /= char_size;
964       read_error = (chars_read == chars_to_read) ? 0 : 1;
965       /* Searching for '\0' from the end of buffer in backward direction.  */
966       for (i = 0; i < chars_read && count > 0 ; ++i, ++chars_counted)
967         {
968           int offset = (chars_to_read - i - 1) * char_size;
969
970           if (integer_is_zero (&buffer[offset], char_size)
971               || chars_counted == options->print_max)
972             {
973               /* Found '\0' or reached print_max.  As OFFSET is the offset to
974                  '\0', we add CHAR_SIZE to return the start address of
975                  a string.  */
976               --count;
977               string_start_addr = addr + offset + char_size;
978               chars_counted = 0;
979             }
980         }
981     }
982
983   /* Update STRINGS_COUNTED with the actual number of loaded strings.  */
984   *strings_counted = count_original - count;
985
986   if (read_error != 0)
987     {
988       /* In error case, STRING_START_ADDR is pointing to the string that
989          was last successfully loaded.  Rewind the partially loaded string.  */
990       string_start_addr -= chars_counted * char_size;
991     }
992
993   return string_start_addr;
994 }
995
996 /* Examine data at address ADDR in format FMT.
997    Fetch it from memory and print on gdb_stdout.  */
998
999 static void
1000 do_examine (struct format_data fmt, struct gdbarch *gdbarch, CORE_ADDR addr)
1001 {
1002   char format = 0;
1003   char size;
1004   int count = 1;
1005   struct type *val_type = NULL;
1006   int i;
1007   int maxelts;
1008   struct value_print_options opts;
1009   int need_to_update_next_address = 0;
1010   CORE_ADDR addr_rewound = 0;
1011
1012   format = fmt.format;
1013   size = fmt.size;
1014   count = fmt.count;
1015   next_gdbarch = gdbarch;
1016   next_address = addr;
1017
1018   /* Instruction format implies fetch single bytes
1019      regardless of the specified size.
1020      The case of strings is handled in decode_format, only explicit
1021      size operator are not changed to 'b'.  */
1022   if (format == 'i')
1023     size = 'b';
1024
1025   if (size == 'a')
1026     {
1027       /* Pick the appropriate size for an address.  */
1028       if (gdbarch_ptr_bit (next_gdbarch) == 64)
1029         size = 'g';
1030       else if (gdbarch_ptr_bit (next_gdbarch) == 32)
1031         size = 'w';
1032       else if (gdbarch_ptr_bit (next_gdbarch) == 16)
1033         size = 'h';
1034       else
1035         /* Bad value for gdbarch_ptr_bit.  */
1036         internal_error (__FILE__, __LINE__,
1037                         _("failed internal consistency check"));
1038     }
1039
1040   if (size == 'b')
1041     val_type = builtin_type (next_gdbarch)->builtin_int8;
1042   else if (size == 'h')
1043     val_type = builtin_type (next_gdbarch)->builtin_int16;
1044   else if (size == 'w')
1045     val_type = builtin_type (next_gdbarch)->builtin_int32;
1046   else if (size == 'g')
1047     val_type = builtin_type (next_gdbarch)->builtin_int64;
1048
1049   if (format == 's')
1050     {
1051       struct type *char_type = NULL;
1052
1053       /* Search for "char16_t"  or "char32_t" types or fall back to 8-bit char
1054          if type is not found.  */
1055       if (size == 'h')
1056         char_type = builtin_type (next_gdbarch)->builtin_char16;
1057       else if (size == 'w')
1058         char_type = builtin_type (next_gdbarch)->builtin_char32;
1059       if (char_type)
1060         val_type = char_type;
1061       else
1062         {
1063           if (size != '\0' && size != 'b')
1064             warning (_("Unable to display strings with "
1065                        "size '%c', using 'b' instead."), size);
1066           size = 'b';
1067           val_type = builtin_type (next_gdbarch)->builtin_int8;
1068         }
1069     }
1070
1071   maxelts = 8;
1072   if (size == 'w')
1073     maxelts = 4;
1074   if (size == 'g')
1075     maxelts = 2;
1076   if (format == 's' || format == 'i')
1077     maxelts = 1;
1078
1079   get_formatted_print_options (&opts, format);
1080
1081   if (count < 0)
1082     {
1083       /* This is the negative repeat count case.
1084          We rewind the address based on the given repeat count and format,
1085          then examine memory from there in forward direction.  */
1086
1087       count = -count;
1088       if (format == 'i')
1089         {
1090           next_address = find_instruction_backward (gdbarch, addr, count,
1091                                                     &count);
1092         }
1093       else if (format == 's')
1094         {
1095           next_address = find_string_backward (gdbarch, addr, count,
1096                                                TYPE_LENGTH (val_type),
1097                                                &opts, &count);
1098         }
1099       else
1100         {
1101           next_address = addr - count * TYPE_LENGTH (val_type);
1102         }
1103
1104       /* The following call to print_formatted updates next_address in every
1105          iteration.  In backward case, we store the start address here
1106          and update next_address with it before exiting the function.  */
1107       addr_rewound = (format == 's'
1108                       ? next_address - TYPE_LENGTH (val_type)
1109                       : next_address);
1110       need_to_update_next_address = 1;
1111     }
1112
1113   /* Whether we need to print the memory tag information for the current
1114      address range.  */
1115   bool print_range_tag = true;
1116   uint32_t gsize = gdbarch_memtag_granule_size (gdbarch);
1117
1118   /* Print as many objects as specified in COUNT, at most maxelts per line,
1119      with the address of the next one at the start of each line.  */
1120
1121   while (count > 0)
1122     {
1123       QUIT;
1124
1125       CORE_ADDR tag_laddr = 0, tag_haddr = 0;
1126
1127       /* Print the memory tag information if requested.  */
1128       if (fmt.print_tags && print_range_tag
1129           && target_supports_memory_tagging ())
1130         {
1131           tag_laddr = align_down (next_address, gsize);
1132           tag_haddr = align_down (next_address + gsize, gsize);
1133
1134           struct value *v_addr
1135             = value_from_ulongest (builtin_type (gdbarch)->builtin_data_ptr,
1136                                    tag_laddr);
1137
1138           if (gdbarch_tagged_address_p (target_gdbarch (), v_addr))
1139             {
1140               /* Fetch the allocation tag.  */
1141               struct value *tag
1142                 = gdbarch_get_memtag (gdbarch, v_addr, memtag_type::allocation);
1143               std::string atag
1144                 = gdbarch_memtag_to_string (gdbarch, tag);
1145
1146               if (!atag.empty ())
1147                 {
1148                   printf_filtered (_("<Allocation Tag %s for range [%s,%s)>\n"),
1149                                    atag.c_str (),
1150                                    paddress (gdbarch, tag_laddr),
1151                                    paddress (gdbarch, tag_haddr));
1152                 }
1153             }
1154           print_range_tag = false;
1155         }
1156
1157       if (format == 'i')
1158         fputs_filtered (pc_prefix (next_address), gdb_stdout);
1159       print_address (next_gdbarch, next_address, gdb_stdout);
1160       printf_filtered (":");
1161       for (i = maxelts;
1162            i > 0 && count > 0;
1163            i--, count--)
1164         {
1165           printf_filtered ("\t");
1166           /* Note that print_formatted sets next_address for the next
1167              object.  */
1168           last_examine_address = next_address;
1169
1170           /* The value to be displayed is not fetched greedily.
1171              Instead, to avoid the possibility of a fetched value not
1172              being used, its retrieval is delayed until the print code
1173              uses it.  When examining an instruction stream, the
1174              disassembler will perform its own memory fetch using just
1175              the address stored in LAST_EXAMINE_VALUE.  FIXME: Should
1176              the disassembler be modified so that LAST_EXAMINE_VALUE
1177              is left with the byte sequence from the last complete
1178              instruction fetched from memory?  */
1179           last_examine_value
1180             = release_value (value_at_lazy (val_type, next_address));
1181
1182           print_formatted (last_examine_value.get (), size, &opts, gdb_stdout);
1183
1184           /* Display any branch delay slots following the final insn.  */
1185           if (format == 'i' && count == 1)
1186             count += branch_delay_insns;
1187
1188           /* Update the tag range based on the current address being
1189              processed.  */
1190           if (tag_haddr <= next_address)
1191               print_range_tag = true;
1192         }
1193       printf_filtered ("\n");
1194     }
1195
1196   if (need_to_update_next_address)
1197     next_address = addr_rewound;
1198 }
1199 \f
1200 static void
1201 validate_format (struct format_data fmt, const char *cmdname)
1202 {
1203   if (fmt.size != 0)
1204     error (_("Size letters are meaningless in \"%s\" command."), cmdname);
1205   if (fmt.count != 1)
1206     error (_("Item count other than 1 is meaningless in \"%s\" command."),
1207            cmdname);
1208   if (fmt.format == 'i')
1209     error (_("Format letter \"%c\" is meaningless in \"%s\" command."),
1210            fmt.format, cmdname);
1211 }
1212
1213 /* Parse print command format string into *OPTS and update *EXPP.
1214    CMDNAME should name the current command.  */
1215
1216 void
1217 print_command_parse_format (const char **expp, const char *cmdname,
1218                             value_print_options *opts)
1219 {
1220   const char *exp = *expp;
1221
1222   /* opts->raw value might already have been set by 'set print raw-values'
1223      or by using 'print -raw-values'.
1224      So, do not set opts->raw to 0, only set it to 1 if /r is given.  */
1225   if (exp && *exp == '/')
1226     {
1227       format_data fmt;
1228
1229       exp++;
1230       fmt = decode_format (&exp, last_format, 0);
1231       validate_format (fmt, cmdname);
1232       last_format = fmt.format;
1233
1234       opts->format = fmt.format;
1235       opts->raw = opts->raw || fmt.raw;
1236     }
1237   else
1238     {
1239       opts->format = 0;
1240     }
1241
1242   *expp = exp;
1243 }
1244
1245 /* See valprint.h.  */
1246
1247 void
1248 print_value (value *val, const value_print_options &opts)
1249 {
1250   int histindex = record_latest_value (val);
1251
1252   annotate_value_history_begin (histindex, value_type (val));
1253
1254   printf_filtered ("$%d = ", histindex);
1255
1256   annotate_value_history_value ();
1257
1258   print_formatted (val, 0, &opts, gdb_stdout);
1259   printf_filtered ("\n");
1260
1261   annotate_value_history_end ();
1262 }
1263
1264 /* Returns true if memory tags should be validated.  False otherwise.  */
1265
1266 static bool
1267 should_validate_memtags (struct value *value)
1268 {
1269   if (target_supports_memory_tagging ()
1270       && gdbarch_tagged_address_p (target_gdbarch (), value))
1271     {
1272       gdb_assert (value != nullptr && value_type (value) != nullptr);
1273
1274       enum type_code code = value_type (value)->code ();
1275
1276       return (code == TYPE_CODE_PTR
1277               || code == TYPE_CODE_REF
1278               || code == TYPE_CODE_METHODPTR
1279               || code == TYPE_CODE_MEMBERPTR);
1280     }
1281   return false;
1282 }
1283
1284 /* Helper for parsing arguments for print_command_1.  */
1285
1286 static struct value *
1287 process_print_command_args (const char *args, value_print_options *print_opts,
1288                             bool voidprint)
1289 {
1290   get_user_print_options (print_opts);
1291   /* Override global settings with explicit options, if any.  */
1292   auto group = make_value_print_options_def_group (print_opts);
1293   gdb::option::process_options
1294     (&args, gdb::option::PROCESS_OPTIONS_REQUIRE_DELIMITER, group);
1295
1296   print_command_parse_format (&args, "print", print_opts);
1297
1298   const char *exp = args;
1299
1300   if (exp != nullptr && *exp)
1301     {
1302       /* VOIDPRINT is true to indicate that we do want to print a void
1303          value, so invert it for parse_expression.  */
1304       expression_up expr = parse_expression (exp, nullptr, !voidprint);
1305       return evaluate_expression (expr.get ());
1306     }
1307
1308   return access_value_history (0);
1309 }
1310
1311 /* Implementation of the "print" and "call" commands.  */
1312
1313 static void
1314 print_command_1 (const char *args, int voidprint)
1315 {
1316   value_print_options print_opts;
1317
1318   struct value *val = process_print_command_args (args, &print_opts, voidprint);
1319
1320   if (voidprint || (val && value_type (val) &&
1321                     value_type (val)->code () != TYPE_CODE_VOID))
1322     {
1323       /* If memory tagging validation is on, check if the tag is valid.  */
1324       if (print_opts.memory_tag_violations && should_validate_memtags (val)
1325           && !gdbarch_memtag_matches_p (target_gdbarch (), val))
1326         {
1327           /* Fetch the logical tag.  */
1328           struct value *tag
1329             = gdbarch_get_memtag (target_gdbarch (), val,
1330                                   memtag_type::logical);
1331           std::string ltag
1332             = gdbarch_memtag_to_string (target_gdbarch (), tag);
1333
1334           /* Fetch the allocation tag.  */
1335           tag = gdbarch_get_memtag (target_gdbarch (), val,
1336                                     memtag_type::allocation);
1337           std::string atag
1338             = gdbarch_memtag_to_string (target_gdbarch (), tag);
1339
1340           printf_filtered (_("Logical tag (%s) does not match the "
1341                              "allocation tag (%s).\n"),
1342                            ltag.c_str (), atag.c_str ());
1343         }
1344       print_value (val, print_opts);
1345     }
1346 }
1347
1348 /* Called from command completion function to skip over /FMT
1349    specifications, allowing the rest of the line to be completed.  Returns
1350    true if the /FMT is at the end of the current line and there is nothing
1351    left to complete, otherwise false is returned.
1352
1353    In either case *ARGS can be updated to point after any part of /FMT that
1354    is present.
1355
1356    This function is designed so that trying to complete '/' will offer no
1357    completions, the user needs to insert the format specification
1358    themselves.  Trying to complete '/FMT' (where FMT is any non-empty set
1359    of alpha-numeric characters) will cause readline to insert a single
1360    space, setting the user up to enter the expression.  */
1361
1362 static bool
1363 skip_over_slash_fmt (completion_tracker &tracker, const char **args)
1364 {
1365   const char *text = *args;
1366
1367   if (text[0] == '/')
1368     {
1369       bool in_fmt;
1370       tracker.set_use_custom_word_point (true);
1371
1372       if (text[1] == '\0')
1373         {
1374           /* The user tried to complete after typing just the '/' character
1375              of the /FMT string.  Step the completer past the '/', but we
1376              don't offer any completions.  */
1377           in_fmt = true;
1378           ++text;
1379         }
1380       else
1381         {
1382           /* The user has typed some characters after the '/', we assume
1383              this is a complete /FMT string, first skip over it.  */
1384           text = skip_to_space (text);
1385
1386           if (*text == '\0')
1387             {
1388               /* We're at the end of the input string.  The user has typed
1389                  '/FMT' and asked for a completion.  Push an empty
1390                  completion string, this will cause readline to insert a
1391                  space so the user now has '/FMT '.  */
1392               in_fmt = true;
1393               tracker.add_completion (make_unique_xstrdup (text));
1394             }
1395           else
1396             {
1397               /* The user has already typed things after the /FMT, skip the
1398                  whitespace and return false.  Whoever called this function
1399                  should then try to complete what comes next.  */
1400               in_fmt = false;
1401               text = skip_spaces (text);
1402             }
1403         }
1404
1405       tracker.advance_custom_word_point_by (text - *args);
1406       *args = text;
1407       return in_fmt;
1408     }
1409
1410   return false;
1411 }
1412
1413 /* See valprint.h.  */
1414
1415 void
1416 print_command_completer (struct cmd_list_element *ignore,
1417                          completion_tracker &tracker,
1418                          const char *text, const char * /*word*/)
1419 {
1420   const auto group = make_value_print_options_def_group (nullptr);
1421   if (gdb::option::complete_options
1422       (tracker, &text, gdb::option::PROCESS_OPTIONS_REQUIRE_DELIMITER, group))
1423     return;
1424
1425   if (skip_over_slash_fmt (tracker, &text))
1426     return;
1427
1428   const char *word = advance_to_expression_complete_word_point (tracker, text);
1429   expression_completer (ignore, tracker, text, word);
1430 }
1431
1432 static void
1433 print_command (const char *exp, int from_tty)
1434 {
1435   print_command_1 (exp, true);
1436 }
1437
1438 /* Same as print, except it doesn't print void results.  */
1439 static void
1440 call_command (const char *exp, int from_tty)
1441 {
1442   print_command_1 (exp, false);
1443 }
1444
1445 /* Implementation of the "output" command.  */
1446
1447 void
1448 output_command (const char *exp, int from_tty)
1449 {
1450   char format = 0;
1451   struct value *val;
1452   struct format_data fmt;
1453   struct value_print_options opts;
1454
1455   fmt.size = 0;
1456   fmt.raw = 0;
1457
1458   if (exp && *exp == '/')
1459     {
1460       exp++;
1461       fmt = decode_format (&exp, 0, 0);
1462       validate_format (fmt, "output");
1463       format = fmt.format;
1464     }
1465
1466   expression_up expr = parse_expression (exp);
1467
1468   val = evaluate_expression (expr.get ());
1469
1470   annotate_value_begin (value_type (val));
1471
1472   get_formatted_print_options (&opts, format);
1473   opts.raw = fmt.raw;
1474   print_formatted (val, fmt.size, &opts, gdb_stdout);
1475
1476   annotate_value_end ();
1477
1478   wrap_here ("");
1479   gdb_flush (gdb_stdout);
1480 }
1481
1482 static void
1483 set_command (const char *exp, int from_tty)
1484 {
1485   expression_up expr = parse_expression (exp);
1486
1487   switch (expr->op->opcode ())
1488     {
1489     case UNOP_PREINCREMENT:
1490     case UNOP_POSTINCREMENT:
1491     case UNOP_PREDECREMENT:
1492     case UNOP_POSTDECREMENT:
1493     case BINOP_ASSIGN:
1494     case BINOP_ASSIGN_MODIFY:
1495     case BINOP_COMMA:
1496       break;
1497     default:
1498       warning
1499         (_("Expression is not an assignment (and might have no effect)"));
1500     }
1501
1502   evaluate_expression (expr.get ());
1503 }
1504
1505 static void
1506 info_symbol_command (const char *arg, int from_tty)
1507 {
1508   struct minimal_symbol *msymbol;
1509   struct obj_section *osect;
1510   CORE_ADDR addr, sect_addr;
1511   int matches = 0;
1512   unsigned int offset;
1513
1514   if (!arg)
1515     error_no_arg (_("address"));
1516
1517   addr = parse_and_eval_address (arg);
1518   for (objfile *objfile : current_program_space->objfiles ())
1519     ALL_OBJFILE_OSECTIONS (objfile, osect)
1520       {
1521         /* Only process each object file once, even if there's a separate
1522            debug file.  */
1523         if (objfile->separate_debug_objfile_backlink)
1524           continue;
1525
1526         sect_addr = overlay_mapped_address (addr, osect);
1527
1528         if (obj_section_addr (osect) <= sect_addr
1529             && sect_addr < obj_section_endaddr (osect)
1530             && (msymbol
1531                 = lookup_minimal_symbol_by_pc_section (sect_addr,
1532                                                        osect).minsym))
1533           {
1534             const char *obj_name, *mapped, *sec_name, *msym_name;
1535             const char *loc_string;
1536
1537             matches = 1;
1538             offset = sect_addr - MSYMBOL_VALUE_ADDRESS (objfile, msymbol);
1539             mapped = section_is_mapped (osect) ? _("mapped") : _("unmapped");
1540             sec_name = osect->the_bfd_section->name;
1541             msym_name = msymbol->print_name ();
1542
1543             /* Don't print the offset if it is zero.
1544                We assume there's no need to handle i18n of "sym + offset".  */
1545             std::string string_holder;
1546             if (offset)
1547               {
1548                 string_holder = string_printf ("%s + %u", msym_name, offset);
1549                 loc_string = string_holder.c_str ();
1550               }
1551             else
1552               loc_string = msym_name;
1553
1554             gdb_assert (osect->objfile && objfile_name (osect->objfile));
1555             obj_name = objfile_name (osect->objfile);
1556
1557             if (current_program_space->multi_objfile_p ())
1558               if (pc_in_unmapped_range (addr, osect))
1559                 if (section_is_overlay (osect))
1560                   printf_filtered (_("%s in load address range of "
1561                                      "%s overlay section %s of %s\n"),
1562                                    loc_string, mapped, sec_name, obj_name);
1563                 else
1564                   printf_filtered (_("%s in load address range of "
1565                                      "section %s of %s\n"),
1566                                    loc_string, sec_name, obj_name);
1567               else
1568                 if (section_is_overlay (osect))
1569                   printf_filtered (_("%s in %s overlay section %s of %s\n"),
1570                                    loc_string, mapped, sec_name, obj_name);
1571                 else
1572                   printf_filtered (_("%s in section %s of %s\n"),
1573                                    loc_string, sec_name, obj_name);
1574             else
1575               if (pc_in_unmapped_range (addr, osect))
1576                 if (section_is_overlay (osect))
1577                   printf_filtered (_("%s in load address range of %s overlay "
1578                                      "section %s\n"),
1579                                    loc_string, mapped, sec_name);
1580                 else
1581                   printf_filtered
1582                     (_("%s in load address range of section %s\n"),
1583                      loc_string, sec_name);
1584               else
1585                 if (section_is_overlay (osect))
1586                   printf_filtered (_("%s in %s overlay section %s\n"),
1587                                    loc_string, mapped, sec_name);
1588                 else
1589                   printf_filtered (_("%s in section %s\n"),
1590                                    loc_string, sec_name);
1591           }
1592       }
1593   if (matches == 0)
1594     printf_filtered (_("No symbol matches %s.\n"), arg);
1595 }
1596
1597 static void
1598 info_address_command (const char *exp, int from_tty)
1599 {
1600   struct gdbarch *gdbarch;
1601   int regno;
1602   struct symbol *sym;
1603   struct bound_minimal_symbol msymbol;
1604   long val;
1605   struct obj_section *section;
1606   CORE_ADDR load_addr, context_pc = 0;
1607   struct field_of_this_result is_a_field_of_this;
1608
1609   if (exp == 0)
1610     error (_("Argument required."));
1611
1612   sym = lookup_symbol (exp, get_selected_block (&context_pc), VAR_DOMAIN,
1613                        &is_a_field_of_this).symbol;
1614   if (sym == NULL)
1615     {
1616       if (is_a_field_of_this.type != NULL)
1617         {
1618           printf_filtered ("Symbol \"");
1619           fprintf_symbol_filtered (gdb_stdout, exp,
1620                                    current_language->la_language, DMGL_ANSI);
1621           printf_filtered ("\" is a field of the local class variable ");
1622           if (current_language->la_language == language_objc)
1623             printf_filtered ("`self'\n");       /* ObjC equivalent of "this" */
1624           else
1625             printf_filtered ("`this'\n");
1626           return;
1627         }
1628
1629       msymbol = lookup_bound_minimal_symbol (exp);
1630
1631       if (msymbol.minsym != NULL)
1632         {
1633           struct objfile *objfile = msymbol.objfile;
1634
1635           gdbarch = objfile->arch ();
1636           load_addr = BMSYMBOL_VALUE_ADDRESS (msymbol);
1637
1638           printf_filtered ("Symbol \"");
1639           fprintf_symbol_filtered (gdb_stdout, exp,
1640                                    current_language->la_language, DMGL_ANSI);
1641           printf_filtered ("\" is at ");
1642           fputs_styled (paddress (gdbarch, load_addr), address_style.style (),
1643                         gdb_stdout);
1644           printf_filtered (" in a file compiled without debugging");
1645           section = msymbol.minsym->obj_section (objfile);
1646           if (section_is_overlay (section))
1647             {
1648               load_addr = overlay_unmapped_address (load_addr, section);
1649               printf_filtered (",\n -- loaded at ");
1650               fputs_styled (paddress (gdbarch, load_addr),
1651                             address_style.style (),
1652                             gdb_stdout);
1653               printf_filtered (" in overlay section %s",
1654                                section->the_bfd_section->name);
1655             }
1656           printf_filtered (".\n");
1657         }
1658       else
1659         error (_("No symbol \"%s\" in current context."), exp);
1660       return;
1661     }
1662
1663   printf_filtered ("Symbol \"");
1664   fprintf_symbol_filtered (gdb_stdout, sym->print_name (),
1665                            current_language->la_language, DMGL_ANSI);
1666   printf_filtered ("\" is ");
1667   val = SYMBOL_VALUE (sym);
1668   if (SYMBOL_OBJFILE_OWNED (sym))
1669     section = sym->obj_section (symbol_objfile (sym));
1670   else
1671     section = NULL;
1672   gdbarch = symbol_arch (sym);
1673
1674   if (SYMBOL_COMPUTED_OPS (sym) != NULL)
1675     {
1676       SYMBOL_COMPUTED_OPS (sym)->describe_location (sym, context_pc,
1677                                                     gdb_stdout);
1678       printf_filtered (".\n");
1679       return;
1680     }
1681
1682   switch (SYMBOL_CLASS (sym))
1683     {
1684     case LOC_CONST:
1685     case LOC_CONST_BYTES:
1686       printf_filtered ("constant");
1687       break;
1688
1689     case LOC_LABEL:
1690       printf_filtered ("a label at address ");
1691       load_addr = SYMBOL_VALUE_ADDRESS (sym);
1692       fputs_styled (paddress (gdbarch, load_addr), address_style.style (),
1693                     gdb_stdout);
1694       if (section_is_overlay (section))
1695         {
1696           load_addr = overlay_unmapped_address (load_addr, section);
1697           printf_filtered (",\n -- loaded at ");
1698           fputs_styled (paddress (gdbarch, load_addr), address_style.style (),
1699                         gdb_stdout);
1700           printf_filtered (" in overlay section %s",
1701                            section->the_bfd_section->name);
1702         }
1703       break;
1704
1705     case LOC_COMPUTED:
1706       gdb_assert_not_reached (_("LOC_COMPUTED variable missing a method"));
1707
1708     case LOC_REGISTER:
1709       /* GDBARCH is the architecture associated with the objfile the symbol
1710          is defined in; the target architecture may be different, and may
1711          provide additional registers.  However, we do not know the target
1712          architecture at this point.  We assume the objfile architecture
1713          will contain all the standard registers that occur in debug info
1714          in that objfile.  */
1715       regno = SYMBOL_REGISTER_OPS (sym)->register_number (sym, gdbarch);
1716
1717       if (SYMBOL_IS_ARGUMENT (sym))
1718         printf_filtered (_("an argument in register %s"),
1719                          gdbarch_register_name (gdbarch, regno));
1720       else
1721         printf_filtered (_("a variable in register %s"),
1722                          gdbarch_register_name (gdbarch, regno));
1723       break;
1724
1725     case LOC_STATIC:
1726       printf_filtered (_("static storage at address "));
1727       load_addr = SYMBOL_VALUE_ADDRESS (sym);
1728       fputs_styled (paddress (gdbarch, load_addr), address_style.style (),
1729                     gdb_stdout);
1730       if (section_is_overlay (section))
1731         {
1732           load_addr = overlay_unmapped_address (load_addr, section);
1733           printf_filtered (_(",\n -- loaded at "));
1734           fputs_styled (paddress (gdbarch, load_addr), address_style.style (),
1735                         gdb_stdout);
1736           printf_filtered (_(" in overlay section %s"),
1737                            section->the_bfd_section->name);
1738         }
1739       break;
1740
1741     case LOC_REGPARM_ADDR:
1742       /* Note comment at LOC_REGISTER.  */
1743       regno = SYMBOL_REGISTER_OPS (sym)->register_number (sym, gdbarch);
1744       printf_filtered (_("address of an argument in register %s"),
1745                        gdbarch_register_name (gdbarch, regno));
1746       break;
1747
1748     case LOC_ARG:
1749       printf_filtered (_("an argument at offset %ld"), val);
1750       break;
1751
1752     case LOC_LOCAL:
1753       printf_filtered (_("a local variable at frame offset %ld"), val);
1754       break;
1755
1756     case LOC_REF_ARG:
1757       printf_filtered (_("a reference argument at offset %ld"), val);
1758       break;
1759
1760     case LOC_TYPEDEF:
1761       printf_filtered (_("a typedef"));
1762       break;
1763
1764     case LOC_BLOCK:
1765       printf_filtered (_("a function at address "));
1766       load_addr = BLOCK_ENTRY_PC (SYMBOL_BLOCK_VALUE (sym));
1767       fputs_styled (paddress (gdbarch, load_addr), address_style.style (),
1768                     gdb_stdout);
1769       if (section_is_overlay (section))
1770         {
1771           load_addr = overlay_unmapped_address (load_addr, section);
1772           printf_filtered (_(",\n -- loaded at "));
1773           fputs_styled (paddress (gdbarch, load_addr), address_style.style (),
1774                         gdb_stdout);
1775           printf_filtered (_(" in overlay section %s"),
1776                            section->the_bfd_section->name);
1777         }
1778       break;
1779
1780     case LOC_UNRESOLVED:
1781       {
1782         struct bound_minimal_symbol msym;
1783
1784         msym = lookup_bound_minimal_symbol (sym->linkage_name ());
1785         if (msym.minsym == NULL)
1786           printf_filtered ("unresolved");
1787         else
1788           {
1789             section = msym.obj_section ();
1790
1791             if (section
1792                 && (section->the_bfd_section->flags & SEC_THREAD_LOCAL) != 0)
1793               {
1794                 load_addr = MSYMBOL_VALUE_RAW_ADDRESS (msym.minsym);
1795                 printf_filtered (_("a thread-local variable at offset %s "
1796                                    "in the thread-local storage for `%s'"),
1797                                  paddress (gdbarch, load_addr),
1798                                  objfile_name (section->objfile));
1799               }
1800             else
1801               {
1802                 load_addr = BMSYMBOL_VALUE_ADDRESS (msym);
1803                 printf_filtered (_("static storage at address "));
1804                 fputs_styled (paddress (gdbarch, load_addr),
1805                               address_style.style (), gdb_stdout);
1806                 if (section_is_overlay (section))
1807                   {
1808                     load_addr = overlay_unmapped_address (load_addr, section);
1809                     printf_filtered (_(",\n -- loaded at "));
1810                     fputs_styled (paddress (gdbarch, load_addr),
1811                                   address_style.style (),
1812                                   gdb_stdout);
1813                     printf_filtered (_(" in overlay section %s"),
1814                                      section->the_bfd_section->name);
1815                   }
1816               }
1817           }
1818       }
1819       break;
1820
1821     case LOC_OPTIMIZED_OUT:
1822       printf_filtered (_("optimized out"));
1823       break;
1824
1825     default:
1826       printf_filtered (_("of unknown (botched) type"));
1827       break;
1828     }
1829   printf_filtered (".\n");
1830 }
1831 \f
1832
1833 static void
1834 x_command (const char *exp, int from_tty)
1835 {
1836   struct format_data fmt;
1837   struct value *val;
1838
1839   fmt.format = last_format ? last_format : 'x';
1840   fmt.print_tags = last_print_tags;
1841   fmt.size = last_size;
1842   fmt.count = 1;
1843   fmt.raw = 0;
1844
1845   /* If there is no expression and no format, use the most recent
1846      count.  */
1847   if (exp == nullptr && last_count > 0)
1848     fmt.count = last_count;
1849
1850   if (exp && *exp == '/')
1851     {
1852       const char *tmp = exp + 1;
1853
1854       fmt = decode_format (&tmp, last_format, last_size);
1855       exp = (char *) tmp;
1856     }
1857
1858   last_count = fmt.count;
1859
1860   /* If we have an expression, evaluate it and use it as the address.  */
1861
1862   if (exp != 0 && *exp != 0)
1863     {
1864       expression_up expr = parse_expression (exp);
1865       /* Cause expression not to be there any more if this command is
1866          repeated with Newline.  But don't clobber a user-defined
1867          command's definition.  */
1868       if (from_tty)
1869         set_repeat_arguments ("");
1870       val = evaluate_expression (expr.get ());
1871       if (TYPE_IS_REFERENCE (value_type (val)))
1872         val = coerce_ref (val);
1873       /* In rvalue contexts, such as this, functions are coerced into
1874          pointers to functions.  This makes "x/i main" work.  */
1875       if (value_type (val)->code () == TYPE_CODE_FUNC
1876            && VALUE_LVAL (val) == lval_memory)
1877         next_address = value_address (val);
1878       else
1879         next_address = value_as_address (val);
1880
1881       next_gdbarch = expr->gdbarch;
1882     }
1883
1884   if (!next_gdbarch)
1885     error_no_arg (_("starting display address"));
1886
1887   do_examine (fmt, next_gdbarch, next_address);
1888
1889   /* If the examine succeeds, we remember its size and format for next
1890      time.  Set last_size to 'b' for strings.  */
1891   if (fmt.format == 's')
1892     last_size = 'b';
1893   else
1894     last_size = fmt.size;
1895   last_format = fmt.format;
1896
1897   /* Remember tag-printing setting.  */
1898   last_print_tags = fmt.print_tags;
1899
1900   /* Set a couple of internal variables if appropriate.  */
1901   if (last_examine_value != nullptr)
1902     {
1903       /* Make last address examined available to the user as $_.  Use
1904          the correct pointer type.  */
1905       struct type *pointer_type
1906         = lookup_pointer_type (value_type (last_examine_value.get ()));
1907       set_internalvar (lookup_internalvar ("_"),
1908                        value_from_pointer (pointer_type,
1909                                            last_examine_address));
1910
1911       /* Make contents of last address examined available to the user
1912          as $__.  If the last value has not been fetched from memory
1913          then don't fetch it now; instead mark it by voiding the $__
1914          variable.  */
1915       if (value_lazy (last_examine_value.get ()))
1916         clear_internalvar (lookup_internalvar ("__"));
1917       else
1918         set_internalvar (lookup_internalvar ("__"), last_examine_value.get ());
1919     }
1920 }
1921
1922 /* Command completion for the 'display' and 'x' commands.  */
1923
1924 static void
1925 display_and_x_command_completer (struct cmd_list_element *ignore,
1926                                  completion_tracker &tracker,
1927                                  const char *text, const char * /*word*/)
1928 {
1929   if (skip_over_slash_fmt (tracker, &text))
1930     return;
1931
1932   const char *word = advance_to_expression_complete_word_point (tracker, text);
1933   expression_completer (ignore, tracker, text, word);
1934 }
1935
1936 \f
1937
1938 /* Add an expression to the auto-display chain.
1939    Specify the expression.  */
1940
1941 static void
1942 display_command (const char *arg, int from_tty)
1943 {
1944   struct format_data fmt;
1945   struct display *newobj;
1946   const char *exp = arg;
1947
1948   if (exp == 0)
1949     {
1950       do_displays ();
1951       return;
1952     }
1953
1954   if (*exp == '/')
1955     {
1956       exp++;
1957       fmt = decode_format (&exp, 0, 0);
1958       if (fmt.size && fmt.format == 0)
1959         fmt.format = 'x';
1960       if (fmt.format == 'i' || fmt.format == 's')
1961         fmt.size = 'b';
1962     }
1963   else
1964     {
1965       fmt.format = 0;
1966       fmt.size = 0;
1967       fmt.count = 0;
1968       fmt.raw = 0;
1969     }
1970
1971   innermost_block_tracker tracker;
1972   expression_up expr = parse_expression (exp, &tracker);
1973
1974   newobj = new display (exp, std::move (expr), fmt,
1975                         current_program_space, tracker.block ());
1976   all_displays.emplace_back (newobj);
1977
1978   if (from_tty)
1979     do_one_display (newobj);
1980
1981   dont_repeat ();
1982 }
1983
1984 /* Clear out the display_chain.  Done when new symtabs are loaded,
1985    since this invalidates the types stored in many expressions.  */
1986
1987 void
1988 clear_displays ()
1989 {
1990   all_displays.clear ();
1991 }
1992
1993 /* Delete the auto-display DISPLAY.  */
1994
1995 static void
1996 delete_display (struct display *display)
1997 {
1998   gdb_assert (display != NULL);
1999
2000   auto iter = std::find_if (all_displays.begin (),
2001                             all_displays.end (),
2002                             [=] (const std::unique_ptr<struct display> &item)
2003                             {
2004                               return item.get () == display;
2005                             });
2006   gdb_assert (iter != all_displays.end ());
2007   all_displays.erase (iter);
2008 }
2009
2010 /* Call FUNCTION on each of the displays whose numbers are given in
2011    ARGS.  DATA is passed unmodified to FUNCTION.  */
2012
2013 static void
2014 map_display_numbers (const char *args,
2015                      gdb::function_view<void (struct display *)> function)
2016 {
2017   int num;
2018
2019   if (args == NULL)
2020     error_no_arg (_("one or more display numbers"));
2021
2022   number_or_range_parser parser (args);
2023
2024   while (!parser.finished ())
2025     {
2026       const char *p = parser.cur_tok ();
2027
2028       num = parser.get_number ();
2029       if (num == 0)
2030         warning (_("bad display number at or near '%s'"), p);
2031       else
2032         {
2033           auto iter = std::find_if (all_displays.begin (),
2034                                     all_displays.end (),
2035                                     [=] (const std::unique_ptr<display> &item)
2036                                     {
2037                                       return item->number == num;
2038                                     });
2039           if (iter == all_displays.end ())
2040             printf_unfiltered (_("No display number %d.\n"), num);
2041           else
2042             function (iter->get ());
2043         }
2044     }
2045 }
2046
2047 /* "undisplay" command.  */
2048
2049 static void
2050 undisplay_command (const char *args, int from_tty)
2051 {
2052   if (args == NULL)
2053     {
2054       if (query (_("Delete all auto-display expressions? ")))
2055         clear_displays ();
2056       dont_repeat ();
2057       return;
2058     }
2059
2060   map_display_numbers (args, delete_display);
2061   dont_repeat ();
2062 }
2063
2064 /* Display a single auto-display.  
2065    Do nothing if the display cannot be printed in the current context,
2066    or if the display is disabled.  */
2067
2068 static void
2069 do_one_display (struct display *d)
2070 {
2071   int within_current_scope;
2072
2073   if (!d->enabled_p)
2074     return;
2075
2076   /* The expression carries the architecture that was used at parse time.
2077      This is a problem if the expression depends on architecture features
2078      (e.g. register numbers), and the current architecture is now different.
2079      For example, a display statement like "display/i $pc" is expected to
2080      display the PC register of the current architecture, not the arch at
2081      the time the display command was given.  Therefore, we re-parse the
2082      expression if the current architecture has changed.  */
2083   if (d->exp != NULL && d->exp->gdbarch != get_current_arch ())
2084     {
2085       d->exp.reset ();
2086       d->block = NULL;
2087     }
2088
2089   if (d->exp == NULL)
2090     {
2091
2092       try
2093         {
2094           innermost_block_tracker tracker;
2095           d->exp = parse_expression (d->exp_string.c_str (), &tracker);
2096           d->block = tracker.block ();
2097         }
2098       catch (const gdb_exception &ex)
2099         {
2100           /* Can't re-parse the expression.  Disable this display item.  */
2101           d->enabled_p = false;
2102           warning (_("Unable to display \"%s\": %s"),
2103                    d->exp_string.c_str (), ex.what ());
2104           return;
2105         }
2106     }
2107
2108   if (d->block)
2109     {
2110       if (d->pspace == current_program_space)
2111         within_current_scope = contained_in (get_selected_block (0), d->block,
2112                                              true);
2113       else
2114         within_current_scope = 0;
2115     }
2116   else
2117     within_current_scope = 1;
2118   if (!within_current_scope)
2119     return;
2120
2121   scoped_restore save_display_number
2122     = make_scoped_restore (&current_display_number, d->number);
2123
2124   annotate_display_begin ();
2125   printf_filtered ("%d", d->number);
2126   annotate_display_number_end ();
2127   printf_filtered (": ");
2128   if (d->format.size)
2129     {
2130
2131       annotate_display_format ();
2132
2133       printf_filtered ("x/");
2134       if (d->format.count != 1)
2135         printf_filtered ("%d", d->format.count);
2136       printf_filtered ("%c", d->format.format);
2137       if (d->format.format != 'i' && d->format.format != 's')
2138         printf_filtered ("%c", d->format.size);
2139       printf_filtered (" ");
2140
2141       annotate_display_expression ();
2142
2143       puts_filtered (d->exp_string.c_str ());
2144       annotate_display_expression_end ();
2145
2146       if (d->format.count != 1 || d->format.format == 'i')
2147         printf_filtered ("\n");
2148       else
2149         printf_filtered ("  ");
2150
2151       annotate_display_value ();
2152
2153       try
2154         {
2155           struct value *val;
2156           CORE_ADDR addr;
2157
2158           val = evaluate_expression (d->exp.get ());
2159           addr = value_as_address (val);
2160           if (d->format.format == 'i')
2161             addr = gdbarch_addr_bits_remove (d->exp->gdbarch, addr);
2162           do_examine (d->format, d->exp->gdbarch, addr);
2163         }
2164       catch (const gdb_exception_error &ex)
2165         {
2166           fprintf_filtered (gdb_stdout, _("%p[<error: %s>%p]\n"),
2167                             metadata_style.style ().ptr (), ex.what (),
2168                             nullptr);
2169         }
2170     }
2171   else
2172     {
2173       struct value_print_options opts;
2174
2175       annotate_display_format ();
2176
2177       if (d->format.format)
2178         printf_filtered ("/%c ", d->format.format);
2179
2180       annotate_display_expression ();
2181
2182       puts_filtered (d->exp_string.c_str ());
2183       annotate_display_expression_end ();
2184
2185       printf_filtered (" = ");
2186
2187       annotate_display_expression ();
2188
2189       get_formatted_print_options (&opts, d->format.format);
2190       opts.raw = d->format.raw;
2191
2192       try
2193         {
2194           struct value *val;
2195
2196           val = evaluate_expression (d->exp.get ());
2197           print_formatted (val, d->format.size, &opts, gdb_stdout);
2198         }
2199       catch (const gdb_exception_error &ex)
2200         {
2201           fprintf_styled (gdb_stdout, metadata_style.style (),
2202                           _("<error: %s>"), ex.what ());
2203         }
2204
2205       printf_filtered ("\n");
2206     }
2207
2208   annotate_display_end ();
2209
2210   gdb_flush (gdb_stdout);
2211 }
2212
2213 /* Display all of the values on the auto-display chain which can be
2214    evaluated in the current scope.  */
2215
2216 void
2217 do_displays (void)
2218 {
2219   for (auto &d : all_displays)
2220     do_one_display (d.get ());
2221 }
2222
2223 /* Delete the auto-display which we were in the process of displaying.
2224    This is done when there is an error or a signal.  */
2225
2226 void
2227 disable_display (int num)
2228 {
2229   for (auto &d : all_displays)
2230     if (d->number == num)
2231       {
2232         d->enabled_p = false;
2233         return;
2234       }
2235   printf_unfiltered (_("No display number %d.\n"), num);
2236 }
2237
2238 void
2239 disable_current_display (void)
2240 {
2241   if (current_display_number >= 0)
2242     {
2243       disable_display (current_display_number);
2244       fprintf_unfiltered (gdb_stderr,
2245                           _("Disabling display %d to "
2246                             "avoid infinite recursion.\n"),
2247                           current_display_number);
2248     }
2249   current_display_number = -1;
2250 }
2251
2252 static void
2253 info_display_command (const char *ignore, int from_tty)
2254 {
2255   if (all_displays.empty ())
2256     printf_unfiltered (_("There are no auto-display expressions now.\n"));
2257   else
2258     printf_filtered (_("Auto-display expressions now in effect:\n\
2259 Num Enb Expression\n"));
2260
2261   for (auto &d : all_displays)
2262     {
2263       printf_filtered ("%d:   %c  ", d->number, "ny"[(int) d->enabled_p]);
2264       if (d->format.size)
2265         printf_filtered ("/%d%c%c ", d->format.count, d->format.size,
2266                          d->format.format);
2267       else if (d->format.format)
2268         printf_filtered ("/%c ", d->format.format);
2269       puts_filtered (d->exp_string.c_str ());
2270       if (d->block && !contained_in (get_selected_block (0), d->block, true))
2271         printf_filtered (_(" (cannot be evaluated in the current context)"));
2272       printf_filtered ("\n");
2273     }
2274 }
2275
2276 /* Implementation of both the "disable display" and "enable display"
2277    commands.  ENABLE decides what to do.  */
2278
2279 static void
2280 enable_disable_display_command (const char *args, int from_tty, bool enable)
2281 {
2282   if (args == NULL)
2283     {
2284       for (auto &d : all_displays)
2285         d->enabled_p = enable;
2286       return;
2287     }
2288
2289   map_display_numbers (args,
2290                        [=] (struct display *d)
2291                        {
2292                          d->enabled_p = enable;
2293                        });
2294 }
2295
2296 /* The "enable display" command.  */
2297
2298 static void
2299 enable_display_command (const char *args, int from_tty)
2300 {
2301   enable_disable_display_command (args, from_tty, true);
2302 }
2303
2304 /* The "disable display" command.  */
2305
2306 static void
2307 disable_display_command (const char *args, int from_tty)
2308 {
2309   enable_disable_display_command (args, from_tty, false);
2310 }
2311
2312 /* display_chain items point to blocks and expressions.  Some expressions in
2313    turn may point to symbols.
2314    Both symbols and blocks are obstack_alloc'd on objfile_stack, and are
2315    obstack_free'd when a shared library is unloaded.
2316    Clear pointers that are about to become dangling.
2317    Both .exp and .block fields will be restored next time we need to display
2318    an item by re-parsing .exp_string field in the new execution context.  */
2319
2320 static void
2321 clear_dangling_display_expressions (struct objfile *objfile)
2322 {
2323   struct program_space *pspace;
2324
2325   /* With no symbol file we cannot have a block or expression from it.  */
2326   if (objfile == NULL)
2327     return;
2328   pspace = objfile->pspace;
2329   if (objfile->separate_debug_objfile_backlink)
2330     {
2331       objfile = objfile->separate_debug_objfile_backlink;
2332       gdb_assert (objfile->pspace == pspace);
2333     }
2334
2335   for (auto &d : all_displays)
2336     {
2337       if (d->pspace != pspace)
2338         continue;
2339
2340       struct objfile *bl_objf = nullptr;
2341       if (d->block != nullptr)
2342         {
2343           bl_objf = block_objfile (d->block);
2344           if (bl_objf->separate_debug_objfile_backlink != nullptr)
2345             bl_objf = bl_objf->separate_debug_objfile_backlink;
2346         }
2347
2348       if (bl_objf == objfile
2349           || (d->exp != NULL && exp_uses_objfile (d->exp.get (), objfile)))
2350         {
2351           d->exp.reset ();
2352           d->block = NULL;
2353         }
2354     }
2355 }
2356 \f
2357
2358 /* Print the value in stack frame FRAME of a variable specified by a
2359    struct symbol.  NAME is the name to print; if NULL then VAR's print
2360    name will be used.  STREAM is the ui_file on which to print the
2361    value.  INDENT specifies the number of indent levels to print
2362    before printing the variable name.
2363
2364    This function invalidates FRAME.  */
2365
2366 void
2367 print_variable_and_value (const char *name, struct symbol *var,
2368                           struct frame_info *frame,
2369                           struct ui_file *stream, int indent)
2370 {
2371
2372   if (!name)
2373     name = var->print_name ();
2374
2375   fprintf_filtered (stream, "%*s%ps = ", 2 * indent, "",
2376                     styled_string (variable_name_style.style (), name));
2377
2378   try
2379     {
2380       struct value *val;
2381       struct value_print_options opts;
2382
2383       /* READ_VAR_VALUE needs a block in order to deal with non-local
2384          references (i.e. to handle nested functions).  In this context, we
2385          print variables that are local to this frame, so we can avoid passing
2386          a block to it.  */
2387       val = read_var_value (var, NULL, frame);
2388       get_user_print_options (&opts);
2389       opts.deref_ref = 1;
2390       common_val_print_checked (val, stream, indent, &opts, current_language);
2391
2392       /* common_val_print invalidates FRAME when a pretty printer calls inferior
2393          function.  */
2394       frame = NULL;
2395     }
2396   catch (const gdb_exception_error &except)
2397     {
2398       fprintf_styled (stream, metadata_style.style (),
2399                       "<error reading variable %s (%s)>", name,
2400                       except.what ());
2401     }
2402
2403   fprintf_filtered (stream, "\n");
2404 }
2405
2406 /* Subroutine of ui_printf to simplify it.
2407    Print VALUE to STREAM using FORMAT.
2408    VALUE is a C-style string either on the target or
2409    in a GDB internal variable.  */
2410
2411 static void
2412 printf_c_string (struct ui_file *stream, const char *format,
2413                  struct value *value)
2414 {
2415   const gdb_byte *str;
2416
2417   if (value_type (value)->code () != TYPE_CODE_PTR
2418       && VALUE_LVAL (value) == lval_internalvar
2419       && c_is_string_type_p (value_type (value)))
2420     {
2421       size_t len = TYPE_LENGTH (value_type (value));
2422
2423       /* Copy the internal var value to TEM_STR and append a terminating null
2424          character.  This protects against corrupted C-style strings that lack
2425          the terminating null char.  It also allows Ada-style strings (not
2426          null terminated) to be printed without problems.  */
2427       gdb_byte *tem_str = (gdb_byte *) alloca (len + 1);
2428
2429       memcpy (tem_str, value_contents (value), len);
2430       tem_str [len] = 0;
2431       str = tem_str;
2432     }
2433   else
2434     {
2435       CORE_ADDR tem = value_as_address (value);;
2436
2437       if (tem == 0)
2438         {
2439           DIAGNOSTIC_PUSH
2440           DIAGNOSTIC_IGNORE_FORMAT_NONLITERAL
2441           fprintf_filtered (stream, format, "(null)");
2442           DIAGNOSTIC_POP
2443           return;
2444         }
2445
2446       /* This is a %s argument.  Find the length of the string.  */
2447       size_t len;
2448
2449       for (len = 0;; len++)
2450         {
2451           gdb_byte c;
2452
2453           QUIT;
2454           read_memory (tem + len, &c, 1);
2455           if (c == 0)
2456             break;
2457         }
2458
2459       /* Copy the string contents into a string inside GDB.  */
2460       gdb_byte *tem_str = (gdb_byte *) alloca (len + 1);
2461
2462       if (len != 0)
2463         read_memory (tem, tem_str, len);
2464       tem_str[len] = 0;
2465       str = tem_str;
2466     }
2467
2468   DIAGNOSTIC_PUSH
2469   DIAGNOSTIC_IGNORE_FORMAT_NONLITERAL
2470   fprintf_filtered (stream, format, (char *) str);
2471   DIAGNOSTIC_POP
2472 }
2473
2474 /* Subroutine of ui_printf to simplify it.
2475    Print VALUE to STREAM using FORMAT.
2476    VALUE is a wide C-style string on the target or
2477    in a GDB internal variable.  */
2478
2479 static void
2480 printf_wide_c_string (struct ui_file *stream, const char *format,
2481                       struct value *value)
2482 {
2483   const gdb_byte *str;
2484   size_t len;
2485   struct gdbarch *gdbarch = value_type (value)->arch ();
2486   struct type *wctype = lookup_typename (current_language,
2487                                          "wchar_t", NULL, 0);
2488   int wcwidth = TYPE_LENGTH (wctype);
2489
2490   if (VALUE_LVAL (value) == lval_internalvar
2491       && c_is_string_type_p (value_type (value)))
2492     {
2493       str = value_contents (value);
2494       len = TYPE_LENGTH (value_type (value));
2495     }
2496   else
2497     {
2498       CORE_ADDR tem = value_as_address (value);
2499
2500       if (tem == 0)
2501         {
2502           DIAGNOSTIC_PUSH
2503           DIAGNOSTIC_IGNORE_FORMAT_NONLITERAL
2504           fprintf_filtered (stream, format, "(null)");
2505           DIAGNOSTIC_POP
2506           return;
2507         }
2508
2509       /* This is a %s argument.  Find the length of the string.  */
2510       enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
2511       gdb_byte *buf = (gdb_byte *) alloca (wcwidth);
2512
2513       for (len = 0;; len += wcwidth)
2514         {
2515           QUIT;
2516           read_memory (tem + len, buf, wcwidth);
2517           if (extract_unsigned_integer (buf, wcwidth, byte_order) == 0)
2518             break;
2519         }
2520
2521       /* Copy the string contents into a string inside GDB.  */
2522       gdb_byte *tem_str = (gdb_byte *) alloca (len + wcwidth);
2523
2524       if (len != 0)
2525         read_memory (tem, tem_str, len);
2526       memset (&tem_str[len], 0, wcwidth);
2527       str = tem_str;
2528     }
2529
2530   auto_obstack output;
2531
2532   convert_between_encodings (target_wide_charset (gdbarch),
2533                              host_charset (),
2534                              str, len, wcwidth,
2535                              &output, translit_char);
2536   obstack_grow_str0 (&output, "");
2537
2538   DIAGNOSTIC_PUSH
2539   DIAGNOSTIC_IGNORE_FORMAT_NONLITERAL
2540   fprintf_filtered (stream, format, obstack_base (&output));
2541   DIAGNOSTIC_POP
2542 }
2543
2544 /* Subroutine of ui_printf to simplify it.
2545    Print VALUE, a floating point value, to STREAM using FORMAT.  */
2546
2547 static void
2548 printf_floating (struct ui_file *stream, const char *format,
2549                  struct value *value, enum argclass argclass)
2550 {
2551   /* Parameter data.  */
2552   struct type *param_type = value_type (value);
2553   struct gdbarch *gdbarch = param_type->arch ();
2554
2555   /* Determine target type corresponding to the format string.  */
2556   struct type *fmt_type;
2557   switch (argclass)
2558     {
2559       case double_arg:
2560         fmt_type = builtin_type (gdbarch)->builtin_double;
2561         break;
2562       case long_double_arg:
2563         fmt_type = builtin_type (gdbarch)->builtin_long_double;
2564         break;
2565       case dec32float_arg:
2566         fmt_type = builtin_type (gdbarch)->builtin_decfloat;
2567         break;
2568       case dec64float_arg:
2569         fmt_type = builtin_type (gdbarch)->builtin_decdouble;
2570         break;
2571       case dec128float_arg:
2572         fmt_type = builtin_type (gdbarch)->builtin_declong;
2573         break;
2574       default:
2575         gdb_assert_not_reached ("unexpected argument class");
2576     }
2577
2578   /* To match the traditional GDB behavior, the conversion is
2579      done differently depending on the type of the parameter:
2580
2581      - if the parameter has floating-point type, it's value
2582        is converted to the target type;
2583
2584      - otherwise, if the parameter has a type that is of the
2585        same size as a built-in floating-point type, the value
2586        bytes are interpreted as if they were of that type, and
2587        then converted to the target type (this is not done for
2588        decimal floating-point argument classes);
2589
2590      - otherwise, if the source value has an integer value,
2591        it's value is converted to the target type;
2592
2593      - otherwise, an error is raised.
2594
2595      In either case, the result of the conversion is a byte buffer
2596      formatted in the target format for the target type.  */
2597
2598   if (fmt_type->code () == TYPE_CODE_FLT)
2599     {
2600       param_type = float_type_from_length (param_type);
2601       if (param_type != value_type (value))
2602         value = value_from_contents (param_type, value_contents (value));
2603     }
2604
2605   value = value_cast (fmt_type, value);
2606
2607   /* Convert the value to a string and print it.  */
2608   std::string str
2609     = target_float_to_string (value_contents (value), fmt_type, format);
2610   fputs_filtered (str.c_str (), stream);
2611 }
2612
2613 /* Subroutine of ui_printf to simplify it.
2614    Print VALUE, a target pointer, to STREAM using FORMAT.  */
2615
2616 static void
2617 printf_pointer (struct ui_file *stream, const char *format,
2618                 struct value *value)
2619 {
2620   /* We avoid the host's %p because pointers are too
2621      likely to be the wrong size.  The only interesting
2622      modifier for %p is a width; extract that, and then
2623      handle %p as glibc would: %#x or a literal "(nil)".  */
2624
2625   const char *p;
2626   char *fmt, *fmt_p;
2627 #ifdef PRINTF_HAS_LONG_LONG
2628   long long val = value_as_long (value);
2629 #else
2630   long val = value_as_long (value);
2631 #endif
2632
2633   fmt = (char *) alloca (strlen (format) + 5);
2634
2635   /* Copy up to the leading %.  */
2636   p = format;
2637   fmt_p = fmt;
2638   while (*p)
2639     {
2640       int is_percent = (*p == '%');
2641
2642       *fmt_p++ = *p++;
2643       if (is_percent)
2644         {
2645           if (*p == '%')
2646             *fmt_p++ = *p++;
2647           else
2648             break;
2649         }
2650     }
2651
2652   if (val != 0)
2653     *fmt_p++ = '#';
2654
2655   /* Copy any width or flags.  Only the "-" flag is valid for pointers
2656      -- see the format_pieces constructor.  */
2657   while (*p == '-' || (*p >= '0' && *p < '9'))
2658     *fmt_p++ = *p++;
2659
2660   gdb_assert (*p == 'p' && *(p + 1) == '\0');
2661   if (val != 0)
2662     {
2663 #ifdef PRINTF_HAS_LONG_LONG
2664       *fmt_p++ = 'l';
2665 #endif
2666       *fmt_p++ = 'l';
2667       *fmt_p++ = 'x';
2668       *fmt_p++ = '\0';
2669       DIAGNOSTIC_PUSH
2670       DIAGNOSTIC_IGNORE_FORMAT_NONLITERAL
2671       fprintf_filtered (stream, fmt, val);
2672       DIAGNOSTIC_POP
2673     }
2674   else
2675     {
2676       *fmt_p++ = 's';
2677       *fmt_p++ = '\0';
2678       DIAGNOSTIC_PUSH
2679       DIAGNOSTIC_IGNORE_FORMAT_NONLITERAL
2680       fprintf_filtered (stream, fmt, "(nil)");
2681       DIAGNOSTIC_POP
2682     }
2683 }
2684
2685 /* printf "printf format string" ARG to STREAM.  */
2686
2687 static void
2688 ui_printf (const char *arg, struct ui_file *stream)
2689 {
2690   const char *s = arg;
2691   std::vector<struct value *> val_args;
2692
2693   if (s == 0)
2694     error_no_arg (_("format-control string and values to print"));
2695
2696   s = skip_spaces (s);
2697
2698   /* A format string should follow, enveloped in double quotes.  */
2699   if (*s++ != '"')
2700     error (_("Bad format string, missing '\"'."));
2701
2702   format_pieces fpieces (&s);
2703
2704   if (*s++ != '"')
2705     error (_("Bad format string, non-terminated '\"'."));
2706   
2707   s = skip_spaces (s);
2708
2709   if (*s != ',' && *s != 0)
2710     error (_("Invalid argument syntax"));
2711
2712   if (*s == ',')
2713     s++;
2714   s = skip_spaces (s);
2715
2716   {
2717     int nargs_wanted;
2718     int i;
2719     const char *current_substring;
2720
2721     nargs_wanted = 0;
2722     for (auto &&piece : fpieces)
2723       if (piece.argclass != literal_piece)
2724         ++nargs_wanted;
2725
2726     /* Now, parse all arguments and evaluate them.
2727        Store the VALUEs in VAL_ARGS.  */
2728
2729     while (*s != '\0')
2730       {
2731         const char *s1;
2732
2733         s1 = s;
2734         val_args.push_back (parse_to_comma_and_eval (&s1));
2735
2736         s = s1;
2737         if (*s == ',')
2738           s++;
2739       }
2740
2741     if (val_args.size () != nargs_wanted)
2742       error (_("Wrong number of arguments for specified format-string"));
2743
2744     /* Now actually print them.  */
2745     i = 0;
2746     for (auto &&piece : fpieces)
2747       {
2748         current_substring = piece.string;
2749         switch (piece.argclass)
2750           {
2751           case string_arg:
2752             printf_c_string (stream, current_substring, val_args[i]);
2753             break;
2754           case wide_string_arg:
2755             printf_wide_c_string (stream, current_substring, val_args[i]);
2756             break;
2757           case wide_char_arg:
2758             {
2759               struct gdbarch *gdbarch = value_type (val_args[i])->arch ();
2760               struct type *wctype = lookup_typename (current_language,
2761                                                      "wchar_t", NULL, 0);
2762               struct type *valtype;
2763               const gdb_byte *bytes;
2764
2765               valtype = value_type (val_args[i]);
2766               if (TYPE_LENGTH (valtype) != TYPE_LENGTH (wctype)
2767                   || valtype->code () != TYPE_CODE_INT)
2768                 error (_("expected wchar_t argument for %%lc"));
2769
2770               bytes = value_contents (val_args[i]);
2771
2772               auto_obstack output;
2773
2774               convert_between_encodings (target_wide_charset (gdbarch),
2775                                          host_charset (),
2776                                          bytes, TYPE_LENGTH (valtype),
2777                                          TYPE_LENGTH (valtype),
2778                                          &output, translit_char);
2779               obstack_grow_str0 (&output, "");
2780
2781               DIAGNOSTIC_PUSH
2782               DIAGNOSTIC_IGNORE_FORMAT_NONLITERAL
2783               fprintf_filtered (stream, current_substring,
2784                                 obstack_base (&output));
2785               DIAGNOSTIC_POP
2786             }
2787             break;
2788           case long_long_arg:
2789 #ifdef PRINTF_HAS_LONG_LONG
2790             {
2791               long long val = value_as_long (val_args[i]);
2792
2793               DIAGNOSTIC_PUSH
2794               DIAGNOSTIC_IGNORE_FORMAT_NONLITERAL
2795               fprintf_filtered (stream, current_substring, val);
2796               DIAGNOSTIC_POP
2797               break;
2798             }
2799 #else
2800             error (_("long long not supported in printf"));
2801 #endif
2802           case int_arg:
2803             {
2804               int val = value_as_long (val_args[i]);
2805
2806               DIAGNOSTIC_PUSH
2807               DIAGNOSTIC_IGNORE_FORMAT_NONLITERAL
2808               fprintf_filtered (stream, current_substring, val);
2809               DIAGNOSTIC_POP
2810               break;
2811             }
2812           case long_arg:
2813             {
2814               long val = value_as_long (val_args[i]);
2815
2816               DIAGNOSTIC_PUSH
2817               DIAGNOSTIC_IGNORE_FORMAT_NONLITERAL
2818               fprintf_filtered (stream, current_substring, val);
2819               DIAGNOSTIC_POP
2820               break;
2821             }
2822           case size_t_arg:
2823             {
2824               size_t val = value_as_long (val_args[i]);
2825
2826               DIAGNOSTIC_PUSH
2827               DIAGNOSTIC_IGNORE_FORMAT_NONLITERAL
2828               fprintf_filtered (stream, current_substring, val);
2829               DIAGNOSTIC_POP
2830               break;
2831             }
2832           /* Handles floating-point values.  */
2833           case double_arg:
2834           case long_double_arg:
2835           case dec32float_arg:
2836           case dec64float_arg:
2837           case dec128float_arg:
2838             printf_floating (stream, current_substring, val_args[i],
2839                              piece.argclass);
2840             break;
2841           case ptr_arg:
2842             printf_pointer (stream, current_substring, val_args[i]);
2843             break;
2844           case literal_piece:
2845             /* Print a portion of the format string that has no
2846                directives.  Note that this will not include any
2847                ordinary %-specs, but it might include "%%".  That is
2848                why we use printf_filtered and not puts_filtered here.
2849                Also, we pass a dummy argument because some platforms
2850                have modified GCC to include -Wformat-security by
2851                default, which will warn here if there is no
2852                argument.  */
2853             DIAGNOSTIC_PUSH
2854             DIAGNOSTIC_IGNORE_FORMAT_NONLITERAL
2855             fprintf_filtered (stream, current_substring, 0);
2856             DIAGNOSTIC_POP
2857             break;
2858           default:
2859             internal_error (__FILE__, __LINE__,
2860                             _("failed internal consistency check"));
2861           }
2862         /* Maybe advance to the next argument.  */
2863         if (piece.argclass != literal_piece)
2864           ++i;
2865       }
2866   }
2867 }
2868
2869 /* Implement the "printf" command.  */
2870
2871 static void
2872 printf_command (const char *arg, int from_tty)
2873 {
2874   ui_printf (arg, gdb_stdout);
2875   reset_terminal_style (gdb_stdout);
2876   wrap_here ("");
2877   gdb_stdout->flush ();
2878 }
2879
2880 /* Implement the "eval" command.  */
2881
2882 static void
2883 eval_command (const char *arg, int from_tty)
2884 {
2885   string_file stb;
2886
2887   ui_printf (arg, &stb);
2888
2889   std::string expanded = insert_user_defined_cmd_args (stb.c_str ());
2890
2891   execute_command (expanded.c_str (), from_tty);
2892 }
2893
2894 /* Convenience function for error checking in memory-tag commands.  */
2895
2896 static void
2897 show_addr_not_tagged (CORE_ADDR address)
2898 {
2899   error (_("Address %s not in a region mapped with a memory tagging flag."),
2900          paddress (target_gdbarch (), address));
2901 }
2902
2903 /* Convenience function for error checking in memory-tag commands.  */
2904
2905 static void
2906 show_memory_tagging_unsupported (void)
2907 {
2908   error (_("Memory tagging not supported or disabled by the current"
2909            " architecture."));
2910 }
2911
2912 /* Implement the "memory-tag" prefix command.  */
2913
2914 static void
2915 memory_tag_command (const char *arg, int from_tty)
2916 {
2917   help_list (memory_tag_list, "memory-tag ", all_commands, gdb_stdout);
2918 }
2919
2920 /* Helper for print-logical-tag and print-allocation-tag.  */
2921
2922 static void
2923 memory_tag_print_tag_command (const char *args, enum memtag_type tag_type)
2924 {
2925   if (args == nullptr)
2926     error_no_arg (_("address or pointer"));
2927
2928   /* Parse args into a value.  If the value is a pointer or an address,
2929      then fetch the logical or allocation tag.  */
2930   value_print_options print_opts;
2931
2932   struct value *val = process_print_command_args (args, &print_opts, true);
2933
2934   /* If the address is not in a region memory mapped with a memory tagging
2935      flag, it is no use trying to access/manipulate its allocation tag.
2936
2937      It is OK to manipulate the logical tag though.  */
2938   if (tag_type == memtag_type::allocation
2939       && !gdbarch_tagged_address_p (target_gdbarch (), val))
2940     show_addr_not_tagged (value_as_address (val));
2941
2942   struct value *tag_value
2943     = gdbarch_get_memtag (target_gdbarch (), val, tag_type);
2944   std::string tag = gdbarch_memtag_to_string (target_gdbarch (), tag_value);
2945
2946   if (tag.empty ())
2947     printf_filtered (_("%s tag unavailable.\n"),
2948                      tag_type
2949                        == memtag_type::logical? "Logical" : "Allocation");
2950
2951   struct value *v_tag = process_print_command_args (tag.c_str (),
2952                                                     &print_opts,
2953                                                     true);
2954   print_opts.output_format = 'x';
2955   print_value (v_tag, print_opts);
2956 }
2957
2958 /* Implement the "memory-tag print-logical-tag" command.  */
2959
2960 static void
2961 memory_tag_print_logical_tag_command (const char *args, int from_tty)
2962 {
2963   if (!target_supports_memory_tagging ())
2964     show_memory_tagging_unsupported ();
2965
2966   memory_tag_print_tag_command (args, memtag_type::logical);
2967 }
2968
2969 /* Implement the "memory-tag print-allocation-tag" command.  */
2970
2971 static void
2972 memory_tag_print_allocation_tag_command (const char *args, int from_tty)
2973 {
2974   if (!target_supports_memory_tagging ())
2975     show_memory_tagging_unsupported ();
2976
2977   memory_tag_print_tag_command (args, memtag_type::allocation);
2978 }
2979
2980 /* Parse ARGS and extract ADDR and TAG.
2981    ARGS should have format <expression> <tag bytes>.  */
2982
2983 static void
2984 parse_with_logical_tag_input (const char *args, struct value **val,
2985                               gdb::byte_vector &tags,
2986                               value_print_options *print_opts)
2987 {
2988   /* Fetch the address.  */
2989   std::string address_string = extract_string_maybe_quoted (&args);
2990
2991   /* Parse the address into a value.  */
2992   *val = process_print_command_args (address_string.c_str (), print_opts,
2993                                      true);
2994
2995   /* Fetch the tag bytes.  */
2996   std::string tag_string = extract_string_maybe_quoted (&args);
2997
2998   /* Validate the input.  */
2999   if (address_string.empty () || tag_string.empty ())
3000     error (_("Missing arguments."));
3001
3002   if (tag_string.length () != 2)
3003     error (_("Error parsing tags argument. The tag should be 2 digits."));
3004
3005   tags = hex2bin (tag_string.c_str ());
3006 }
3007
3008 /* Implement the "memory-tag with-logical-tag" command.  */
3009
3010 static void
3011 memory_tag_with_logical_tag_command (const char *args, int from_tty)
3012 {
3013   if (!target_supports_memory_tagging ())
3014     show_memory_tagging_unsupported ();
3015
3016   if (args == nullptr)
3017     error_no_arg (_("<address> <tag>"));
3018
3019   gdb::byte_vector tags;
3020   struct value *val;
3021   value_print_options print_opts;
3022
3023   /* Parse the input.  */
3024   parse_with_logical_tag_input (args, &val, tags, &print_opts);
3025
3026   /* Setting the logical tag is just a local operation that does not touch
3027      any memory from the target.  Given an input value, we modify the value
3028      to include the appropriate tag.
3029
3030      For this reason we need to cast the argument value to a
3031      (void *) pointer.  This is so we have the right type for the gdbarch
3032      hook to manipulate the value and insert the tag.
3033
3034      Otherwise, this would fail if, for example, GDB parsed the argument value
3035      into an int-sized value and the pointer value has a type of greater
3036      length.  */
3037
3038   /* Cast to (void *).  */
3039   val = value_cast (builtin_type (target_gdbarch ())->builtin_data_ptr,
3040                     val);
3041
3042   /* Length doesn't matter for a logical tag.  Pass 0.  */
3043   if (!gdbarch_set_memtags (target_gdbarch (), val, 0, tags,
3044                             memtag_type::logical))
3045     printf_filtered (_("Could not update the logical tag data.\n"));
3046   else
3047     {
3048       /* Always print it in hex format.  */
3049       print_opts.output_format = 'x';
3050       print_value (val, print_opts);
3051     }
3052 }
3053
3054 /* Parse ARGS and extract ADDR, LENGTH and TAGS.  */
3055
3056 static void
3057 parse_set_allocation_tag_input (const char *args, struct value **val,
3058                                 size_t *length, gdb::byte_vector &tags)
3059 {
3060   /* Fetch the address.  */
3061   std::string address_string = extract_string_maybe_quoted (&args);
3062
3063   /* Parse the address into a value.  */
3064   value_print_options print_opts;
3065   *val = process_print_command_args (address_string.c_str (), &print_opts,
3066                                      true);
3067
3068   /* Fetch the length.  */
3069   std::string length_string = extract_string_maybe_quoted (&args);
3070
3071   /* Fetch the tag bytes.  */
3072   std::string tags_string = extract_string_maybe_quoted (&args);
3073
3074   /* Validate the input.  */
3075   if (address_string.empty () || length_string.empty () || tags_string.empty ())
3076     error (_("Missing arguments."));
3077
3078   errno = 0;
3079   const char *trailer = nullptr;
3080   LONGEST parsed_length = strtoulst (length_string.c_str (), &trailer, 10);
3081
3082   if (errno != 0 || (trailer != nullptr && trailer[0] != '\0'))
3083     error (_("Error parsing length argument."));
3084
3085   if (parsed_length <= 0)
3086     error (_("Invalid zero or negative length."));
3087
3088   *length = parsed_length;
3089
3090   if (tags_string.length () % 2)
3091     error (_("Error parsing tags argument. Tags should be 2 digits per byte."));
3092
3093   tags = hex2bin (tags_string.c_str ());
3094
3095   /* If the address is not in a region memory mapped with a memory tagging
3096      flag, it is no use trying to access/manipulate its allocation tag.  */
3097   if (!gdbarch_tagged_address_p (target_gdbarch (), *val))
3098     show_addr_not_tagged (value_as_address (*val));
3099 }
3100
3101 /* Implement the "memory-tag set-allocation-tag" command.
3102    ARGS should be in the format <address> <length> <tags>.  */
3103
3104 static void
3105 memory_tag_set_allocation_tag_command (const char *args, int from_tty)
3106 {
3107   if (!target_supports_memory_tagging ())
3108     show_memory_tagging_unsupported ();
3109
3110   if (args == nullptr)
3111     error_no_arg (_("<starting address> <length> <tag bytes>"));
3112
3113   gdb::byte_vector tags;
3114   size_t length = 0;
3115   struct value *val;
3116
3117   /* Parse the input.  */
3118   parse_set_allocation_tag_input (args, &val, &length, tags);
3119
3120   if (!gdbarch_set_memtags (target_gdbarch (), val, length, tags,
3121                             memtag_type::allocation))
3122     printf_filtered (_("Could not update the allocation tag(s).\n"));
3123   else
3124     printf_filtered (_("Allocation tag(s) updated successfully.\n"));
3125 }
3126
3127 /* Implement the "memory-tag check" command.  */
3128
3129 static void
3130 memory_tag_check_command (const char *args, int from_tty)
3131 {
3132   if (!target_supports_memory_tagging ())
3133     show_memory_tagging_unsupported ();
3134
3135   if (args == nullptr)
3136     error (_("Argument required (address or pointer)"));
3137
3138   /* Parse the expression into a value.  If the value is an address or
3139      pointer, then check its logical tag against the allocation tag.  */
3140   value_print_options print_opts;
3141
3142   struct value *val = process_print_command_args (args, &print_opts, true);
3143
3144   /* If the address is not in a region memory mapped with a memory tagging
3145      flag, it is no use trying to access/manipulate its allocation tag.  */
3146   if (!gdbarch_tagged_address_p (target_gdbarch (), val))
3147     show_addr_not_tagged (value_as_address (val));
3148
3149   CORE_ADDR addr = value_as_address (val);
3150
3151   /* Check if the tag is valid.  */
3152   if (!gdbarch_memtag_matches_p (target_gdbarch (), val))
3153     {
3154       struct value *tag
3155         = gdbarch_get_memtag (target_gdbarch (), val, memtag_type::logical);
3156       std::string ltag
3157         = gdbarch_memtag_to_string (target_gdbarch (), tag);
3158
3159       tag = gdbarch_get_memtag (target_gdbarch (), val,
3160                                 memtag_type::allocation);
3161       std::string atag
3162         = gdbarch_memtag_to_string (target_gdbarch (), tag);
3163
3164       printf_filtered (_("Logical tag (%s) does not match"
3165                          " the allocation tag (%s) for address %s.\n"),
3166                        ltag.c_str (), atag.c_str (),
3167                        paddress (target_gdbarch (), addr));
3168     }
3169   else
3170     {
3171       struct value *tag
3172         = gdbarch_get_memtag (target_gdbarch (), val, memtag_type::logical);
3173       std::string ltag
3174         = gdbarch_memtag_to_string (target_gdbarch (), tag);
3175
3176       printf_filtered (_("Memory tags for address %s match (%s).\n"),
3177                        paddress (target_gdbarch (), addr), ltag.c_str ());
3178     }
3179 }
3180
3181 void _initialize_printcmd ();
3182 void
3183 _initialize_printcmd ()
3184 {
3185   struct cmd_list_element *c;
3186
3187   current_display_number = -1;
3188
3189   gdb::observers::free_objfile.attach (clear_dangling_display_expressions,
3190                                        "printcmd");
3191
3192   add_info ("address", info_address_command,
3193             _("Describe where symbol SYM is stored.\n\
3194 Usage: info address SYM"));
3195
3196   add_info ("symbol", info_symbol_command, _("\
3197 Describe what symbol is at location ADDR.\n\
3198 Usage: info symbol ADDR\n\
3199 Only for symbols with fixed locations (global or static scope)."));
3200
3201   c = add_com ("x", class_vars, x_command, _("\
3202 Examine memory: x/FMT ADDRESS.\n\
3203 ADDRESS is an expression for the memory address to examine.\n\
3204 FMT is a repeat count followed by a format letter and a size letter.\n\
3205 Format letters are o(octal), x(hex), d(decimal), u(unsigned decimal),\n\
3206   t(binary), f(float), a(address), i(instruction), c(char), s(string)\n\
3207   and z(hex, zero padded on the left).\n\
3208 Size letters are b(byte), h(halfword), w(word), g(giant, 8 bytes).\n\
3209 The specified number of objects of the specified size are printed\n\
3210 according to the format.  If a negative number is specified, memory is\n\
3211 examined backward from the address.\n\n\
3212 Defaults for format and size letters are those previously used.\n\
3213 Default count is 1.  Default address is following last thing printed\n\
3214 with this command or \"print\"."));
3215   set_cmd_completer_handle_brkchars (c, display_and_x_command_completer);
3216
3217   add_info ("display", info_display_command, _("\
3218 Expressions to display when program stops, with code numbers.\n\
3219 Usage: info display"));
3220
3221   add_cmd ("undisplay", class_vars, undisplay_command, _("\
3222 Cancel some expressions to be displayed when program stops.\n\
3223 Usage: undisplay [NUM]...\n\
3224 Arguments are the code numbers of the expressions to stop displaying.\n\
3225 No argument means cancel all automatic-display expressions.\n\
3226 \"delete display\" has the same effect as this command.\n\
3227 Do \"info display\" to see current list of code numbers."),
3228            &cmdlist);
3229
3230   c = add_com ("display", class_vars, display_command, _("\
3231 Print value of expression EXP each time the program stops.\n\
3232 Usage: display[/FMT] EXP\n\
3233 /FMT may be used before EXP as in the \"print\" command.\n\
3234 /FMT \"i\" or \"s\" or including a size-letter is allowed,\n\
3235 as in the \"x\" command, and then EXP is used to get the address to examine\n\
3236 and examining is done as in the \"x\" command.\n\n\
3237 With no argument, display all currently requested auto-display expressions.\n\
3238 Use \"undisplay\" to cancel display requests previously made."));
3239   set_cmd_completer_handle_brkchars (c, display_and_x_command_completer);
3240
3241   add_cmd ("display", class_vars, enable_display_command, _("\
3242 Enable some expressions to be displayed when program stops.\n\
3243 Usage: enable display [NUM]...\n\
3244 Arguments are the code numbers of the expressions to resume displaying.\n\
3245 No argument means enable all automatic-display expressions.\n\
3246 Do \"info display\" to see current list of code numbers."), &enablelist);
3247
3248   add_cmd ("display", class_vars, disable_display_command, _("\
3249 Disable some expressions to be displayed when program stops.\n\
3250 Usage: disable display [NUM]...\n\
3251 Arguments are the code numbers of the expressions to stop displaying.\n\
3252 No argument means disable all automatic-display expressions.\n\
3253 Do \"info display\" to see current list of code numbers."), &disablelist);
3254
3255   add_cmd ("display", class_vars, undisplay_command, _("\
3256 Cancel some expressions to be displayed when program stops.\n\
3257 Usage: delete display [NUM]...\n\
3258 Arguments are the code numbers of the expressions to stop displaying.\n\
3259 No argument means cancel all automatic-display expressions.\n\
3260 Do \"info display\" to see current list of code numbers."), &deletelist);
3261
3262   add_com ("printf", class_vars, printf_command, _("\
3263 Formatted printing, like the C \"printf\" function.\n\
3264 Usage: printf \"format string\", ARG1, ARG2, ARG3, ..., ARGN\n\
3265 This supports most C printf format specifications, like %s, %d, etc."));
3266
3267   add_com ("output", class_vars, output_command, _("\
3268 Like \"print\" but don't put in value history and don't print newline.\n\
3269 Usage: output EXP\n\
3270 This is useful in user-defined commands."));
3271
3272   add_prefix_cmd ("set", class_vars, set_command, _("\
3273 Evaluate expression EXP and assign result to variable VAR.\n\
3274 Usage: set VAR = EXP\n\
3275 This uses assignment syntax appropriate for the current language\n\
3276 (VAR = EXP or VAR := EXP for example).\n\
3277 VAR may be a debugger \"convenience\" variable (names starting\n\
3278 with $), a register (a few standard names starting with $), or an actual\n\
3279 variable in the program being debugged.  EXP is any valid expression.\n\
3280 Use \"set variable\" for variables with names identical to set subcommands.\n\
3281 \n\
3282 With a subcommand, this command modifies parts of the gdb environment.\n\
3283 You can see these environment settings with the \"show\" command."),
3284                   &setlist, "set ", 1, &cmdlist);
3285   if (dbx_commands)
3286     add_com ("assign", class_vars, set_command, _("\
3287 Evaluate expression EXP and assign result to variable VAR.\n\
3288 Usage: assign VAR = EXP\n\
3289 This uses assignment syntax appropriate for the current language\n\
3290 (VAR = EXP or VAR := EXP for example).\n\
3291 VAR may be a debugger \"convenience\" variable (names starting\n\
3292 with $), a register (a few standard names starting with $), or an actual\n\
3293 variable in the program being debugged.  EXP is any valid expression.\n\
3294 Use \"set variable\" for variables with names identical to set subcommands.\n\
3295 \nWith a subcommand, this command modifies parts of the gdb environment.\n\
3296 You can see these environment settings with the \"show\" command."));
3297
3298   /* "call" is the same as "set", but handy for dbx users to call fns.  */
3299   c = add_com ("call", class_vars, call_command, _("\
3300 Call a function in the program.\n\
3301 Usage: call EXP\n\
3302 The argument is the function name and arguments, in the notation of the\n\
3303 current working language.  The result is printed and saved in the value\n\
3304 history, if it is not void."));
3305   set_cmd_completer_handle_brkchars (c, print_command_completer);
3306
3307   add_cmd ("variable", class_vars, set_command, _("\
3308 Evaluate expression EXP and assign result to variable VAR.\n\
3309 Usage: set variable VAR = EXP\n\
3310 This uses assignment syntax appropriate for the current language\n\
3311 (VAR = EXP or VAR := EXP for example).\n\
3312 VAR may be a debugger \"convenience\" variable (names starting\n\
3313 with $), a register (a few standard names starting with $), or an actual\n\
3314 variable in the program being debugged.  EXP is any valid expression.\n\
3315 This may usually be abbreviated to simply \"set\"."),
3316            &setlist);
3317   add_alias_cmd ("var", "variable", class_vars, 0, &setlist);
3318
3319   const auto print_opts = make_value_print_options_def_group (nullptr);
3320
3321   static const std::string print_help = gdb::option::build_help (_("\
3322 Print value of expression EXP.\n\
3323 Usage: print [[OPTION]... --] [/FMT] [EXP]\n\
3324 \n\
3325 Options:\n\
3326 %OPTIONS%\n\
3327 \n\
3328 Note: because this command accepts arbitrary expressions, if you\n\
3329 specify any command option, you must use a double dash (\"--\")\n\
3330 to mark the end of option processing.  E.g.: \"print -o -- myobj\".\n\
3331 \n\
3332 Variables accessible are those of the lexical environment of the selected\n\
3333 stack frame, plus all those whose scope is global or an entire file.\n\
3334 \n\
3335 $NUM gets previous value number NUM.  $ and $$ are the last two values.\n\
3336 $$NUM refers to NUM'th value back from the last one.\n\
3337 Names starting with $ refer to registers (with the values they would have\n\
3338 if the program were to return to the stack frame now selected, restoring\n\
3339 all registers saved by frames farther in) or else to debugger\n\
3340 \"convenience\" variables (any such name not a known register).\n\
3341 Use assignment expressions to give values to convenience variables.\n\
3342 \n\
3343 {TYPE}ADREXP refers to a datum of data type TYPE, located at address ADREXP.\n\
3344 @ is a binary operator for treating consecutive data objects\n\
3345 anywhere in memory as an array.  FOO@NUM gives an array whose first\n\
3346 element is FOO, whose second element is stored in the space following\n\
3347 where FOO is stored, etc.  FOO must be an expression whose value\n\
3348 resides in memory.\n\
3349 \n\
3350 EXP may be preceded with /FMT, where FMT is a format letter\n\
3351 but no count or size letter (see \"x\" command)."),
3352                                               print_opts);
3353
3354   c = add_com ("print", class_vars, print_command, print_help.c_str ());
3355   set_cmd_completer_handle_brkchars (c, print_command_completer);
3356   add_com_alias ("p", "print", class_vars, 1);
3357   add_com_alias ("inspect", "print", class_vars, 1);
3358
3359   add_setshow_uinteger_cmd ("max-symbolic-offset", no_class,
3360                             &max_symbolic_offset, _("\
3361 Set the largest offset that will be printed in <SYMBOL+1234> form."), _("\
3362 Show the largest offset that will be printed in <SYMBOL+1234> form."), _("\
3363 Tell GDB to only display the symbolic form of an address if the\n\
3364 offset between the closest earlier symbol and the address is less than\n\
3365 the specified maximum offset.  The default is \"unlimited\", which tells GDB\n\
3366 to always print the symbolic form of an address if any symbol precedes\n\
3367 it.  Zero is equivalent to \"unlimited\"."),
3368                             NULL,
3369                             show_max_symbolic_offset,
3370                             &setprintlist, &showprintlist);
3371   add_setshow_boolean_cmd ("symbol-filename", no_class,
3372                            &print_symbol_filename, _("\
3373 Set printing of source filename and line number with <SYMBOL>."), _("\
3374 Show printing of source filename and line number with <SYMBOL>."), NULL,
3375                            NULL,
3376                            show_print_symbol_filename,
3377                            &setprintlist, &showprintlist);
3378
3379   add_com ("eval", no_class, eval_command, _("\
3380 Construct a GDB command and then evaluate it.\n\
3381 Usage: eval \"format string\", ARG1, ARG2, ARG3, ..., ARGN\n\
3382 Convert the arguments to a string as \"printf\" would, but then\n\
3383 treat this string as a command line, and evaluate it."));
3384
3385   /* Memory tagging commands.  */
3386   add_prefix_cmd ("memory-tag", class_vars, memory_tag_command, _("\
3387 Generic command for printing and manipulating memory tag properties."),
3388                   &memory_tag_list, "memory-tag ", 0, &cmdlist);
3389   add_cmd ("print-logical-tag", class_vars,
3390            memory_tag_print_logical_tag_command,
3391            ("Print the logical tag from POINTER.\n\
3392 Usage: memory-tag print-logical-tag <POINTER>.\n\
3393 <POINTER> is an expression that evaluates to a pointer.\n\
3394 Print the logical tag contained in POINTER.  The tag interpretation is\n\
3395 architecture-specific."),
3396            &memory_tag_list);
3397   add_cmd ("print-allocation-tag", class_vars,
3398            memory_tag_print_allocation_tag_command,
3399            _("Print the allocation tag for ADDRESS.\n\
3400 Usage: memory-tag print-allocation-tag <ADDRESS>.\n\
3401 <ADDRESS> is an expression that evaluates to a memory address.\n\
3402 Print the allocation tag associated with the memory address ADDRESS.\n\
3403 The tag interpretation is architecture-specific."),
3404            &memory_tag_list);
3405   add_cmd ("with-logical-tag", class_vars, memory_tag_with_logical_tag_command,
3406            _("Print a POINTER with a specific logical TAG.\n\
3407 Usage: memory-tag with-logical-tag <POINTER> <TAG>\n\
3408 <POINTER> is an expression that evaluates to a pointer.\n\
3409 <TAG> is a sequence of hex bytes that is interpreted by the architecture\n\
3410 as a single memory tag."),
3411            &memory_tag_list);
3412   add_cmd ("set-allocation-tag", class_vars,
3413            memory_tag_set_allocation_tag_command,
3414            _("Set the allocation tag(s) for a memory range.\n\
3415 Usage: memory-tag set-allocation-tag <ADDRESS> <LENGTH> <TAG_BYTES>\n\
3416 <ADDRESS> is an expression that evaluates to a memory address\n\
3417 <LENGTH> is the number of bytes that is added to <ADDRESS> to calculate\n\
3418 the memory range.\n\
3419 <TAG_BYTES> is a sequence of hex bytes that is interpreted by the\n\
3420 architecture as one or more memory tags.\n\
3421 Sets the tags of the memory range [ADDRESS, ADDRESS + LENGTH)\n\
3422 to TAG_BYTES.\n\
3423 \n\
3424 If the number of tags is greater than or equal to the number of tag granules\n\
3425 in the [ADDRESS, ADDRESS + LENGTH) range, only the tags up to the\n\
3426 number of tag granules are updated.\n\
3427 \n\
3428 If the number of tags is less than the number of tag granules, then the\n\
3429 command is a fill operation.  The TAG_BYTES are interpreted as a pattern\n\
3430 that gets repeated until the number of tag granules in the memory range\n\
3431 [ADDRESS, ADDRESS + LENGTH) is updated."),
3432            &memory_tag_list);
3433   add_cmd ("check", class_vars, memory_tag_check_command,
3434            _("Validate a pointer's logical tag against the allocation tag.\n\
3435 Usage: memory-tag check <POINTER>\n\
3436 <POINTER> is an expression that evaluates to a pointer\n\
3437 Fetch the logical and allocation tags for POINTER and compare them\n\
3438 for equality.  If the tags do not match, print additional information about\n\
3439 the tag mismatch."),
3440            &memory_tag_list);
3441 }
This page took 0.211772 seconds and 4 git commands to generate.