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