Automatic date update in version.in
[binutils-gdb/blckswan.git] / gdb / valprint.c
blob471146769342a8874e57ca76ad318940c934b397
1 /* Print values for GDB, the GNU debugger.
3 Copyright (C) 1986-2022 Free Software Foundation, Inc.
5 This file is part of GDB.
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.
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.
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/>. */
20 #include "defs.h"
21 #include "symtab.h"
22 #include "gdbtypes.h"
23 #include "value.h"
24 #include "gdbcore.h"
25 #include "gdbcmd.h"
26 #include "target.h"
27 #include "language.h"
28 #include "annotate.h"
29 #include "valprint.h"
30 #include "target-float.h"
31 #include "extension.h"
32 #include "ada-lang.h"
33 #include "gdbsupport/gdb_obstack.h"
34 #include "charset.h"
35 #include "typeprint.h"
36 #include <ctype.h>
37 #include <algorithm>
38 #include "gdbsupport/byte-vector.h"
39 #include "cli/cli-option.h"
40 #include "gdbarch.h"
41 #include "cli/cli-style.h"
42 #include "count-one-bits.h"
43 #include "c-lang.h"
44 #include "cp-abi.h"
45 #include "inferior.h"
46 #include "gdbsupport/selftest.h"
47 #include "selftest-arch.h"
49 /* Maximum number of wchars returned from wchar_iterate. */
50 #define MAX_WCHARS 4
52 /* A convenience macro to compute the size of a wchar_t buffer containing X
53 characters. */
54 #define WCHAR_BUFLEN(X) ((X) * sizeof (gdb_wchar_t))
56 /* Character buffer size saved while iterating over wchars. */
57 #define WCHAR_BUFLEN_MAX WCHAR_BUFLEN (MAX_WCHARS)
59 /* A structure to encapsulate state information from iterated
60 character conversions. */
61 struct converted_character
63 /* The number of characters converted. */
64 int num_chars;
66 /* The result of the conversion. See charset.h for more. */
67 enum wchar_iterate_result result;
69 /* The (saved) converted character(s). */
70 gdb_wchar_t chars[WCHAR_BUFLEN_MAX];
72 /* The first converted target byte. */
73 const gdb_byte *buf;
75 /* The number of bytes converted. */
76 size_t buflen;
78 /* How many times this character(s) is repeated. */
79 int repeat_count;
82 /* Command lists for set/show print raw. */
83 struct cmd_list_element *setprintrawlist;
84 struct cmd_list_element *showprintrawlist;
86 /* Prototypes for local functions */
88 static void set_input_radix_1 (int, unsigned);
90 static void set_output_radix_1 (int, unsigned);
92 static void val_print_type_code_flags (struct type *type,
93 struct value *original_value,
94 int embedded_offset,
95 struct ui_file *stream);
97 #define PRINT_MAX_DEFAULT 200 /* Start print_max off at this value. */
98 #define PRINT_MAX_DEPTH_DEFAULT 20 /* Start print_max_depth off at this value. */
100 struct value_print_options user_print_options =
102 Val_prettyformat_default, /* prettyformat */
103 0, /* prettyformat_arrays */
104 0, /* prettyformat_structs */
105 0, /* vtblprint */
106 1, /* unionprint */
107 1, /* addressprint */
108 0, /* objectprint */
109 PRINT_MAX_DEFAULT, /* print_max */
110 10, /* repeat_count_threshold */
111 0, /* output_format */
112 0, /* format */
113 1, /* memory_tag_violations */
114 0, /* stop_print_at_null */
115 0, /* print_array_indexes */
116 0, /* deref_ref */
117 1, /* static_field_print */
118 1, /* pascal_static_field_print */
119 0, /* raw */
120 0, /* summary */
121 1, /* symbol_print */
122 PRINT_MAX_DEPTH_DEFAULT, /* max_depth */
123 1 /* finish_print */
126 /* Initialize *OPTS to be a copy of the user print options. */
127 void
128 get_user_print_options (struct value_print_options *opts)
130 *opts = user_print_options;
133 /* Initialize *OPTS to be a copy of the user print options, but with
134 pretty-formatting disabled. */
135 void
136 get_no_prettyformat_print_options (struct value_print_options *opts)
138 *opts = user_print_options;
139 opts->prettyformat = Val_no_prettyformat;
142 /* Initialize *OPTS to be a copy of the user print options, but using
143 FORMAT as the formatting option. */
144 void
145 get_formatted_print_options (struct value_print_options *opts,
146 char format)
148 *opts = user_print_options;
149 opts->format = format;
152 static void
153 show_print_max (struct ui_file *file, int from_tty,
154 struct cmd_list_element *c, const char *value)
156 gdb_printf (file,
157 _("Limit on string chars or array "
158 "elements to print is %s.\n"),
159 value);
163 /* Default input and output radixes, and output format letter. */
165 unsigned input_radix = 10;
166 static void
167 show_input_radix (struct ui_file *file, int from_tty,
168 struct cmd_list_element *c, const char *value)
170 gdb_printf (file,
171 _("Default input radix for entering numbers is %s.\n"),
172 value);
175 unsigned output_radix = 10;
176 static void
177 show_output_radix (struct ui_file *file, int from_tty,
178 struct cmd_list_element *c, const char *value)
180 gdb_printf (file,
181 _("Default output radix for printing of values is %s.\n"),
182 value);
185 /* By default we print arrays without printing the index of each element in
186 the array. This behavior can be changed by setting PRINT_ARRAY_INDEXES. */
188 static void
189 show_print_array_indexes (struct ui_file *file, int from_tty,
190 struct cmd_list_element *c, const char *value)
192 gdb_printf (file, _("Printing of array indexes is %s.\n"), value);
195 /* Print repeat counts if there are more than this many repetitions of an
196 element in an array. Referenced by the low level language dependent
197 print routines. */
199 static void
200 show_repeat_count_threshold (struct ui_file *file, int from_tty,
201 struct cmd_list_element *c, const char *value)
203 gdb_printf (file, _("Threshold for repeated print elements is %s.\n"),
204 value);
207 /* If nonzero, prints memory tag violations for pointers. */
209 static void
210 show_memory_tag_violations (struct ui_file *file, int from_tty,
211 struct cmd_list_element *c, const char *value)
213 gdb_printf (file,
214 _("Printing of memory tag violations is %s.\n"),
215 value);
218 /* If nonzero, stops printing of char arrays at first null. */
220 static void
221 show_stop_print_at_null (struct ui_file *file, int from_tty,
222 struct cmd_list_element *c, const char *value)
224 gdb_printf (file,
225 _("Printing of char arrays to stop "
226 "at first null char is %s.\n"),
227 value);
230 /* Controls pretty printing of structures. */
232 static void
233 show_prettyformat_structs (struct ui_file *file, int from_tty,
234 struct cmd_list_element *c, const char *value)
236 gdb_printf (file, _("Pretty formatting of structures is %s.\n"), value);
239 /* Controls pretty printing of arrays. */
241 static void
242 show_prettyformat_arrays (struct ui_file *file, int from_tty,
243 struct cmd_list_element *c, const char *value)
245 gdb_printf (file, _("Pretty formatting of arrays is %s.\n"), value);
248 /* If nonzero, causes unions inside structures or other unions to be
249 printed. */
251 static void
252 show_unionprint (struct ui_file *file, int from_tty,
253 struct cmd_list_element *c, const char *value)
255 gdb_printf (file,
256 _("Printing of unions interior to structures is %s.\n"),
257 value);
260 /* If nonzero, causes machine addresses to be printed in certain contexts. */
262 static void
263 show_addressprint (struct ui_file *file, int from_tty,
264 struct cmd_list_element *c, const char *value)
266 gdb_printf (file, _("Printing of addresses is %s.\n"), value);
269 static void
270 show_symbol_print (struct ui_file *file, int from_tty,
271 struct cmd_list_element *c, const char *value)
273 gdb_printf (file,
274 _("Printing of symbols when printing pointers is %s.\n"),
275 value);
280 /* A helper function for val_print. When printing in "summary" mode,
281 we want to print scalar arguments, but not aggregate arguments.
282 This function distinguishes between the two. */
285 val_print_scalar_type_p (struct type *type)
287 type = check_typedef (type);
288 while (TYPE_IS_REFERENCE (type))
290 type = TYPE_TARGET_TYPE (type);
291 type = check_typedef (type);
293 switch (type->code ())
295 case TYPE_CODE_ARRAY:
296 case TYPE_CODE_STRUCT:
297 case TYPE_CODE_UNION:
298 case TYPE_CODE_SET:
299 case TYPE_CODE_STRING:
300 return 0;
301 default:
302 return 1;
306 /* A helper function for val_print. When printing with limited depth we
307 want to print string and scalar arguments, but not aggregate arguments.
308 This function distinguishes between the two. */
310 static bool
311 val_print_scalar_or_string_type_p (struct type *type,
312 const struct language_defn *language)
314 return (val_print_scalar_type_p (type)
315 || language->is_string_type_p (type));
318 /* See valprint.h. */
321 valprint_check_validity (struct ui_file *stream,
322 struct type *type,
323 LONGEST embedded_offset,
324 const struct value *val)
326 type = check_typedef (type);
328 if (type_not_associated (type))
330 val_print_not_associated (stream);
331 return 0;
334 if (type_not_allocated (type))
336 val_print_not_allocated (stream);
337 return 0;
340 if (type->code () != TYPE_CODE_UNION
341 && type->code () != TYPE_CODE_STRUCT
342 && type->code () != TYPE_CODE_ARRAY)
344 if (value_bits_any_optimized_out (val,
345 TARGET_CHAR_BIT * embedded_offset,
346 TARGET_CHAR_BIT * TYPE_LENGTH (type)))
348 val_print_optimized_out (val, stream);
349 return 0;
352 if (value_bits_synthetic_pointer (val, TARGET_CHAR_BIT * embedded_offset,
353 TARGET_CHAR_BIT * TYPE_LENGTH (type)))
355 const int is_ref = type->code () == TYPE_CODE_REF;
356 int ref_is_addressable = 0;
358 if (is_ref)
360 const struct value *deref_val = coerce_ref_if_computed (val);
362 if (deref_val != NULL)
363 ref_is_addressable = value_lval_const (deref_val) == lval_memory;
366 if (!is_ref || !ref_is_addressable)
367 fputs_styled (_("<synthetic pointer>"), metadata_style.style (),
368 stream);
370 /* C++ references should be valid even if they're synthetic. */
371 return is_ref;
374 if (!value_bytes_available (val, embedded_offset, TYPE_LENGTH (type)))
376 val_print_unavailable (stream);
377 return 0;
381 return 1;
384 void
385 val_print_optimized_out (const struct value *val, struct ui_file *stream)
387 if (val != NULL && value_lval_const (val) == lval_register)
388 val_print_not_saved (stream);
389 else
390 fprintf_styled (stream, metadata_style.style (), _("<optimized out>"));
393 void
394 val_print_not_saved (struct ui_file *stream)
396 fprintf_styled (stream, metadata_style.style (), _("<not saved>"));
399 void
400 val_print_unavailable (struct ui_file *stream)
402 fprintf_styled (stream, metadata_style.style (), _("<unavailable>"));
405 void
406 val_print_invalid_address (struct ui_file *stream)
408 fprintf_styled (stream, metadata_style.style (), _("<invalid address>"));
411 /* Print a pointer based on the type of its target.
413 Arguments to this functions are roughly the same as those in
414 generic_val_print. A difference is that ADDRESS is the address to print,
415 with embedded_offset already added. ELTTYPE represents
416 the pointed type after check_typedef. */
418 static void
419 print_unpacked_pointer (struct type *type, struct type *elttype,
420 CORE_ADDR address, struct ui_file *stream,
421 const struct value_print_options *options)
423 struct gdbarch *gdbarch = type->arch ();
425 if (elttype->code () == TYPE_CODE_FUNC)
427 /* Try to print what function it points to. */
428 print_function_pointer_address (options, gdbarch, address, stream);
429 return;
432 if (options->symbol_print)
433 print_address_demangle (options, gdbarch, address, stream, demangle);
434 else if (options->addressprint)
435 gdb_puts (paddress (gdbarch, address), stream);
438 /* generic_val_print helper for TYPE_CODE_ARRAY. */
440 static void
441 generic_val_print_array (struct value *val,
442 struct ui_file *stream, int recurse,
443 const struct value_print_options *options,
444 const struct
445 generic_val_print_decorations *decorations)
447 struct type *type = check_typedef (value_type (val));
448 struct type *unresolved_elttype = TYPE_TARGET_TYPE (type);
449 struct type *elttype = check_typedef (unresolved_elttype);
451 if (TYPE_LENGTH (type) > 0 && TYPE_LENGTH (unresolved_elttype) > 0)
453 LONGEST low_bound, high_bound;
455 if (!get_array_bounds (type, &low_bound, &high_bound))
456 error (_("Could not determine the array high bound"));
458 gdb_puts (decorations->array_start, stream);
459 value_print_array_elements (val, stream, recurse, options, 0);
460 gdb_puts (decorations->array_end, stream);
462 else
464 /* Array of unspecified length: treat like pointer to first elt. */
465 print_unpacked_pointer (type, elttype, value_address (val),
466 stream, options);
471 /* generic_value_print helper for TYPE_CODE_PTR. */
473 static void
474 generic_value_print_ptr (struct value *val, struct ui_file *stream,
475 const struct value_print_options *options)
478 if (options->format && options->format != 's')
479 value_print_scalar_formatted (val, options, 0, stream);
480 else
482 struct type *type = check_typedef (value_type (val));
483 struct type *elttype = check_typedef (TYPE_TARGET_TYPE (type));
484 const gdb_byte *valaddr = value_contents_for_printing (val).data ();
485 CORE_ADDR addr = unpack_pointer (type, valaddr);
487 print_unpacked_pointer (type, elttype, addr, stream, options);
492 /* Print '@' followed by the address contained in ADDRESS_BUFFER. */
494 static void
495 print_ref_address (struct type *type, const gdb_byte *address_buffer,
496 int embedded_offset, struct ui_file *stream)
498 struct gdbarch *gdbarch = type->arch ();
500 if (address_buffer != NULL)
502 CORE_ADDR address
503 = extract_typed_address (address_buffer + embedded_offset, type);
505 gdb_printf (stream, "@");
506 gdb_puts (paddress (gdbarch, address), stream);
508 /* Else: we have a non-addressable value, such as a DW_AT_const_value. */
511 /* If VAL is addressable, return the value contents buffer of a value that
512 represents a pointer to VAL. Otherwise return NULL. */
514 static const gdb_byte *
515 get_value_addr_contents (struct value *deref_val)
517 gdb_assert (deref_val != NULL);
519 if (value_lval_const (deref_val) == lval_memory)
520 return value_contents_for_printing_const (value_addr (deref_val)).data ();
521 else
523 /* We have a non-addressable value, such as a DW_AT_const_value. */
524 return NULL;
528 /* generic_val_print helper for TYPE_CODE_{RVALUE_,}REF. */
530 static void
531 generic_val_print_ref (struct type *type,
532 int embedded_offset, struct ui_file *stream, int recurse,
533 struct value *original_value,
534 const struct value_print_options *options)
536 struct type *elttype = check_typedef (TYPE_TARGET_TYPE (type));
537 struct value *deref_val = NULL;
538 const int value_is_synthetic
539 = value_bits_synthetic_pointer (original_value,
540 TARGET_CHAR_BIT * embedded_offset,
541 TARGET_CHAR_BIT * TYPE_LENGTH (type));
542 const int must_coerce_ref = ((options->addressprint && value_is_synthetic)
543 || options->deref_ref);
544 const int type_is_defined = elttype->code () != TYPE_CODE_UNDEF;
545 const gdb_byte *valaddr = value_contents_for_printing (original_value).data ();
547 if (must_coerce_ref && type_is_defined)
549 deref_val = coerce_ref_if_computed (original_value);
551 if (deref_val != NULL)
553 /* More complicated computed references are not supported. */
554 gdb_assert (embedded_offset == 0);
556 else
557 deref_val = value_at (TYPE_TARGET_TYPE (type),
558 unpack_pointer (type, valaddr + embedded_offset));
560 /* Else, original_value isn't a synthetic reference or we don't have to print
561 the reference's contents.
563 Notice that for references to TYPE_CODE_STRUCT, 'set print object on' will
564 cause original_value to be a not_lval instead of an lval_computed,
565 which will make value_bits_synthetic_pointer return false.
566 This happens because if options->objectprint is true, c_value_print will
567 overwrite original_value's contents with the result of coercing
568 the reference through value_addr, and then set its type back to
569 TYPE_CODE_REF. In that case we don't have to coerce the reference again;
570 we can simply treat it as non-synthetic and move on. */
572 if (options->addressprint)
574 const gdb_byte *address = (value_is_synthetic && type_is_defined
575 ? get_value_addr_contents (deref_val)
576 : valaddr);
578 print_ref_address (type, address, embedded_offset, stream);
580 if (options->deref_ref)
581 gdb_puts (": ", stream);
584 if (options->deref_ref)
586 if (type_is_defined)
587 common_val_print (deref_val, stream, recurse, options,
588 current_language);
589 else
590 gdb_puts ("???", stream);
594 /* Helper function for generic_val_print_enum.
595 This is also used to print enums in TYPE_CODE_FLAGS values. */
597 static void
598 generic_val_print_enum_1 (struct type *type, LONGEST val,
599 struct ui_file *stream)
601 unsigned int i;
602 unsigned int len;
604 len = type->num_fields ();
605 for (i = 0; i < len; i++)
607 QUIT;
608 if (val == type->field (i).loc_enumval ())
610 break;
613 if (i < len)
615 fputs_styled (type->field (i).name (), variable_name_style.style (),
616 stream);
618 else if (type->is_flag_enum ())
620 int first = 1;
622 /* We have a "flag" enum, so we try to decompose it into pieces as
623 appropriate. The enum may have multiple enumerators representing
624 the same bit, in which case we choose to only print the first one
625 we find. */
626 for (i = 0; i < len; ++i)
628 QUIT;
630 ULONGEST enumval = type->field (i).loc_enumval ();
631 int nbits = count_one_bits_ll (enumval);
633 gdb_assert (nbits == 0 || nbits == 1);
635 if ((val & enumval) != 0)
637 if (first)
639 gdb_puts ("(", stream);
640 first = 0;
642 else
643 gdb_puts (" | ", stream);
645 val &= ~type->field (i).loc_enumval ();
646 fputs_styled (type->field (i).name (),
647 variable_name_style.style (), stream);
651 if (val != 0)
653 /* There are leftover bits, print them. */
654 if (first)
655 gdb_puts ("(", stream);
656 else
657 gdb_puts (" | ", stream);
659 gdb_puts ("unknown: 0x", stream);
660 print_longest (stream, 'x', 0, val);
661 gdb_puts (")", stream);
663 else if (first)
665 /* Nothing has been printed and the value is 0, the enum value must
666 have been 0. */
667 gdb_puts ("0", stream);
669 else
671 /* Something has been printed, close the parenthesis. */
672 gdb_puts (")", stream);
675 else
676 print_longest (stream, 'd', 0, val);
679 /* generic_val_print helper for TYPE_CODE_ENUM. */
681 static void
682 generic_val_print_enum (struct type *type,
683 int embedded_offset, struct ui_file *stream,
684 struct value *original_value,
685 const struct value_print_options *options)
687 LONGEST val;
688 struct gdbarch *gdbarch = type->arch ();
689 int unit_size = gdbarch_addressable_memory_unit_size (gdbarch);
691 gdb_assert (!options->format);
693 const gdb_byte *valaddr = value_contents_for_printing (original_value).data ();
695 val = unpack_long (type, valaddr + embedded_offset * unit_size);
697 generic_val_print_enum_1 (type, val, stream);
700 /* generic_val_print helper for TYPE_CODE_FUNC and TYPE_CODE_METHOD. */
702 static void
703 generic_val_print_func (struct type *type,
704 int embedded_offset, CORE_ADDR address,
705 struct ui_file *stream,
706 struct value *original_value,
707 const struct value_print_options *options)
709 struct gdbarch *gdbarch = type->arch ();
711 gdb_assert (!options->format);
713 /* FIXME, we should consider, at least for ANSI C language,
714 eliminating the distinction made between FUNCs and POINTERs to
715 FUNCs. */
716 gdb_printf (stream, "{");
717 type_print (type, "", stream, -1);
718 gdb_printf (stream, "} ");
719 /* Try to print what function it points to, and its address. */
720 print_address_demangle (options, gdbarch, address, stream, demangle);
723 /* generic_value_print helper for TYPE_CODE_BOOL. */
725 static void
726 generic_value_print_bool
727 (struct value *value, struct ui_file *stream,
728 const struct value_print_options *options,
729 const struct generic_val_print_decorations *decorations)
731 if (options->format || options->output_format)
733 struct value_print_options opts = *options;
734 opts.format = (options->format ? options->format
735 : options->output_format);
736 value_print_scalar_formatted (value, &opts, 0, stream);
738 else
740 const gdb_byte *valaddr = value_contents_for_printing (value).data ();
741 struct type *type = check_typedef (value_type (value));
742 LONGEST val = unpack_long (type, valaddr);
743 if (val == 0)
744 gdb_puts (decorations->false_name, stream);
745 else if (val == 1)
746 gdb_puts (decorations->true_name, stream);
747 else
748 print_longest (stream, 'd', 0, val);
752 /* generic_value_print helper for TYPE_CODE_INT. */
754 static void
755 generic_value_print_int (struct value *val, struct ui_file *stream,
756 const struct value_print_options *options)
758 struct value_print_options opts = *options;
760 opts.format = (options->format ? options->format
761 : options->output_format);
762 value_print_scalar_formatted (val, &opts, 0, stream);
765 /* generic_value_print helper for TYPE_CODE_CHAR. */
767 static void
768 generic_value_print_char (struct value *value, struct ui_file *stream,
769 const struct value_print_options *options)
771 if (options->format || options->output_format)
773 struct value_print_options opts = *options;
775 opts.format = (options->format ? options->format
776 : options->output_format);
777 value_print_scalar_formatted (value, &opts, 0, stream);
779 else
781 struct type *unresolved_type = value_type (value);
782 struct type *type = check_typedef (unresolved_type);
783 const gdb_byte *valaddr = value_contents_for_printing (value).data ();
785 LONGEST val = unpack_long (type, valaddr);
786 if (type->is_unsigned ())
787 gdb_printf (stream, "%u", (unsigned int) val);
788 else
789 gdb_printf (stream, "%d", (int) val);
790 gdb_puts (" ", stream);
791 current_language->printchar (val, unresolved_type, stream);
795 /* generic_val_print helper for TYPE_CODE_FLT and TYPE_CODE_DECFLOAT. */
797 static void
798 generic_val_print_float (struct type *type, struct ui_file *stream,
799 struct value *original_value,
800 const struct value_print_options *options)
802 gdb_assert (!options->format);
804 const gdb_byte *valaddr = value_contents_for_printing (original_value).data ();
806 print_floating (valaddr, type, stream);
809 /* generic_val_print helper for TYPE_CODE_FIXED_POINT. */
811 static void
812 generic_val_print_fixed_point (struct value *val, struct ui_file *stream,
813 const struct value_print_options *options)
815 if (options->format)
816 value_print_scalar_formatted (val, options, 0, stream);
817 else
819 struct type *type = value_type (val);
821 const gdb_byte *valaddr = value_contents_for_printing (val).data ();
822 gdb_mpf f;
824 f.read_fixed_point (gdb::make_array_view (valaddr, TYPE_LENGTH (type)),
825 type_byte_order (type), type->is_unsigned (),
826 type->fixed_point_scaling_factor ());
828 const char *fmt = TYPE_LENGTH (type) < 4 ? "%.11Fg" : "%.17Fg";
829 std::string str = gmp_string_printf (fmt, f.val);
830 gdb_printf (stream, "%s", str.c_str ());
834 /* generic_value_print helper for TYPE_CODE_COMPLEX. */
836 static void
837 generic_value_print_complex (struct value *val, struct ui_file *stream,
838 const struct value_print_options *options,
839 const struct generic_val_print_decorations
840 *decorations)
842 gdb_printf (stream, "%s", decorations->complex_prefix);
844 struct value *real_part = value_real_part (val);
845 value_print_scalar_formatted (real_part, options, 0, stream);
846 gdb_printf (stream, "%s", decorations->complex_infix);
848 struct value *imag_part = value_imaginary_part (val);
849 value_print_scalar_formatted (imag_part, options, 0, stream);
850 gdb_printf (stream, "%s", decorations->complex_suffix);
853 /* generic_value_print helper for TYPE_CODE_MEMBERPTR. */
855 static void
856 generic_value_print_memberptr
857 (struct value *val, struct ui_file *stream,
858 int recurse,
859 const struct value_print_options *options,
860 const struct generic_val_print_decorations *decorations)
862 if (!options->format)
864 /* Member pointers are essentially specific to C++, and so if we
865 encounter one, we should print it according to C++ rules. */
866 struct type *type = check_typedef (value_type (val));
867 const gdb_byte *valaddr = value_contents_for_printing (val).data ();
868 cp_print_class_member (valaddr, type, stream, "&");
870 else
871 generic_value_print (val, stream, recurse, options, decorations);
874 /* See valprint.h. */
876 void
877 generic_value_print (struct value *val, struct ui_file *stream, int recurse,
878 const struct value_print_options *options,
879 const struct generic_val_print_decorations *decorations)
881 struct type *type = value_type (val);
883 type = check_typedef (type);
885 if (is_fixed_point_type (type))
886 type = type->fixed_point_type_base_type ();
888 /* Widen a subrange to its target type, then use that type's
889 printer. */
890 while (type->code () == TYPE_CODE_RANGE)
892 type = check_typedef (TYPE_TARGET_TYPE (type));
893 val = value_cast (type, val);
896 switch (type->code ())
898 case TYPE_CODE_ARRAY:
899 generic_val_print_array (val, stream, recurse, options, decorations);
900 break;
902 case TYPE_CODE_MEMBERPTR:
903 generic_value_print_memberptr (val, stream, recurse, options,
904 decorations);
905 break;
907 case TYPE_CODE_PTR:
908 generic_value_print_ptr (val, stream, options);
909 break;
911 case TYPE_CODE_REF:
912 case TYPE_CODE_RVALUE_REF:
913 generic_val_print_ref (type, 0, stream, recurse,
914 val, options);
915 break;
917 case TYPE_CODE_ENUM:
918 if (options->format)
919 value_print_scalar_formatted (val, options, 0, stream);
920 else
921 generic_val_print_enum (type, 0, stream, val, options);
922 break;
924 case TYPE_CODE_FLAGS:
925 if (options->format)
926 value_print_scalar_formatted (val, options, 0, stream);
927 else
928 val_print_type_code_flags (type, val, 0, stream);
929 break;
931 case TYPE_CODE_FUNC:
932 case TYPE_CODE_METHOD:
933 if (options->format)
934 value_print_scalar_formatted (val, options, 0, stream);
935 else
936 generic_val_print_func (type, 0, value_address (val), stream,
937 val, options);
938 break;
940 case TYPE_CODE_BOOL:
941 generic_value_print_bool (val, stream, options, decorations);
942 break;
944 case TYPE_CODE_INT:
945 generic_value_print_int (val, stream, options);
946 break;
948 case TYPE_CODE_CHAR:
949 generic_value_print_char (val, stream, options);
950 break;
952 case TYPE_CODE_FLT:
953 case TYPE_CODE_DECFLOAT:
954 if (options->format)
955 value_print_scalar_formatted (val, options, 0, stream);
956 else
957 generic_val_print_float (type, stream, val, options);
958 break;
960 case TYPE_CODE_FIXED_POINT:
961 generic_val_print_fixed_point (val, stream, options);
962 break;
964 case TYPE_CODE_VOID:
965 gdb_puts (decorations->void_name, stream);
966 break;
968 case TYPE_CODE_ERROR:
969 gdb_printf (stream, "%s", TYPE_ERROR_NAME (type));
970 break;
972 case TYPE_CODE_UNDEF:
973 /* This happens (without TYPE_STUB set) on systems which don't use
974 dbx xrefs (NO_DBX_XREFS in gcc) if a file has a "struct foo *bar"
975 and no complete type for struct foo in that file. */
976 fprintf_styled (stream, metadata_style.style (), _("<incomplete type>"));
977 break;
979 case TYPE_CODE_COMPLEX:
980 generic_value_print_complex (val, stream, options, decorations);
981 break;
983 case TYPE_CODE_METHODPTR:
984 cplus_print_method_ptr (value_contents_for_printing (val).data (), type,
985 stream);
986 break;
988 case TYPE_CODE_UNION:
989 case TYPE_CODE_STRUCT:
990 default:
991 error (_("Unhandled type code %d in symbol table."),
992 type->code ());
996 /* Print using the given LANGUAGE the value VAL onto stream STREAM according
997 to OPTIONS.
999 This is a preferable interface to val_print, above, because it uses
1000 GDB's value mechanism. */
1002 void
1003 common_val_print (struct value *value, struct ui_file *stream, int recurse,
1004 const struct value_print_options *options,
1005 const struct language_defn *language)
1007 if (language->la_language == language_ada)
1008 /* The value might have a dynamic type, which would cause trouble
1009 below when trying to extract the value contents (since the value
1010 size is determined from the type size which is unknown). So
1011 get a fixed representation of our value. */
1012 value = ada_to_fixed_value (value);
1014 if (value_lazy (value))
1015 value_fetch_lazy (value);
1017 struct value_print_options local_opts = *options;
1018 struct type *type = value_type (value);
1019 struct type *real_type = check_typedef (type);
1021 if (local_opts.prettyformat == Val_prettyformat_default)
1022 local_opts.prettyformat = (local_opts.prettyformat_structs
1023 ? Val_prettyformat : Val_no_prettyformat);
1025 QUIT;
1027 /* Ensure that the type is complete and not just a stub. If the type is
1028 only a stub and we can't find and substitute its complete type, then
1029 print appropriate string and return. */
1031 if (real_type->is_stub ())
1033 fprintf_styled (stream, metadata_style.style (), _("<incomplete type>"));
1034 return;
1037 if (!valprint_check_validity (stream, real_type, 0, value))
1038 return;
1040 if (!options->raw)
1042 if (apply_ext_lang_val_pretty_printer (value, stream, recurse, options,
1043 language))
1044 return;
1047 /* Handle summary mode. If the value is a scalar, print it;
1048 otherwise, print an ellipsis. */
1049 if (options->summary && !val_print_scalar_type_p (type))
1051 gdb_printf (stream, "...");
1052 return;
1055 /* If this value is too deep then don't print it. */
1056 if (!val_print_scalar_or_string_type_p (type, language)
1057 && val_print_check_max_depth (stream, recurse, options, language))
1058 return;
1062 language->value_print_inner (value, stream, recurse, &local_opts);
1064 catch (const gdb_exception_error &except)
1066 fprintf_styled (stream, metadata_style.style (),
1067 _("<error reading variable: %s>"), except.what ());
1071 /* See valprint.h. */
1073 bool
1074 val_print_check_max_depth (struct ui_file *stream, int recurse,
1075 const struct value_print_options *options,
1076 const struct language_defn *language)
1078 if (options->max_depth > -1 && recurse >= options->max_depth)
1080 gdb_assert (language->struct_too_deep_ellipsis () != NULL);
1081 gdb_puts (language->struct_too_deep_ellipsis (), stream);
1082 return true;
1085 return false;
1088 /* Check whether the value VAL is printable. Return 1 if it is;
1089 return 0 and print an appropriate error message to STREAM according to
1090 OPTIONS if it is not. */
1092 static int
1093 value_check_printable (struct value *val, struct ui_file *stream,
1094 const struct value_print_options *options)
1096 if (val == 0)
1098 fprintf_styled (stream, metadata_style.style (),
1099 _("<address of value unknown>"));
1100 return 0;
1103 if (value_entirely_optimized_out (val))
1105 if (options->summary && !val_print_scalar_type_p (value_type (val)))
1106 gdb_printf (stream, "...");
1107 else
1108 val_print_optimized_out (val, stream);
1109 return 0;
1112 if (value_entirely_unavailable (val))
1114 if (options->summary && !val_print_scalar_type_p (value_type (val)))
1115 gdb_printf (stream, "...");
1116 else
1117 val_print_unavailable (stream);
1118 return 0;
1121 if (value_type (val)->code () == TYPE_CODE_INTERNAL_FUNCTION)
1123 fprintf_styled (stream, metadata_style.style (),
1124 _("<internal function %s>"),
1125 value_internal_function_name (val));
1126 return 0;
1129 if (type_not_associated (value_type (val)))
1131 val_print_not_associated (stream);
1132 return 0;
1135 if (type_not_allocated (value_type (val)))
1137 val_print_not_allocated (stream);
1138 return 0;
1141 return 1;
1144 /* See valprint.h. */
1146 void
1147 common_val_print_checked (struct value *val, struct ui_file *stream,
1148 int recurse,
1149 const struct value_print_options *options,
1150 const struct language_defn *language)
1152 if (!value_check_printable (val, stream, options))
1153 return;
1154 common_val_print (val, stream, recurse, options, language);
1157 /* Print on stream STREAM the value VAL according to OPTIONS. The value
1158 is printed using the current_language syntax. */
1160 void
1161 value_print (struct value *val, struct ui_file *stream,
1162 const struct value_print_options *options)
1164 scoped_value_mark free_values;
1166 if (!value_check_printable (val, stream, options))
1167 return;
1169 if (!options->raw)
1171 int r
1172 = apply_ext_lang_val_pretty_printer (val, stream, 0, options,
1173 current_language);
1175 if (r)
1176 return;
1179 current_language->value_print (val, stream, options);
1182 static void
1183 val_print_type_code_flags (struct type *type, struct value *original_value,
1184 int embedded_offset, struct ui_file *stream)
1186 const gdb_byte *valaddr = (value_contents_for_printing (original_value).data ()
1187 + embedded_offset);
1188 ULONGEST val = unpack_long (type, valaddr);
1189 int field, nfields = type->num_fields ();
1190 struct gdbarch *gdbarch = type->arch ();
1191 struct type *bool_type = builtin_type (gdbarch)->builtin_bool;
1193 gdb_puts ("[", stream);
1194 for (field = 0; field < nfields; field++)
1196 if (type->field (field).name ()[0] != '\0')
1198 struct type *field_type = type->field (field).type ();
1200 if (field_type == bool_type
1201 /* We require boolean types here to be one bit wide. This is a
1202 problematic place to notify the user of an internal error
1203 though. Instead just fall through and print the field as an
1204 int. */
1205 && TYPE_FIELD_BITSIZE (type, field) == 1)
1207 if (val & ((ULONGEST)1 << type->field (field).loc_bitpos ()))
1208 gdb_printf
1209 (stream, " %ps",
1210 styled_string (variable_name_style.style (),
1211 type->field (field).name ()));
1213 else
1215 unsigned field_len = TYPE_FIELD_BITSIZE (type, field);
1216 ULONGEST field_val = val >> type->field (field).loc_bitpos ();
1218 if (field_len < sizeof (ULONGEST) * TARGET_CHAR_BIT)
1219 field_val &= ((ULONGEST) 1 << field_len) - 1;
1220 gdb_printf (stream, " %ps=",
1221 styled_string (variable_name_style.style (),
1222 type->field (field).name ()));
1223 if (field_type->code () == TYPE_CODE_ENUM)
1224 generic_val_print_enum_1 (field_type, field_val, stream);
1225 else
1226 print_longest (stream, 'd', 0, field_val);
1230 gdb_puts (" ]", stream);
1233 /* See valprint.h. */
1235 void
1236 value_print_scalar_formatted (struct value *val,
1237 const struct value_print_options *options,
1238 int size,
1239 struct ui_file *stream)
1241 struct type *type = check_typedef (value_type (val));
1243 gdb_assert (val != NULL);
1245 /* If we get here with a string format, try again without it. Go
1246 all the way back to the language printers, which may call us
1247 again. */
1248 if (options->format == 's')
1250 struct value_print_options opts = *options;
1251 opts.format = 0;
1252 opts.deref_ref = 0;
1253 common_val_print (val, stream, 0, &opts, current_language);
1254 return;
1257 /* value_contents_for_printing fetches all VAL's contents. They are
1258 needed to check whether VAL is optimized-out or unavailable
1259 below. */
1260 const gdb_byte *valaddr = value_contents_for_printing (val).data ();
1262 /* A scalar object that does not have all bits available can't be
1263 printed, because all bits contribute to its representation. */
1264 if (value_bits_any_optimized_out (val, 0,
1265 TARGET_CHAR_BIT * TYPE_LENGTH (type)))
1266 val_print_optimized_out (val, stream);
1267 else if (!value_bytes_available (val, 0, TYPE_LENGTH (type)))
1268 val_print_unavailable (stream);
1269 else
1270 print_scalar_formatted (valaddr, type, options, size, stream);
1273 /* Print a number according to FORMAT which is one of d,u,x,o,b,h,w,g.
1274 The raison d'etre of this function is to consolidate printing of
1275 LONG_LONG's into this one function. The format chars b,h,w,g are
1276 from print_scalar_formatted(). Numbers are printed using C
1277 format.
1279 USE_C_FORMAT means to use C format in all cases. Without it,
1280 'o' and 'x' format do not include the standard C radix prefix
1281 (leading 0 or 0x).
1283 Hilfinger/2004-09-09: USE_C_FORMAT was originally called USE_LOCAL
1284 and was intended to request formatting according to the current
1285 language and would be used for most integers that GDB prints. The
1286 exceptional cases were things like protocols where the format of
1287 the integer is a protocol thing, not a user-visible thing). The
1288 parameter remains to preserve the information of what things might
1289 be printed with language-specific format, should we ever resurrect
1290 that capability. */
1292 void
1293 print_longest (struct ui_file *stream, int format, int use_c_format,
1294 LONGEST val_long)
1296 const char *val;
1298 switch (format)
1300 case 'd':
1301 val = int_string (val_long, 10, 1, 0, 1); break;
1302 case 'u':
1303 val = int_string (val_long, 10, 0, 0, 1); break;
1304 case 'x':
1305 val = int_string (val_long, 16, 0, 0, use_c_format); break;
1306 case 'b':
1307 val = int_string (val_long, 16, 0, 2, 1); break;
1308 case 'h':
1309 val = int_string (val_long, 16, 0, 4, 1); break;
1310 case 'w':
1311 val = int_string (val_long, 16, 0, 8, 1); break;
1312 case 'g':
1313 val = int_string (val_long, 16, 0, 16, 1); break;
1314 break;
1315 case 'o':
1316 val = int_string (val_long, 8, 0, 0, use_c_format); break;
1317 default:
1318 internal_error (__FILE__, __LINE__,
1319 _("failed internal consistency check"));
1321 gdb_puts (val, stream);
1324 /* This used to be a macro, but I don't think it is called often enough
1325 to merit such treatment. */
1326 /* Convert a LONGEST to an int. This is used in contexts (e.g. number of
1327 arguments to a function, number in a value history, register number, etc.)
1328 where the value must not be larger than can fit in an int. */
1331 longest_to_int (LONGEST arg)
1333 /* Let the compiler do the work. */
1334 int rtnval = (int) arg;
1336 /* Check for overflows or underflows. */
1337 if (sizeof (LONGEST) > sizeof (int))
1339 if (rtnval != arg)
1341 error (_("Value out of range."));
1344 return (rtnval);
1347 /* Print a floating point value of floating-point type TYPE,
1348 pointed to in GDB by VALADDR, on STREAM. */
1350 void
1351 print_floating (const gdb_byte *valaddr, struct type *type,
1352 struct ui_file *stream)
1354 std::string str = target_float_to_string (valaddr, type);
1355 gdb_puts (str.c_str (), stream);
1358 void
1359 print_binary_chars (struct ui_file *stream, const gdb_byte *valaddr,
1360 unsigned len, enum bfd_endian byte_order, bool zero_pad)
1362 const gdb_byte *p;
1363 unsigned int i;
1364 int b;
1365 bool seen_a_one = false;
1367 /* Declared "int" so it will be signed.
1368 This ensures that right shift will shift in zeros. */
1370 const int mask = 0x080;
1372 if (byte_order == BFD_ENDIAN_BIG)
1374 for (p = valaddr;
1375 p < valaddr + len;
1376 p++)
1378 /* Every byte has 8 binary characters; peel off
1379 and print from the MSB end. */
1381 for (i = 0; i < (HOST_CHAR_BIT * sizeof (*p)); i++)
1383 if (*p & (mask >> i))
1384 b = '1';
1385 else
1386 b = '0';
1388 if (zero_pad || seen_a_one || b == '1')
1389 gdb_putc (b, stream);
1390 if (b == '1')
1391 seen_a_one = true;
1395 else
1397 for (p = valaddr + len - 1;
1398 p >= valaddr;
1399 p--)
1401 for (i = 0; i < (HOST_CHAR_BIT * sizeof (*p)); i++)
1403 if (*p & (mask >> i))
1404 b = '1';
1405 else
1406 b = '0';
1408 if (zero_pad || seen_a_one || b == '1')
1409 gdb_putc (b, stream);
1410 if (b == '1')
1411 seen_a_one = true;
1416 /* When not zero-padding, ensure that something is printed when the
1417 input is 0. */
1418 if (!zero_pad && !seen_a_one)
1419 gdb_putc ('0', stream);
1422 /* A helper for print_octal_chars that emits a single octal digit,
1423 optionally suppressing it if is zero and updating SEEN_A_ONE. */
1425 static void
1426 emit_octal_digit (struct ui_file *stream, bool *seen_a_one, int digit)
1428 if (*seen_a_one || digit != 0)
1429 gdb_printf (stream, "%o", digit);
1430 if (digit != 0)
1431 *seen_a_one = true;
1434 /* VALADDR points to an integer of LEN bytes.
1435 Print it in octal on stream or format it in buf. */
1437 void
1438 print_octal_chars (struct ui_file *stream, const gdb_byte *valaddr,
1439 unsigned len, enum bfd_endian byte_order)
1441 const gdb_byte *p;
1442 unsigned char octa1, octa2, octa3, carry;
1443 int cycle;
1445 /* Octal is 3 bits, which doesn't fit. Yuk. So we have to track
1446 * the extra bits, which cycle every three bytes:
1448 * Byte side: 0 1 2 3
1449 * | | | |
1450 * bit number 123 456 78 | 9 012 345 6 | 78 901 234 | 567 890 12 |
1452 * Octal side: 0 1 carry 3 4 carry ...
1454 * Cycle number: 0 1 2
1456 * But of course we are printing from the high side, so we have to
1457 * figure out where in the cycle we are so that we end up with no
1458 * left over bits at the end.
1460 #define BITS_IN_OCTAL 3
1461 #define HIGH_ZERO 0340
1462 #define LOW_ZERO 0034
1463 #define CARRY_ZERO 0003
1464 static_assert (HIGH_ZERO + LOW_ZERO + CARRY_ZERO == 0xff,
1465 "cycle zero constants are wrong");
1466 #define HIGH_ONE 0200
1467 #define MID_ONE 0160
1468 #define LOW_ONE 0016
1469 #define CARRY_ONE 0001
1470 static_assert (HIGH_ONE + MID_ONE + LOW_ONE + CARRY_ONE == 0xff,
1471 "cycle one constants are wrong");
1472 #define HIGH_TWO 0300
1473 #define MID_TWO 0070
1474 #define LOW_TWO 0007
1475 static_assert (HIGH_TWO + MID_TWO + LOW_TWO == 0xff,
1476 "cycle two constants are wrong");
1478 /* For 32 we start in cycle 2, with two bits and one bit carry;
1479 for 64 in cycle in cycle 1, with one bit and a two bit carry. */
1481 cycle = (len * HOST_CHAR_BIT) % BITS_IN_OCTAL;
1482 carry = 0;
1484 gdb_puts ("0", stream);
1485 bool seen_a_one = false;
1486 if (byte_order == BFD_ENDIAN_BIG)
1488 for (p = valaddr;
1489 p < valaddr + len;
1490 p++)
1492 switch (cycle)
1494 case 0:
1495 /* No carry in, carry out two bits. */
1497 octa1 = (HIGH_ZERO & *p) >> 5;
1498 octa2 = (LOW_ZERO & *p) >> 2;
1499 carry = (CARRY_ZERO & *p);
1500 emit_octal_digit (stream, &seen_a_one, octa1);
1501 emit_octal_digit (stream, &seen_a_one, octa2);
1502 break;
1504 case 1:
1505 /* Carry in two bits, carry out one bit. */
1507 octa1 = (carry << 1) | ((HIGH_ONE & *p) >> 7);
1508 octa2 = (MID_ONE & *p) >> 4;
1509 octa3 = (LOW_ONE & *p) >> 1;
1510 carry = (CARRY_ONE & *p);
1511 emit_octal_digit (stream, &seen_a_one, octa1);
1512 emit_octal_digit (stream, &seen_a_one, octa2);
1513 emit_octal_digit (stream, &seen_a_one, octa3);
1514 break;
1516 case 2:
1517 /* Carry in one bit, no carry out. */
1519 octa1 = (carry << 2) | ((HIGH_TWO & *p) >> 6);
1520 octa2 = (MID_TWO & *p) >> 3;
1521 octa3 = (LOW_TWO & *p);
1522 carry = 0;
1523 emit_octal_digit (stream, &seen_a_one, octa1);
1524 emit_octal_digit (stream, &seen_a_one, octa2);
1525 emit_octal_digit (stream, &seen_a_one, octa3);
1526 break;
1528 default:
1529 error (_("Internal error in octal conversion;"));
1532 cycle++;
1533 cycle = cycle % BITS_IN_OCTAL;
1536 else
1538 for (p = valaddr + len - 1;
1539 p >= valaddr;
1540 p--)
1542 switch (cycle)
1544 case 0:
1545 /* Carry out, no carry in */
1547 octa1 = (HIGH_ZERO & *p) >> 5;
1548 octa2 = (LOW_ZERO & *p) >> 2;
1549 carry = (CARRY_ZERO & *p);
1550 emit_octal_digit (stream, &seen_a_one, octa1);
1551 emit_octal_digit (stream, &seen_a_one, octa2);
1552 break;
1554 case 1:
1555 /* Carry in, carry out */
1557 octa1 = (carry << 1) | ((HIGH_ONE & *p) >> 7);
1558 octa2 = (MID_ONE & *p) >> 4;
1559 octa3 = (LOW_ONE & *p) >> 1;
1560 carry = (CARRY_ONE & *p);
1561 emit_octal_digit (stream, &seen_a_one, octa1);
1562 emit_octal_digit (stream, &seen_a_one, octa2);
1563 emit_octal_digit (stream, &seen_a_one, octa3);
1564 break;
1566 case 2:
1567 /* Carry in, no carry out */
1569 octa1 = (carry << 2) | ((HIGH_TWO & *p) >> 6);
1570 octa2 = (MID_TWO & *p) >> 3;
1571 octa3 = (LOW_TWO & *p);
1572 carry = 0;
1573 emit_octal_digit (stream, &seen_a_one, octa1);
1574 emit_octal_digit (stream, &seen_a_one, octa2);
1575 emit_octal_digit (stream, &seen_a_one, octa3);
1576 break;
1578 default:
1579 error (_("Internal error in octal conversion;"));
1582 cycle++;
1583 cycle = cycle % BITS_IN_OCTAL;
1589 /* Possibly negate the integer represented by BYTES. It contains LEN
1590 bytes in the specified byte order. If the integer is negative,
1591 copy it into OUT_VEC, negate it, and return true. Otherwise, do
1592 nothing and return false. */
1594 static bool
1595 maybe_negate_by_bytes (const gdb_byte *bytes, unsigned len,
1596 enum bfd_endian byte_order,
1597 gdb::byte_vector *out_vec)
1599 gdb_byte sign_byte;
1600 gdb_assert (len > 0);
1601 if (byte_order == BFD_ENDIAN_BIG)
1602 sign_byte = bytes[0];
1603 else
1604 sign_byte = bytes[len - 1];
1605 if ((sign_byte & 0x80) == 0)
1606 return false;
1608 out_vec->resize (len);
1610 /* Compute -x == 1 + ~x. */
1611 if (byte_order == BFD_ENDIAN_LITTLE)
1613 unsigned carry = 1;
1614 for (unsigned i = 0; i < len; ++i)
1616 unsigned tem = (0xff & ~bytes[i]) + carry;
1617 (*out_vec)[i] = tem & 0xff;
1618 carry = tem / 256;
1621 else
1623 unsigned carry = 1;
1624 for (unsigned i = len; i > 0; --i)
1626 unsigned tem = (0xff & ~bytes[i - 1]) + carry;
1627 (*out_vec)[i - 1] = tem & 0xff;
1628 carry = tem / 256;
1632 return true;
1635 /* VALADDR points to an integer of LEN bytes.
1636 Print it in decimal on stream or format it in buf. */
1638 void
1639 print_decimal_chars (struct ui_file *stream, const gdb_byte *valaddr,
1640 unsigned len, bool is_signed,
1641 enum bfd_endian byte_order)
1643 #define TEN 10
1644 #define CARRY_OUT( x ) ((x) / TEN) /* extend char to int */
1645 #define CARRY_LEFT( x ) ((x) % TEN)
1646 #define SHIFT( x ) ((x) << 4)
1647 #define LOW_NIBBLE( x ) ( (x) & 0x00F)
1648 #define HIGH_NIBBLE( x ) (((x) & 0x0F0) >> 4)
1650 const gdb_byte *p;
1651 int carry;
1652 int decimal_len;
1653 int i, j, decimal_digits;
1654 int dummy;
1655 int flip;
1657 gdb::byte_vector negated_bytes;
1658 if (is_signed
1659 && maybe_negate_by_bytes (valaddr, len, byte_order, &negated_bytes))
1661 gdb_puts ("-", stream);
1662 valaddr = negated_bytes.data ();
1665 /* Base-ten number is less than twice as many digits
1666 as the base 16 number, which is 2 digits per byte. */
1668 decimal_len = len * 2 * 2;
1669 std::vector<unsigned char> digits (decimal_len, 0);
1671 /* Ok, we have an unknown number of bytes of data to be printed in
1672 * decimal.
1674 * Given a hex number (in nibbles) as XYZ, we start by taking X and
1675 * decimalizing it as "x1 x2" in two decimal nibbles. Then we multiply
1676 * the nibbles by 16, add Y and re-decimalize. Repeat with Z.
1678 * The trick is that "digits" holds a base-10 number, but sometimes
1679 * the individual digits are > 10.
1681 * Outer loop is per nibble (hex digit) of input, from MSD end to
1682 * LSD end.
1684 decimal_digits = 0; /* Number of decimal digits so far */
1685 p = (byte_order == BFD_ENDIAN_BIG) ? valaddr : valaddr + len - 1;
1686 flip = 0;
1687 while ((byte_order == BFD_ENDIAN_BIG) ? (p < valaddr + len) : (p >= valaddr))
1690 * Multiply current base-ten number by 16 in place.
1691 * Each digit was between 0 and 9, now is between
1692 * 0 and 144.
1694 for (j = 0; j < decimal_digits; j++)
1696 digits[j] = SHIFT (digits[j]);
1699 /* Take the next nibble off the input and add it to what
1700 * we've got in the LSB position. Bottom 'digit' is now
1701 * between 0 and 159.
1703 * "flip" is used to run this loop twice for each byte.
1705 if (flip == 0)
1707 /* Take top nibble. */
1709 digits[0] += HIGH_NIBBLE (*p);
1710 flip = 1;
1712 else
1714 /* Take low nibble and bump our pointer "p". */
1716 digits[0] += LOW_NIBBLE (*p);
1717 if (byte_order == BFD_ENDIAN_BIG)
1718 p++;
1719 else
1720 p--;
1721 flip = 0;
1724 /* Re-decimalize. We have to do this often enough
1725 * that we don't overflow, but once per nibble is
1726 * overkill. Easier this way, though. Note that the
1727 * carry is often larger than 10 (e.g. max initial
1728 * carry out of lowest nibble is 15, could bubble all
1729 * the way up greater than 10). So we have to do
1730 * the carrying beyond the last current digit.
1732 carry = 0;
1733 for (j = 0; j < decimal_len - 1; j++)
1735 digits[j] += carry;
1737 /* "/" won't handle an unsigned char with
1738 * a value that if signed would be negative.
1739 * So extend to longword int via "dummy".
1741 dummy = digits[j];
1742 carry = CARRY_OUT (dummy);
1743 digits[j] = CARRY_LEFT (dummy);
1745 if (j >= decimal_digits && carry == 0)
1748 * All higher digits are 0 and we
1749 * no longer have a carry.
1751 * Note: "j" is 0-based, "decimal_digits" is
1752 * 1-based.
1754 decimal_digits = j + 1;
1755 break;
1760 /* Ok, now "digits" is the decimal representation, with
1761 the "decimal_digits" actual digits. Print! */
1763 for (i = decimal_digits - 1; i > 0 && digits[i] == 0; --i)
1766 for (; i >= 0; i--)
1768 gdb_printf (stream, "%1d", digits[i]);
1772 /* VALADDR points to an integer of LEN bytes. Print it in hex on stream. */
1774 void
1775 print_hex_chars (struct ui_file *stream, const gdb_byte *valaddr,
1776 unsigned len, enum bfd_endian byte_order,
1777 bool zero_pad)
1779 const gdb_byte *p;
1781 gdb_puts ("0x", stream);
1782 if (byte_order == BFD_ENDIAN_BIG)
1784 p = valaddr;
1786 if (!zero_pad)
1788 /* Strip leading 0 bytes, but be sure to leave at least a
1789 single byte at the end. */
1790 for (; p < valaddr + len - 1 && !*p; ++p)
1794 const gdb_byte *first = p;
1795 for (;
1796 p < valaddr + len;
1797 p++)
1799 /* When not zero-padding, use a different format for the
1800 very first byte printed. */
1801 if (!zero_pad && p == first)
1802 gdb_printf (stream, "%x", *p);
1803 else
1804 gdb_printf (stream, "%02x", *p);
1807 else
1809 p = valaddr + len - 1;
1811 if (!zero_pad)
1813 /* Strip leading 0 bytes, but be sure to leave at least a
1814 single byte at the end. */
1815 for (; p >= valaddr + 1 && !*p; --p)
1819 const gdb_byte *first = p;
1820 for (;
1821 p >= valaddr;
1822 p--)
1824 /* When not zero-padding, use a different format for the
1825 very first byte printed. */
1826 if (!zero_pad && p == first)
1827 gdb_printf (stream, "%x", *p);
1828 else
1829 gdb_printf (stream, "%02x", *p);
1834 /* Print function pointer with inferior address ADDRESS onto stdio
1835 stream STREAM. */
1837 void
1838 print_function_pointer_address (const struct value_print_options *options,
1839 struct gdbarch *gdbarch,
1840 CORE_ADDR address,
1841 struct ui_file *stream)
1843 CORE_ADDR func_addr = gdbarch_convert_from_func_ptr_addr
1844 (gdbarch, address, current_inferior ()->top_target ());
1846 /* If the function pointer is represented by a description, print
1847 the address of the description. */
1848 if (options->addressprint && func_addr != address)
1850 gdb_puts ("@", stream);
1851 gdb_puts (paddress (gdbarch, address), stream);
1852 gdb_puts (": ", stream);
1854 print_address_demangle (options, gdbarch, func_addr, stream, demangle);
1858 /* Print on STREAM using the given OPTIONS the index for the element
1859 at INDEX of an array whose index type is INDEX_TYPE. */
1861 void
1862 maybe_print_array_index (struct type *index_type, LONGEST index,
1863 struct ui_file *stream,
1864 const struct value_print_options *options)
1866 if (!options->print_array_indexes)
1867 return;
1869 current_language->print_array_index (index_type, index, stream, options);
1872 /* See valprint.h. */
1874 void
1875 value_print_array_elements (struct value *val, struct ui_file *stream,
1876 int recurse,
1877 const struct value_print_options *options,
1878 unsigned int i)
1880 unsigned int things_printed = 0;
1881 unsigned len;
1882 struct type *elttype, *index_type;
1883 unsigned eltlen;
1884 /* Position of the array element we are examining to see
1885 whether it is repeated. */
1886 unsigned int rep1;
1887 /* Number of repetitions we have detected so far. */
1888 unsigned int reps;
1889 LONGEST low_bound, high_bound;
1891 struct type *type = check_typedef (value_type (val));
1893 elttype = TYPE_TARGET_TYPE (type);
1894 eltlen = type_length_units (check_typedef (elttype));
1895 index_type = type->index_type ();
1896 if (index_type->code () == TYPE_CODE_RANGE)
1897 index_type = TYPE_TARGET_TYPE (index_type);
1899 if (get_array_bounds (type, &low_bound, &high_bound))
1901 /* The array length should normally be HIGH_BOUND - LOW_BOUND +
1902 1. But we have to be a little extra careful, because some
1903 languages such as Ada allow LOW_BOUND to be greater than
1904 HIGH_BOUND for empty arrays. In that situation, the array
1905 length is just zero, not negative! */
1906 if (low_bound > high_bound)
1907 len = 0;
1908 else
1909 len = high_bound - low_bound + 1;
1911 else
1913 warning (_("unable to get bounds of array, assuming null array"));
1914 low_bound = 0;
1915 len = 0;
1918 annotate_array_section_begin (i, elttype);
1920 for (; i < len && things_printed < options->print_max; i++)
1922 scoped_value_mark free_values;
1924 if (i != 0)
1926 if (options->prettyformat_arrays)
1928 gdb_printf (stream, ",\n");
1929 print_spaces (2 + 2 * recurse, stream);
1931 else
1932 gdb_printf (stream, ", ");
1934 else if (options->prettyformat_arrays)
1936 gdb_printf (stream, "\n");
1937 print_spaces (2 + 2 * recurse, stream);
1939 stream->wrap_here (2 + 2 * recurse);
1940 maybe_print_array_index (index_type, i + low_bound,
1941 stream, options);
1943 rep1 = i + 1;
1944 reps = 1;
1945 /* Only check for reps if repeat_count_threshold is not set to
1946 UINT_MAX (unlimited). */
1947 if (options->repeat_count_threshold < UINT_MAX)
1949 while (rep1 < len
1950 && value_contents_eq (val, i * eltlen,
1951 val, rep1 * eltlen,
1952 eltlen))
1954 ++reps;
1955 ++rep1;
1959 struct value *element = value_from_component (val, elttype, eltlen * i);
1960 common_val_print (element, stream, recurse + 1, options,
1961 current_language);
1963 if (reps > options->repeat_count_threshold)
1965 annotate_elt_rep (reps);
1966 gdb_printf (stream, " %p[<repeats %u times>%p]",
1967 metadata_style.style ().ptr (), reps, nullptr);
1968 annotate_elt_rep_end ();
1970 i = rep1 - 1;
1971 things_printed += options->repeat_count_threshold;
1973 else
1975 annotate_elt ();
1976 things_printed++;
1979 annotate_array_section_end ();
1980 if (i < len)
1981 gdb_printf (stream, "...");
1982 if (options->prettyformat_arrays)
1984 gdb_printf (stream, "\n");
1985 print_spaces (2 * recurse, stream);
1989 /* Return true if print_wchar can display W without resorting to a
1990 numeric escape, false otherwise. */
1992 static int
1993 wchar_printable (gdb_wchar_t w)
1995 return (gdb_iswprint (w)
1996 || w == LCST ('\a') || w == LCST ('\b')
1997 || w == LCST ('\f') || w == LCST ('\n')
1998 || w == LCST ('\r') || w == LCST ('\t')
1999 || w == LCST ('\v'));
2002 /* A helper function that converts the contents of STRING to wide
2003 characters and then appends them to OUTPUT. */
2005 static void
2006 append_string_as_wide (const char *string,
2007 struct obstack *output)
2009 for (; *string; ++string)
2011 gdb_wchar_t w = gdb_btowc (*string);
2012 obstack_grow (output, &w, sizeof (gdb_wchar_t));
2016 /* Print a wide character W to OUTPUT. ORIG is a pointer to the
2017 original (target) bytes representing the character, ORIG_LEN is the
2018 number of valid bytes. WIDTH is the number of bytes in a base
2019 characters of the type. OUTPUT is an obstack to which wide
2020 characters are emitted. QUOTER is a (narrow) character indicating
2021 the style of quotes surrounding the character to be printed.
2022 NEED_ESCAPE is an in/out flag which is used to track numeric
2023 escapes across calls. */
2025 static void
2026 print_wchar (gdb_wint_t w, const gdb_byte *orig,
2027 int orig_len, int width,
2028 enum bfd_endian byte_order,
2029 struct obstack *output,
2030 int quoter, int *need_escapep)
2032 int need_escape = *need_escapep;
2034 *need_escapep = 0;
2036 /* iswprint implementation on Windows returns 1 for tab character.
2037 In order to avoid different printout on this host, we explicitly
2038 use wchar_printable function. */
2039 switch (w)
2041 case LCST ('\a'):
2042 obstack_grow_wstr (output, LCST ("\\a"));
2043 break;
2044 case LCST ('\b'):
2045 obstack_grow_wstr (output, LCST ("\\b"));
2046 break;
2047 case LCST ('\f'):
2048 obstack_grow_wstr (output, LCST ("\\f"));
2049 break;
2050 case LCST ('\n'):
2051 obstack_grow_wstr (output, LCST ("\\n"));
2052 break;
2053 case LCST ('\r'):
2054 obstack_grow_wstr (output, LCST ("\\r"));
2055 break;
2056 case LCST ('\t'):
2057 obstack_grow_wstr (output, LCST ("\\t"));
2058 break;
2059 case LCST ('\v'):
2060 obstack_grow_wstr (output, LCST ("\\v"));
2061 break;
2062 default:
2064 if (wchar_printable (w) && (!need_escape || (!gdb_iswdigit (w)
2065 && w != LCST ('8')
2066 && w != LCST ('9'))))
2068 gdb_wchar_t wchar = w;
2070 if (w == gdb_btowc (quoter) || w == LCST ('\\'))
2071 obstack_grow_wstr (output, LCST ("\\"));
2072 obstack_grow (output, &wchar, sizeof (gdb_wchar_t));
2074 else
2076 int i;
2078 for (i = 0; i + width <= orig_len; i += width)
2080 char octal[30];
2081 ULONGEST value;
2083 value = extract_unsigned_integer (&orig[i], width,
2084 byte_order);
2085 /* If the value fits in 3 octal digits, print it that
2086 way. Otherwise, print it as a hex escape. */
2087 if (value <= 0777)
2088 xsnprintf (octal, sizeof (octal), "\\%.3o",
2089 (int) (value & 0777));
2090 else
2091 xsnprintf (octal, sizeof (octal), "\\x%lx", (long) value);
2092 append_string_as_wide (octal, output);
2094 /* If we somehow have extra bytes, print them now. */
2095 while (i < orig_len)
2097 char octal[5];
2099 xsnprintf (octal, sizeof (octal), "\\%.3o", orig[i] & 0xff);
2100 append_string_as_wide (octal, output);
2101 ++i;
2104 *need_escapep = 1;
2106 break;
2111 /* Print the character C on STREAM as part of the contents of a
2112 literal string whose delimiter is QUOTER. ENCODING names the
2113 encoding of C. */
2115 void
2116 generic_emit_char (int c, struct type *type, struct ui_file *stream,
2117 int quoter, const char *encoding)
2119 enum bfd_endian byte_order
2120 = type_byte_order (type);
2121 gdb_byte *c_buf;
2122 int need_escape = 0;
2124 c_buf = (gdb_byte *) alloca (TYPE_LENGTH (type));
2125 pack_long (c_buf, type, c);
2127 wchar_iterator iter (c_buf, TYPE_LENGTH (type), encoding, TYPE_LENGTH (type));
2129 /* This holds the printable form of the wchar_t data. */
2130 auto_obstack wchar_buf;
2132 while (1)
2134 int num_chars;
2135 gdb_wchar_t *chars;
2136 const gdb_byte *buf;
2137 size_t buflen;
2138 int print_escape = 1;
2139 enum wchar_iterate_result result;
2141 num_chars = iter.iterate (&result, &chars, &buf, &buflen);
2142 if (num_chars < 0)
2143 break;
2144 if (num_chars > 0)
2146 /* If all characters are printable, print them. Otherwise,
2147 we're going to have to print an escape sequence. We
2148 check all characters because we want to print the target
2149 bytes in the escape sequence, and we don't know character
2150 boundaries there. */
2151 int i;
2153 print_escape = 0;
2154 for (i = 0; i < num_chars; ++i)
2155 if (!wchar_printable (chars[i]))
2157 print_escape = 1;
2158 break;
2161 if (!print_escape)
2163 for (i = 0; i < num_chars; ++i)
2164 print_wchar (chars[i], buf, buflen,
2165 TYPE_LENGTH (type), byte_order,
2166 &wchar_buf, quoter, &need_escape);
2170 /* This handles the NUM_CHARS == 0 case as well. */
2171 if (print_escape)
2172 print_wchar (gdb_WEOF, buf, buflen, TYPE_LENGTH (type),
2173 byte_order, &wchar_buf, quoter, &need_escape);
2176 /* The output in the host encoding. */
2177 auto_obstack output;
2179 convert_between_encodings (INTERMEDIATE_ENCODING, host_charset (),
2180 (gdb_byte *) obstack_base (&wchar_buf),
2181 obstack_object_size (&wchar_buf),
2182 sizeof (gdb_wchar_t), &output, translit_char);
2183 obstack_1grow (&output, '\0');
2185 gdb_puts ((const char *) obstack_base (&output), stream);
2188 /* Return the repeat count of the next character/byte in ITER,
2189 storing the result in VEC. */
2191 static int
2192 count_next_character (wchar_iterator *iter,
2193 std::vector<converted_character> *vec)
2195 struct converted_character *current;
2197 if (vec->empty ())
2199 struct converted_character tmp;
2200 gdb_wchar_t *chars;
2202 tmp.num_chars
2203 = iter->iterate (&tmp.result, &chars, &tmp.buf, &tmp.buflen);
2204 if (tmp.num_chars > 0)
2206 gdb_assert (tmp.num_chars < MAX_WCHARS);
2207 memcpy (tmp.chars, chars, tmp.num_chars * sizeof (gdb_wchar_t));
2209 vec->push_back (tmp);
2212 current = &vec->back ();
2214 /* Count repeated characters or bytes. */
2215 current->repeat_count = 1;
2216 if (current->num_chars == -1)
2218 /* EOF */
2219 return -1;
2221 else
2223 gdb_wchar_t *chars;
2224 struct converted_character d;
2225 int repeat;
2227 d.repeat_count = 0;
2229 while (1)
2231 /* Get the next character. */
2232 d.num_chars = iter->iterate (&d.result, &chars, &d.buf, &d.buflen);
2234 /* If a character was successfully converted, save the character
2235 into the converted character. */
2236 if (d.num_chars > 0)
2238 gdb_assert (d.num_chars < MAX_WCHARS);
2239 memcpy (d.chars, chars, WCHAR_BUFLEN (d.num_chars));
2242 /* Determine if the current character is the same as this
2243 new character. */
2244 if (d.num_chars == current->num_chars && d.result == current->result)
2246 /* There are two cases to consider:
2248 1) Equality of converted character (num_chars > 0)
2249 2) Equality of non-converted character (num_chars == 0) */
2250 if ((current->num_chars > 0
2251 && memcmp (current->chars, d.chars,
2252 WCHAR_BUFLEN (current->num_chars)) == 0)
2253 || (current->num_chars == 0
2254 && current->buflen == d.buflen
2255 && memcmp (current->buf, d.buf, current->buflen) == 0))
2256 ++current->repeat_count;
2257 else
2258 break;
2260 else
2261 break;
2264 /* Push this next converted character onto the result vector. */
2265 repeat = current->repeat_count;
2266 vec->push_back (d);
2267 return repeat;
2271 /* Print the characters in CHARS to the OBSTACK. QUOTE_CHAR is the quote
2272 character to use with string output. WIDTH is the size of the output
2273 character type. BYTE_ORDER is the target byte order. OPTIONS
2274 is the user's print options. */
2276 static void
2277 print_converted_chars_to_obstack (struct obstack *obstack,
2278 const std::vector<converted_character> &chars,
2279 int quote_char, int width,
2280 enum bfd_endian byte_order,
2281 const struct value_print_options *options)
2283 unsigned int idx;
2284 const converted_character *elem;
2285 enum {START, SINGLE, REPEAT, INCOMPLETE, FINISH} state, last;
2286 gdb_wchar_t wide_quote_char = gdb_btowc (quote_char);
2287 int need_escape = 0;
2289 /* Set the start state. */
2290 idx = 0;
2291 last = state = START;
2292 elem = NULL;
2294 while (1)
2296 switch (state)
2298 case START:
2299 /* Nothing to do. */
2300 break;
2302 case SINGLE:
2304 int j;
2306 /* We are outputting a single character
2307 (< options->repeat_count_threshold). */
2309 if (last != SINGLE)
2311 /* We were outputting some other type of content, so we
2312 must output and a comma and a quote. */
2313 if (last != START)
2314 obstack_grow_wstr (obstack, LCST (", "));
2315 obstack_grow (obstack, &wide_quote_char, sizeof (gdb_wchar_t));
2317 /* Output the character. */
2318 for (j = 0; j < elem->repeat_count; ++j)
2320 if (elem->result == wchar_iterate_ok)
2321 print_wchar (elem->chars[0], elem->buf, elem->buflen, width,
2322 byte_order, obstack, quote_char, &need_escape);
2323 else
2324 print_wchar (gdb_WEOF, elem->buf, elem->buflen, width,
2325 byte_order, obstack, quote_char, &need_escape);
2328 break;
2330 case REPEAT:
2332 int j;
2334 /* We are outputting a character with a repeat count
2335 greater than options->repeat_count_threshold. */
2337 if (last == SINGLE)
2339 /* We were outputting a single string. Terminate the
2340 string. */
2341 obstack_grow (obstack, &wide_quote_char, sizeof (gdb_wchar_t));
2343 if (last != START)
2344 obstack_grow_wstr (obstack, LCST (", "));
2346 /* Output the character and repeat string. */
2347 obstack_grow_wstr (obstack, LCST ("'"));
2348 if (elem->result == wchar_iterate_ok)
2349 print_wchar (elem->chars[0], elem->buf, elem->buflen, width,
2350 byte_order, obstack, quote_char, &need_escape);
2351 else
2352 print_wchar (gdb_WEOF, elem->buf, elem->buflen, width,
2353 byte_order, obstack, quote_char, &need_escape);
2354 obstack_grow_wstr (obstack, LCST ("'"));
2355 std::string s = string_printf (_(" <repeats %u times>"),
2356 elem->repeat_count);
2357 for (j = 0; s[j]; ++j)
2359 gdb_wchar_t w = gdb_btowc (s[j]);
2360 obstack_grow (obstack, &w, sizeof (gdb_wchar_t));
2363 break;
2365 case INCOMPLETE:
2366 /* We are outputting an incomplete sequence. */
2367 if (last == SINGLE)
2369 /* If we were outputting a string of SINGLE characters,
2370 terminate the quote. */
2371 obstack_grow (obstack, &wide_quote_char, sizeof (gdb_wchar_t));
2373 if (last != START)
2374 obstack_grow_wstr (obstack, LCST (", "));
2376 /* Output the incomplete sequence string. */
2377 obstack_grow_wstr (obstack, LCST ("<incomplete sequence "));
2378 print_wchar (gdb_WEOF, elem->buf, elem->buflen, width, byte_order,
2379 obstack, 0, &need_escape);
2380 obstack_grow_wstr (obstack, LCST (">"));
2382 /* We do not attempt to output anything after this. */
2383 state = FINISH;
2384 break;
2386 case FINISH:
2387 /* All done. If we were outputting a string of SINGLE
2388 characters, the string must be terminated. Otherwise,
2389 REPEAT and INCOMPLETE are always left properly terminated. */
2390 if (last == SINGLE)
2391 obstack_grow (obstack, &wide_quote_char, sizeof (gdb_wchar_t));
2393 return;
2396 /* Get the next element and state. */
2397 last = state;
2398 if (state != FINISH)
2400 elem = &chars[idx++];
2401 switch (elem->result)
2403 case wchar_iterate_ok:
2404 case wchar_iterate_invalid:
2405 if (elem->repeat_count > options->repeat_count_threshold)
2406 state = REPEAT;
2407 else
2408 state = SINGLE;
2409 break;
2411 case wchar_iterate_incomplete:
2412 state = INCOMPLETE;
2413 break;
2415 case wchar_iterate_eof:
2416 state = FINISH;
2417 break;
2423 /* Print the character string STRING, printing at most LENGTH
2424 characters. LENGTH is -1 if the string is nul terminated. TYPE is
2425 the type of each character. OPTIONS holds the printing options;
2426 printing stops early if the number hits print_max; repeat counts
2427 are printed as appropriate. Print ellipses at the end if we had to
2428 stop before printing LENGTH characters, or if FORCE_ELLIPSES.
2429 QUOTE_CHAR is the character to print at each end of the string. If
2430 C_STYLE_TERMINATOR is true, and the last character is 0, then it is
2431 omitted. */
2433 void
2434 generic_printstr (struct ui_file *stream, struct type *type,
2435 const gdb_byte *string, unsigned int length,
2436 const char *encoding, int force_ellipses,
2437 int quote_char, int c_style_terminator,
2438 const struct value_print_options *options)
2440 enum bfd_endian byte_order = type_byte_order (type);
2441 unsigned int i;
2442 int width = TYPE_LENGTH (type);
2443 int finished = 0;
2444 struct converted_character *last;
2446 if (length == -1)
2448 unsigned long current_char = 1;
2450 for (i = 0; current_char; ++i)
2452 QUIT;
2453 current_char = extract_unsigned_integer (string + i * width,
2454 width, byte_order);
2456 length = i;
2459 /* If the string was not truncated due to `set print elements', and
2460 the last byte of it is a null, we don't print that, in
2461 traditional C style. */
2462 if (c_style_terminator
2463 && !force_ellipses
2464 && length > 0
2465 && (extract_unsigned_integer (string + (length - 1) * width,
2466 width, byte_order) == 0))
2467 length--;
2469 if (length == 0)
2471 gdb_puts ("\"\"", stream);
2472 return;
2475 /* Arrange to iterate over the characters, in wchar_t form. */
2476 wchar_iterator iter (string, length * width, encoding, width);
2477 std::vector<converted_character> converted_chars;
2479 /* Convert characters until the string is over or the maximum
2480 number of printed characters has been reached. */
2481 i = 0;
2482 while (i < options->print_max)
2484 int r;
2486 QUIT;
2488 /* Grab the next character and repeat count. */
2489 r = count_next_character (&iter, &converted_chars);
2491 /* If less than zero, the end of the input string was reached. */
2492 if (r < 0)
2493 break;
2495 /* Otherwise, add the count to the total print count and get
2496 the next character. */
2497 i += r;
2500 /* Get the last element and determine if the entire string was
2501 processed. */
2502 last = &converted_chars.back ();
2503 finished = (last->result == wchar_iterate_eof);
2505 /* Ensure that CONVERTED_CHARS is terminated. */
2506 last->result = wchar_iterate_eof;
2508 /* WCHAR_BUF is the obstack we use to represent the string in
2509 wchar_t form. */
2510 auto_obstack wchar_buf;
2512 /* Print the output string to the obstack. */
2513 print_converted_chars_to_obstack (&wchar_buf, converted_chars, quote_char,
2514 width, byte_order, options);
2516 if (force_ellipses || !finished)
2517 obstack_grow_wstr (&wchar_buf, LCST ("..."));
2519 /* OUTPUT is where we collect `char's for printing. */
2520 auto_obstack output;
2522 convert_between_encodings (INTERMEDIATE_ENCODING, host_charset (),
2523 (gdb_byte *) obstack_base (&wchar_buf),
2524 obstack_object_size (&wchar_buf),
2525 sizeof (gdb_wchar_t), &output, translit_char);
2526 obstack_1grow (&output, '\0');
2528 gdb_puts ((const char *) obstack_base (&output), stream);
2531 /* Print a string from the inferior, starting at ADDR and printing up to LEN
2532 characters, of WIDTH bytes a piece, to STREAM. If LEN is -1, printing
2533 stops at the first null byte, otherwise printing proceeds (including null
2534 bytes) until either print_max or LEN characters have been printed,
2535 whichever is smaller. ENCODING is the name of the string's
2536 encoding. It can be NULL, in which case the target encoding is
2537 assumed. */
2540 val_print_string (struct type *elttype, const char *encoding,
2541 CORE_ADDR addr, int len,
2542 struct ui_file *stream,
2543 const struct value_print_options *options)
2545 int force_ellipsis = 0; /* Force ellipsis to be printed if nonzero. */
2546 int err; /* Non-zero if we got a bad read. */
2547 int found_nul; /* Non-zero if we found the nul char. */
2548 unsigned int fetchlimit; /* Maximum number of chars to print. */
2549 int bytes_read;
2550 gdb::unique_xmalloc_ptr<gdb_byte> buffer; /* Dynamically growable fetch buffer. */
2551 struct gdbarch *gdbarch = elttype->arch ();
2552 enum bfd_endian byte_order = type_byte_order (elttype);
2553 int width = TYPE_LENGTH (elttype);
2555 /* First we need to figure out the limit on the number of characters we are
2556 going to attempt to fetch and print. This is actually pretty simple. If
2557 LEN >= zero, then the limit is the minimum of LEN and print_max. If
2558 LEN is -1, then the limit is print_max. This is true regardless of
2559 whether print_max is zero, UINT_MAX (unlimited), or something in between,
2560 because finding the null byte (or available memory) is what actually
2561 limits the fetch. */
2563 fetchlimit = (len == -1 ? options->print_max : std::min ((unsigned) len,
2564 options->print_max));
2566 err = target_read_string (addr, len, width, fetchlimit,
2567 &buffer, &bytes_read);
2569 addr += bytes_read;
2571 /* We now have either successfully filled the buffer to fetchlimit,
2572 or terminated early due to an error or finding a null char when
2573 LEN is -1. */
2575 /* Determine found_nul by looking at the last character read. */
2576 found_nul = 0;
2577 if (bytes_read >= width)
2578 found_nul = extract_unsigned_integer (buffer.get () + bytes_read - width,
2579 width, byte_order) == 0;
2580 if (len == -1 && !found_nul)
2582 gdb_byte *peekbuf;
2584 /* We didn't find a NUL terminator we were looking for. Attempt
2585 to peek at the next character. If not successful, or it is not
2586 a null byte, then force ellipsis to be printed. */
2588 peekbuf = (gdb_byte *) alloca (width);
2590 if (target_read_memory (addr, peekbuf, width) == 0
2591 && extract_unsigned_integer (peekbuf, width, byte_order) != 0)
2592 force_ellipsis = 1;
2594 else if ((len >= 0 && err != 0) || (len > bytes_read / width))
2596 /* Getting an error when we have a requested length, or fetching less
2597 than the number of characters actually requested, always make us
2598 print ellipsis. */
2599 force_ellipsis = 1;
2602 /* If we get an error before fetching anything, don't print a string.
2603 But if we fetch something and then get an error, print the string
2604 and then the error message. */
2605 if (err == 0 || bytes_read > 0)
2606 current_language->printstr (stream, elttype, buffer.get (),
2607 bytes_read / width,
2608 encoding, force_ellipsis, options);
2610 if (err != 0)
2612 std::string str = memory_error_message (TARGET_XFER_E_IO, gdbarch, addr);
2614 gdb_printf (stream, _("<error: %ps>"),
2615 styled_string (metadata_style.style (),
2616 str.c_str ()));
2619 return (bytes_read / width);
2622 /* Handle 'show print max-depth'. */
2624 static void
2625 show_print_max_depth (struct ui_file *file, int from_tty,
2626 struct cmd_list_element *c, const char *value)
2628 gdb_printf (file, _("Maximum print depth is %s.\n"), value);
2632 /* The 'set input-radix' command writes to this auxiliary variable.
2633 If the requested radix is valid, INPUT_RADIX is updated; otherwise,
2634 it is left unchanged. */
2636 static unsigned input_radix_1 = 10;
2638 /* Validate an input or output radix setting, and make sure the user
2639 knows what they really did here. Radix setting is confusing, e.g.
2640 setting the input radix to "10" never changes it! */
2642 static void
2643 set_input_radix (const char *args, int from_tty, struct cmd_list_element *c)
2645 set_input_radix_1 (from_tty, input_radix_1);
2648 static void
2649 set_input_radix_1 (int from_tty, unsigned radix)
2651 /* We don't currently disallow any input radix except 0 or 1, which don't
2652 make any mathematical sense. In theory, we can deal with any input
2653 radix greater than 1, even if we don't have unique digits for every
2654 value from 0 to radix-1, but in practice we lose on large radix values.
2655 We should either fix the lossage or restrict the radix range more.
2656 (FIXME). */
2658 if (radix < 2)
2660 input_radix_1 = input_radix;
2661 error (_("Nonsense input radix ``decimal %u''; input radix unchanged."),
2662 radix);
2664 input_radix_1 = input_radix = radix;
2665 if (from_tty)
2667 gdb_printf (_("Input radix now set to "
2668 "decimal %u, hex %x, octal %o.\n"),
2669 radix, radix, radix);
2673 /* The 'set output-radix' command writes to this auxiliary variable.
2674 If the requested radix is valid, OUTPUT_RADIX is updated,
2675 otherwise, it is left unchanged. */
2677 static unsigned output_radix_1 = 10;
2679 static void
2680 set_output_radix (const char *args, int from_tty, struct cmd_list_element *c)
2682 set_output_radix_1 (from_tty, output_radix_1);
2685 static void
2686 set_output_radix_1 (int from_tty, unsigned radix)
2688 /* Validate the radix and disallow ones that we aren't prepared to
2689 handle correctly, leaving the radix unchanged. */
2690 switch (radix)
2692 case 16:
2693 user_print_options.output_format = 'x'; /* hex */
2694 break;
2695 case 10:
2696 user_print_options.output_format = 0; /* decimal */
2697 break;
2698 case 8:
2699 user_print_options.output_format = 'o'; /* octal */
2700 break;
2701 default:
2702 output_radix_1 = output_radix;
2703 error (_("Unsupported output radix ``decimal %u''; "
2704 "output radix unchanged."),
2705 radix);
2707 output_radix_1 = output_radix = radix;
2708 if (from_tty)
2710 gdb_printf (_("Output radix now set to "
2711 "decimal %u, hex %x, octal %o.\n"),
2712 radix, radix, radix);
2716 /* Set both the input and output radix at once. Try to set the output radix
2717 first, since it has the most restrictive range. An radix that is valid as
2718 an output radix is also valid as an input radix.
2720 It may be useful to have an unusual input radix. If the user wishes to
2721 set an input radix that is not valid as an output radix, he needs to use
2722 the 'set input-radix' command. */
2724 static void
2725 set_radix (const char *arg, int from_tty)
2727 unsigned radix;
2729 radix = (arg == NULL) ? 10 : parse_and_eval_long (arg);
2730 set_output_radix_1 (0, radix);
2731 set_input_radix_1 (0, radix);
2732 if (from_tty)
2734 gdb_printf (_("Input and output radices now set to "
2735 "decimal %u, hex %x, octal %o.\n"),
2736 radix, radix, radix);
2740 /* Show both the input and output radices. */
2742 static void
2743 show_radix (const char *arg, int from_tty)
2745 if (from_tty)
2747 if (input_radix == output_radix)
2749 gdb_printf (_("Input and output radices set to "
2750 "decimal %u, hex %x, octal %o.\n"),
2751 input_radix, input_radix, input_radix);
2753 else
2755 gdb_printf (_("Input radix set to decimal "
2756 "%u, hex %x, octal %o.\n"),
2757 input_radix, input_radix, input_radix);
2758 gdb_printf (_("Output radix set to decimal "
2759 "%u, hex %x, octal %o.\n"),
2760 output_radix, output_radix, output_radix);
2766 /* Controls printing of vtbl's. */
2767 static void
2768 show_vtblprint (struct ui_file *file, int from_tty,
2769 struct cmd_list_element *c, const char *value)
2771 gdb_printf (file, _("\
2772 Printing of C++ virtual function tables is %s.\n"),
2773 value);
2776 /* Controls looking up an object's derived type using what we find in
2777 its vtables. */
2778 static void
2779 show_objectprint (struct ui_file *file, int from_tty,
2780 struct cmd_list_element *c,
2781 const char *value)
2783 gdb_printf (file, _("\
2784 Printing of object's derived type based on vtable info is %s.\n"),
2785 value);
2788 static void
2789 show_static_field_print (struct ui_file *file, int from_tty,
2790 struct cmd_list_element *c,
2791 const char *value)
2793 gdb_printf (file,
2794 _("Printing of C++ static members is %s.\n"),
2795 value);
2800 /* A couple typedefs to make writing the options a bit more
2801 convenient. */
2802 using boolean_option_def
2803 = gdb::option::boolean_option_def<value_print_options>;
2804 using uinteger_option_def
2805 = gdb::option::uinteger_option_def<value_print_options>;
2806 using zuinteger_unlimited_option_def
2807 = gdb::option::zuinteger_unlimited_option_def<value_print_options>;
2809 /* Definitions of options for the "print" and "compile print"
2810 commands. */
2811 static const gdb::option::option_def value_print_option_defs[] = {
2813 boolean_option_def {
2814 "address",
2815 [] (value_print_options *opt) { return &opt->addressprint; },
2816 show_addressprint, /* show_cmd_cb */
2817 N_("Set printing of addresses."),
2818 N_("Show printing of addresses."),
2819 NULL, /* help_doc */
2822 boolean_option_def {
2823 "array",
2824 [] (value_print_options *opt) { return &opt->prettyformat_arrays; },
2825 show_prettyformat_arrays, /* show_cmd_cb */
2826 N_("Set pretty formatting of arrays."),
2827 N_("Show pretty formatting of arrays."),
2828 NULL, /* help_doc */
2831 boolean_option_def {
2832 "array-indexes",
2833 [] (value_print_options *opt) { return &opt->print_array_indexes; },
2834 show_print_array_indexes, /* show_cmd_cb */
2835 N_("Set printing of array indexes."),
2836 N_("Show printing of array indexes."),
2837 NULL, /* help_doc */
2840 uinteger_option_def {
2841 "elements",
2842 [] (value_print_options *opt) { return &opt->print_max; },
2843 show_print_max, /* show_cmd_cb */
2844 N_("Set limit on string chars or array elements to print."),
2845 N_("Show limit on string chars or array elements to print."),
2846 N_("\"unlimited\" causes there to be no limit."),
2849 zuinteger_unlimited_option_def {
2850 "max-depth",
2851 [] (value_print_options *opt) { return &opt->max_depth; },
2852 show_print_max_depth, /* show_cmd_cb */
2853 N_("Set maximum print depth for nested structures, unions and arrays."),
2854 N_("Show maximum print depth for nested structures, unions, and arrays."),
2855 N_("When structures, unions, or arrays are nested beyond this depth then they\n\
2856 will be replaced with either '{...}' or '(...)' depending on the language.\n\
2857 Use \"unlimited\" to print the complete structure.")
2860 boolean_option_def {
2861 "memory-tag-violations",
2862 [] (value_print_options *opt) { return &opt->memory_tag_violations; },
2863 show_memory_tag_violations, /* show_cmd_cb */
2864 N_("Set printing of memory tag violations for pointers."),
2865 N_("Show printing of memory tag violations for pointers."),
2866 N_("Issue a warning when the printed value is a pointer\n\
2867 whose logical tag doesn't match the allocation tag of the memory\n\
2868 location it points to."),
2871 boolean_option_def {
2872 "null-stop",
2873 [] (value_print_options *opt) { return &opt->stop_print_at_null; },
2874 show_stop_print_at_null, /* show_cmd_cb */
2875 N_("Set printing of char arrays to stop at first null char."),
2876 N_("Show printing of char arrays to stop at first null char."),
2877 NULL, /* help_doc */
2880 boolean_option_def {
2881 "object",
2882 [] (value_print_options *opt) { return &opt->objectprint; },
2883 show_objectprint, /* show_cmd_cb */
2884 _("Set printing of C++ virtual function tables."),
2885 _("Show printing of C++ virtual function tables."),
2886 NULL, /* help_doc */
2889 boolean_option_def {
2890 "pretty",
2891 [] (value_print_options *opt) { return &opt->prettyformat_structs; },
2892 show_prettyformat_structs, /* show_cmd_cb */
2893 N_("Set pretty formatting of structures."),
2894 N_("Show pretty formatting of structures."),
2895 NULL, /* help_doc */
2898 boolean_option_def {
2899 "raw-values",
2900 [] (value_print_options *opt) { return &opt->raw; },
2901 NULL, /* show_cmd_cb */
2902 N_("Set whether to print values in raw form."),
2903 N_("Show whether to print values in raw form."),
2904 N_("If set, values are printed in raw form, bypassing any\n\
2905 pretty-printers for that value.")
2908 uinteger_option_def {
2909 "repeats",
2910 [] (value_print_options *opt) { return &opt->repeat_count_threshold; },
2911 show_repeat_count_threshold, /* show_cmd_cb */
2912 N_("Set threshold for repeated print elements."),
2913 N_("Show threshold for repeated print elements."),
2914 N_("\"unlimited\" causes all elements to be individually printed."),
2917 boolean_option_def {
2918 "static-members",
2919 [] (value_print_options *opt) { return &opt->static_field_print; },
2920 show_static_field_print, /* show_cmd_cb */
2921 N_("Set printing of C++ static members."),
2922 N_("Show printing of C++ static members."),
2923 NULL, /* help_doc */
2926 boolean_option_def {
2927 "symbol",
2928 [] (value_print_options *opt) { return &opt->symbol_print; },
2929 show_symbol_print, /* show_cmd_cb */
2930 N_("Set printing of symbol names when printing pointers."),
2931 N_("Show printing of symbol names when printing pointers."),
2932 NULL, /* help_doc */
2935 boolean_option_def {
2936 "union",
2937 [] (value_print_options *opt) { return &opt->unionprint; },
2938 show_unionprint, /* show_cmd_cb */
2939 N_("Set printing of unions interior to structures."),
2940 N_("Show printing of unions interior to structures."),
2941 NULL, /* help_doc */
2944 boolean_option_def {
2945 "vtbl",
2946 [] (value_print_options *opt) { return &opt->vtblprint; },
2947 show_vtblprint, /* show_cmd_cb */
2948 N_("Set printing of C++ virtual function tables."),
2949 N_("Show printing of C++ virtual function tables."),
2950 NULL, /* help_doc */
2954 /* See valprint.h. */
2956 gdb::option::option_def_group
2957 make_value_print_options_def_group (value_print_options *opts)
2959 return {{value_print_option_defs}, opts};
2962 #if GDB_SELF_TEST
2964 /* Test printing of TYPE_CODE_FLAGS values. */
2966 static void
2967 test_print_flags (gdbarch *arch)
2969 type *flags_type = arch_flags_type (arch, "test_type", 32);
2970 type *field_type = builtin_type (arch)->builtin_uint32;
2972 /* Value: 1010 1010
2973 Fields: CCCB BAAA */
2974 append_flags_type_field (flags_type, 0, 3, field_type, "A");
2975 append_flags_type_field (flags_type, 3, 2, field_type, "B");
2976 append_flags_type_field (flags_type, 5, 3, field_type, "C");
2978 value *val = allocate_value (flags_type);
2979 gdb_byte *contents = value_contents_writeable (val).data ();
2980 store_unsigned_integer (contents, 4, gdbarch_byte_order (arch), 0xaa);
2982 string_file out;
2983 val_print_type_code_flags (flags_type, val, 0, &out);
2984 SELF_CHECK (out.string () == "[ A=2 B=1 C=5 ]");
2987 #endif
2989 void _initialize_valprint ();
2990 void
2991 _initialize_valprint ()
2993 #if GDB_SELF_TEST
2994 selftests::register_test_foreach_arch ("print-flags", test_print_flags);
2995 #endif
2997 set_show_commands setshow_print_cmds
2998 = add_setshow_prefix_cmd ("print", no_class,
2999 _("Generic command for setting how things print."),
3000 _("Generic command for showing print settings."),
3001 &setprintlist, &showprintlist,
3002 &setlist, &showlist);
3003 add_alias_cmd ("p", setshow_print_cmds.set, no_class, 1, &setlist);
3004 /* Prefer set print to set prompt. */
3005 add_alias_cmd ("pr", setshow_print_cmds.set, no_class, 1, &setlist);
3006 add_alias_cmd ("p", setshow_print_cmds.show, no_class, 1, &showlist);
3007 add_alias_cmd ("pr", setshow_print_cmds.show, no_class, 1, &showlist);
3009 set_show_commands setshow_print_raw_cmds
3010 = add_setshow_prefix_cmd
3011 ("raw", no_class,
3012 _("Generic command for setting what things to print in \"raw\" mode."),
3013 _("Generic command for showing \"print raw\" settings."),
3014 &setprintrawlist, &showprintrawlist, &setprintlist, &showprintlist);
3015 deprecate_cmd (setshow_print_raw_cmds.set, nullptr);
3016 deprecate_cmd (setshow_print_raw_cmds.show, nullptr);
3018 gdb::option::add_setshow_cmds_for_options
3019 (class_support, &user_print_options, value_print_option_defs,
3020 &setprintlist, &showprintlist);
3022 add_setshow_zuinteger_cmd ("input-radix", class_support, &input_radix_1,
3023 _("\
3024 Set default input radix for entering numbers."), _("\
3025 Show default input radix for entering numbers."), NULL,
3026 set_input_radix,
3027 show_input_radix,
3028 &setlist, &showlist);
3030 add_setshow_zuinteger_cmd ("output-radix", class_support, &output_radix_1,
3031 _("\
3032 Set default output radix for printing of values."), _("\
3033 Show default output radix for printing of values."), NULL,
3034 set_output_radix,
3035 show_output_radix,
3036 &setlist, &showlist);
3038 /* The "set radix" and "show radix" commands are special in that
3039 they are like normal set and show commands but allow two normally
3040 independent variables to be either set or shown with a single
3041 command. So the usual deprecated_add_set_cmd() and [deleted]
3042 add_show_from_set() commands aren't really appropriate. */
3043 /* FIXME: i18n: With the new add_setshow_integer command, that is no
3044 longer true - show can display anything. */
3045 add_cmd ("radix", class_support, set_radix, _("\
3046 Set default input and output number radices.\n\
3047 Use 'set input-radix' or 'set output-radix' to independently set each.\n\
3048 Without an argument, sets both radices back to the default value of 10."),
3049 &setlist);
3050 add_cmd ("radix", class_support, show_radix, _("\
3051 Show the default input and output number radices.\n\
3052 Use 'show input-radix' or 'show output-radix' to independently show each."),
3053 &showlist);