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