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