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