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