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