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