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