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