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