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