]> Git Repo - binutils.git/blob - gdb/valprint.c
43ba08d5ef23cf88edabd44dfb42bd94268db2c6
[binutils.git] / gdb / valprint.c
1 /* Print values for GDB, the GNU debugger.
2
3    Copyright (C) 1986-2022 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 "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"
48
49 /* Maximum number of wchars returned from wchar_iterate.  */
50 #define MAX_WCHARS 4
51
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))
55
56 /* Character buffer size saved while iterating over wchars.  */
57 #define WCHAR_BUFLEN_MAX WCHAR_BUFLEN (MAX_WCHARS)
58
59 /* A structure to encapsulate state information from iterated
60    character conversions.  */
61 struct converted_character
62 {
63   /* The number of characters converted.  */
64   int num_chars;
65
66   /* The result of the conversion.  See charset.h for more.  */
67   enum wchar_iterate_result result;
68
69   /* The (saved) converted character(s).  */
70   gdb_wchar_t chars[WCHAR_BUFLEN_MAX];
71
72   /* The first converted target byte.  */
73   const gdb_byte *buf;
74
75   /* The number of bytes converted.  */
76   size_t buflen;
77
78   /* How many times this character(s) is repeated.  */
79   int repeat_count;
80 };
81
82 /* Command lists for set/show print raw.  */
83 struct cmd_list_element *setprintrawlist;
84 struct cmd_list_element *showprintrawlist;
85
86 /* Prototypes for local functions */
87
88 static int partial_memory_read (CORE_ADDR memaddr, gdb_byte *myaddr,
89                                 int len, int *errptr);
90
91 static void set_input_radix_1 (int, unsigned);
92
93 static void set_output_radix_1 (int, unsigned);
94
95 static void val_print_type_code_flags (struct type *type,
96                                        struct value *original_value,
97                                        int embedded_offset,
98                                        struct ui_file *stream);
99
100 #define PRINT_MAX_DEFAULT 200   /* Start print_max off at this value.  */
101 #define PRINT_MAX_DEPTH_DEFAULT 20      /* Start print_max_depth off at this value. */
102
103 struct value_print_options user_print_options =
104 {
105   Val_prettyformat_default,     /* prettyformat */
106   0,                            /* prettyformat_arrays */
107   0,                            /* prettyformat_structs */
108   0,                            /* vtblprint */
109   1,                            /* unionprint */
110   1,                            /* addressprint */
111   0,                            /* objectprint */
112   PRINT_MAX_DEFAULT,            /* print_max */
113   10,                           /* repeat_count_threshold */
114   0,                            /* output_format */
115   0,                            /* format */
116   1,                            /* memory_tag_violations */
117   0,                            /* stop_print_at_null */
118   0,                            /* print_array_indexes */
119   0,                            /* deref_ref */
120   1,                            /* static_field_print */
121   1,                            /* pascal_static_field_print */
122   0,                            /* raw */
123   0,                            /* summary */
124   1,                            /* symbol_print */
125   PRINT_MAX_DEPTH_DEFAULT,      /* max_depth */
126   1                             /* finish_print */
127 };
128
129 /* Initialize *OPTS to be a copy of the user print options.  */
130 void
131 get_user_print_options (struct value_print_options *opts)
132 {
133   *opts = user_print_options;
134 }
135
136 /* Initialize *OPTS to be a copy of the user print options, but with
137    pretty-formatting disabled.  */
138 void
139 get_no_prettyformat_print_options (struct value_print_options *opts)
140 {  
141   *opts = user_print_options;
142   opts->prettyformat = Val_no_prettyformat;
143 }
144
145 /* Initialize *OPTS to be a copy of the user print options, but using
146    FORMAT as the formatting option.  */
147 void
148 get_formatted_print_options (struct value_print_options *opts,
149                              char format)
150 {
151   *opts = user_print_options;
152   opts->format = format;
153 }
154
155 static void
156 show_print_max (struct ui_file *file, int from_tty,
157                 struct cmd_list_element *c, const char *value)
158 {
159   fprintf_filtered (file,
160                     _("Limit on string chars or array "
161                       "elements to print is %s.\n"),
162                     value);
163 }
164
165
166 /* Default input and output radixes, and output format letter.  */
167
168 unsigned input_radix = 10;
169 static void
170 show_input_radix (struct ui_file *file, int from_tty,
171                   struct cmd_list_element *c, const char *value)
172 {
173   fprintf_filtered (file,
174                     _("Default input radix for entering numbers is %s.\n"),
175                     value);
176 }
177
178 unsigned output_radix = 10;
179 static void
180 show_output_radix (struct ui_file *file, int from_tty,
181                    struct cmd_list_element *c, const char *value)
182 {
183   fprintf_filtered (file,
184                     _("Default output radix for printing of values is %s.\n"),
185                     value);
186 }
187
188 /* By default we print arrays without printing the index of each element in
189    the array.  This behavior can be changed by setting PRINT_ARRAY_INDEXES.  */
190
191 static void
192 show_print_array_indexes (struct ui_file *file, int from_tty,
193                           struct cmd_list_element *c, const char *value)
194 {
195   fprintf_filtered (file, _("Printing of array indexes is %s.\n"), value);
196 }
197
198 /* Print repeat counts if there are more than this many repetitions of an
199    element in an array.  Referenced by the low level language dependent
200    print routines.  */
201
202 static void
203 show_repeat_count_threshold (struct ui_file *file, int from_tty,
204                              struct cmd_list_element *c, const char *value)
205 {
206   fprintf_filtered (file, _("Threshold for repeated print elements is %s.\n"),
207                     value);
208 }
209
210 /* If nonzero, prints memory tag violations for pointers.  */
211
212 static void
213 show_memory_tag_violations (struct ui_file *file, int from_tty,
214                             struct cmd_list_element *c, const char *value)
215 {
216   fprintf_filtered (file,
217                     _("Printing of memory tag violations is %s.\n"),
218                     value);
219 }
220
221 /* If nonzero, stops printing of char arrays at first null.  */
222
223 static void
224 show_stop_print_at_null (struct ui_file *file, int from_tty,
225                          struct cmd_list_element *c, const char *value)
226 {
227   fprintf_filtered (file,
228                     _("Printing of char arrays to stop "
229                       "at first null char is %s.\n"),
230                     value);
231 }
232
233 /* Controls pretty printing of structures.  */
234
235 static void
236 show_prettyformat_structs (struct ui_file *file, int from_tty,
237                           struct cmd_list_element *c, const char *value)
238 {
239   fprintf_filtered (file, _("Pretty formatting of structures is %s.\n"), value);
240 }
241
242 /* Controls pretty printing of arrays.  */
243
244 static void
245 show_prettyformat_arrays (struct ui_file *file, int from_tty,
246                          struct cmd_list_element *c, const char *value)
247 {
248   fprintf_filtered (file, _("Pretty formatting of arrays is %s.\n"), value);
249 }
250
251 /* If nonzero, causes unions inside structures or other unions to be
252    printed.  */
253
254 static void
255 show_unionprint (struct ui_file *file, int from_tty,
256                  struct cmd_list_element *c, const char *value)
257 {
258   fprintf_filtered (file,
259                     _("Printing of unions interior to structures is %s.\n"),
260                     value);
261 }
262
263 /* If nonzero, causes machine addresses to be printed in certain contexts.  */
264
265 static void
266 show_addressprint (struct ui_file *file, int from_tty,
267                    struct cmd_list_element *c, const char *value)
268 {
269   fprintf_filtered (file, _("Printing of addresses is %s.\n"), value);
270 }
271
272 static void
273 show_symbol_print (struct ui_file *file, int from_tty,
274                    struct cmd_list_element *c, const char *value)
275 {
276   fprintf_filtered (file,
277                     _("Printing of symbols when printing pointers is %s.\n"),
278                     value);
279 }
280
281 \f
282
283 /* A helper function for val_print.  When printing in "summary" mode,
284    we want to print scalar arguments, but not aggregate arguments.
285    This function distinguishes between the two.  */
286
287 int
288 val_print_scalar_type_p (struct type *type)
289 {
290   type = check_typedef (type);
291   while (TYPE_IS_REFERENCE (type))
292     {
293       type = TYPE_TARGET_TYPE (type);
294       type = check_typedef (type);
295     }
296   switch (type->code ())
297     {
298     case TYPE_CODE_ARRAY:
299     case TYPE_CODE_STRUCT:
300     case TYPE_CODE_UNION:
301     case TYPE_CODE_SET:
302     case TYPE_CODE_STRING:
303       return 0;
304     default:
305       return 1;
306     }
307 }
308
309 /* A helper function for val_print.  When printing with limited depth we
310    want to print string and scalar arguments, but not aggregate arguments.
311    This function distinguishes between the two.  */
312
313 static bool
314 val_print_scalar_or_string_type_p (struct type *type,
315                                    const struct language_defn *language)
316 {
317   return (val_print_scalar_type_p (type)
318           || language->is_string_type_p (type));
319 }
320
321 /* See valprint.h.  */
322
323 int
324 valprint_check_validity (struct ui_file *stream,
325                          struct type *type,
326                          LONGEST embedded_offset,
327                          const struct value *val)
328 {
329   type = check_typedef (type);
330
331   if (type_not_associated (type))
332     {
333       val_print_not_associated (stream);
334       return 0;
335     }
336
337   if (type_not_allocated (type))
338     {
339       val_print_not_allocated (stream);
340       return 0;
341     }
342
343   if (type->code () != TYPE_CODE_UNION
344       && type->code () != TYPE_CODE_STRUCT
345       && type->code () != TYPE_CODE_ARRAY)
346     {
347       if (value_bits_any_optimized_out (val,
348                                         TARGET_CHAR_BIT * embedded_offset,
349                                         TARGET_CHAR_BIT * TYPE_LENGTH (type)))
350         {
351           val_print_optimized_out (val, stream);
352           return 0;
353         }
354
355       if (value_bits_synthetic_pointer (val, TARGET_CHAR_BIT * embedded_offset,
356                                         TARGET_CHAR_BIT * TYPE_LENGTH (type)))
357         {
358           const int is_ref = type->code () == TYPE_CODE_REF;
359           int ref_is_addressable = 0;
360
361           if (is_ref)
362             {
363               const struct value *deref_val = coerce_ref_if_computed (val);
364
365               if (deref_val != NULL)
366                 ref_is_addressable = value_lval_const (deref_val) == lval_memory;
367             }
368
369           if (!is_ref || !ref_is_addressable)
370             fputs_styled (_("<synthetic pointer>"), metadata_style.style (),
371                           stream);
372
373           /* C++ references should be valid even if they're synthetic.  */
374           return is_ref;
375         }
376
377       if (!value_bytes_available (val, embedded_offset, TYPE_LENGTH (type)))
378         {
379           val_print_unavailable (stream);
380           return 0;
381         }
382     }
383
384   return 1;
385 }
386
387 void
388 val_print_optimized_out (const struct value *val, struct ui_file *stream)
389 {
390   if (val != NULL && value_lval_const (val) == lval_register)
391     val_print_not_saved (stream);
392   else
393     fprintf_styled (stream, metadata_style.style (), _("<optimized out>"));
394 }
395
396 void
397 val_print_not_saved (struct ui_file *stream)
398 {
399   fprintf_styled (stream, metadata_style.style (), _("<not saved>"));
400 }
401
402 void
403 val_print_unavailable (struct ui_file *stream)
404 {
405   fprintf_styled (stream, metadata_style.style (), _("<unavailable>"));
406 }
407
408 void
409 val_print_invalid_address (struct ui_file *stream)
410 {
411   fprintf_styled (stream, metadata_style.style (), _("<invalid address>"));
412 }
413
414 /* Print a pointer based on the type of its target.
415
416    Arguments to this functions are roughly the same as those in
417    generic_val_print.  A difference is that ADDRESS is the address to print,
418    with embedded_offset already added.  ELTTYPE represents
419    the pointed type after check_typedef.  */
420
421 static void
422 print_unpacked_pointer (struct type *type, struct type *elttype,
423                         CORE_ADDR address, struct ui_file *stream,
424                         const struct value_print_options *options)
425 {
426   struct gdbarch *gdbarch = type->arch ();
427
428   if (elttype->code () == TYPE_CODE_FUNC)
429     {
430       /* Try to print what function it points to.  */
431       print_function_pointer_address (options, gdbarch, address, stream);
432       return;
433     }
434
435   if (options->symbol_print)
436     print_address_demangle (options, gdbarch, address, stream, demangle);
437   else if (options->addressprint)
438     gdb_puts (paddress (gdbarch, address), stream);
439 }
440
441 /* generic_val_print helper for TYPE_CODE_ARRAY.  */
442
443 static void
444 generic_val_print_array (struct value *val,
445                          struct ui_file *stream, int recurse,
446                          const struct value_print_options *options,
447                          const struct
448                              generic_val_print_decorations *decorations)
449 {
450   struct type *type = check_typedef (value_type (val));
451   struct type *unresolved_elttype = TYPE_TARGET_TYPE (type);
452   struct type *elttype = check_typedef (unresolved_elttype);
453
454   if (TYPE_LENGTH (type) > 0 && TYPE_LENGTH (unresolved_elttype) > 0)
455     {
456       LONGEST low_bound, high_bound;
457
458       if (!get_array_bounds (type, &low_bound, &high_bound))
459         error (_("Could not determine the array high bound"));
460
461       gdb_puts (decorations->array_start, stream);
462       value_print_array_elements (val, stream, recurse, options, 0);
463       gdb_puts (decorations->array_end, stream);
464     }
465   else
466     {
467       /* Array of unspecified length: treat like pointer to first elt.  */
468       print_unpacked_pointer (type, elttype, value_address (val),
469                               stream, options);
470     }
471
472 }
473
474 /* generic_value_print helper for TYPE_CODE_PTR.  */
475
476 static void
477 generic_value_print_ptr (struct value *val, struct ui_file *stream,
478                          const struct value_print_options *options)
479 {
480
481   if (options->format && options->format != 's')
482     value_print_scalar_formatted (val, options, 0, stream);
483   else
484     {
485       struct type *type = check_typedef (value_type (val));
486       struct type *elttype = check_typedef (TYPE_TARGET_TYPE (type));
487       const gdb_byte *valaddr = value_contents_for_printing (val).data ();
488       CORE_ADDR addr = unpack_pointer (type, valaddr);
489
490       print_unpacked_pointer (type, elttype, addr, stream, options);
491     }
492 }
493
494
495 /* Print '@' followed by the address contained in ADDRESS_BUFFER.  */
496
497 static void
498 print_ref_address (struct type *type, const gdb_byte *address_buffer,
499                   int embedded_offset, struct ui_file *stream)
500 {
501   struct gdbarch *gdbarch = type->arch ();
502
503   if (address_buffer != NULL)
504     {
505       CORE_ADDR address
506         = extract_typed_address (address_buffer + embedded_offset, type);
507
508       fprintf_filtered (stream, "@");
509       gdb_puts (paddress (gdbarch, address), stream);
510     }
511   /* Else: we have a non-addressable value, such as a DW_AT_const_value.  */
512 }
513
514 /* If VAL is addressable, return the value contents buffer of a value that
515    represents a pointer to VAL.  Otherwise return NULL.  */
516
517 static const gdb_byte *
518 get_value_addr_contents (struct value *deref_val)
519 {
520   gdb_assert (deref_val != NULL);
521
522   if (value_lval_const (deref_val) == lval_memory)
523     return value_contents_for_printing_const (value_addr (deref_val)).data ();
524   else
525     {
526       /* We have a non-addressable value, such as a DW_AT_const_value.  */
527       return NULL;
528     }
529 }
530
531 /* generic_val_print helper for TYPE_CODE_{RVALUE_,}REF.  */
532
533 static void
534 generic_val_print_ref (struct type *type,
535                        int embedded_offset, struct ui_file *stream, int recurse,
536                        struct value *original_value,
537                        const struct value_print_options *options)
538 {
539   struct type *elttype = check_typedef (TYPE_TARGET_TYPE (type));
540   struct value *deref_val = NULL;
541   const int value_is_synthetic
542     = value_bits_synthetic_pointer (original_value,
543                                     TARGET_CHAR_BIT * embedded_offset,
544                                     TARGET_CHAR_BIT * TYPE_LENGTH (type));
545   const int must_coerce_ref = ((options->addressprint && value_is_synthetic)
546                                || options->deref_ref);
547   const int type_is_defined = elttype->code () != TYPE_CODE_UNDEF;
548   const gdb_byte *valaddr = value_contents_for_printing (original_value).data ();
549
550   if (must_coerce_ref && type_is_defined)
551     {
552       deref_val = coerce_ref_if_computed (original_value);
553
554       if (deref_val != NULL)
555         {
556           /* More complicated computed references are not supported.  */
557           gdb_assert (embedded_offset == 0);
558         }
559       else
560         deref_val = value_at (TYPE_TARGET_TYPE (type),
561                               unpack_pointer (type, valaddr + embedded_offset));
562     }
563   /* Else, original_value isn't a synthetic reference or we don't have to print
564      the reference's contents.
565
566      Notice that for references to TYPE_CODE_STRUCT, 'set print object on' will
567      cause original_value to be a not_lval instead of an lval_computed,
568      which will make value_bits_synthetic_pointer return false.
569      This happens because if options->objectprint is true, c_value_print will
570      overwrite original_value's contents with the result of coercing
571      the reference through value_addr, and then set its type back to
572      TYPE_CODE_REF.  In that case we don't have to coerce the reference again;
573      we can simply treat it as non-synthetic and move on.  */
574
575   if (options->addressprint)
576     {
577       const gdb_byte *address = (value_is_synthetic && type_is_defined
578                                  ? get_value_addr_contents (deref_val)
579                                  : valaddr);
580
581       print_ref_address (type, address, embedded_offset, stream);
582
583       if (options->deref_ref)
584         gdb_puts (": ", stream);
585     }
586
587   if (options->deref_ref)
588     {
589       if (type_is_defined)
590         common_val_print (deref_val, stream, recurse, options,
591                           current_language);
592       else
593         gdb_puts ("???", stream);
594     }
595 }
596
597 /* Helper function for generic_val_print_enum.
598    This is also used to print enums in TYPE_CODE_FLAGS values.  */
599
600 static void
601 generic_val_print_enum_1 (struct type *type, LONGEST val,
602                           struct ui_file *stream)
603 {
604   unsigned int i;
605   unsigned int len;
606
607   len = type->num_fields ();
608   for (i = 0; i < len; i++)
609     {
610       QUIT;
611       if (val == type->field (i).loc_enumval ())
612         {
613           break;
614         }
615     }
616   if (i < len)
617     {
618       fputs_styled (type->field (i).name (), variable_name_style.style (),
619                     stream);
620     }
621   else if (type->is_flag_enum ())
622     {
623       int first = 1;
624
625       /* We have a "flag" enum, so we try to decompose it into pieces as
626          appropriate.  The enum may have multiple enumerators representing
627          the same bit, in which case we choose to only print the first one
628          we find.  */
629       for (i = 0; i < len; ++i)
630         {
631           QUIT;
632
633           ULONGEST enumval = type->field (i).loc_enumval ();
634           int nbits = count_one_bits_ll (enumval);
635
636           gdb_assert (nbits == 0 || nbits == 1);
637
638           if ((val & enumval) != 0)
639             {
640               if (first)
641                 {
642                   gdb_puts ("(", stream);
643                   first = 0;
644                 }
645               else
646                 gdb_puts (" | ", stream);
647
648               val &= ~type->field (i).loc_enumval ();
649               fputs_styled (type->field (i).name (),
650                             variable_name_style.style (), stream);
651             }
652         }
653
654       if (val != 0)
655         {
656           /* There are leftover bits, print them.  */
657           if (first)
658             gdb_puts ("(", stream);
659           else
660             gdb_puts (" | ", stream);
661
662           gdb_puts ("unknown: 0x", stream);
663           print_longest (stream, 'x', 0, val);
664           gdb_puts (")", stream);
665         }
666       else if (first)
667         {
668           /* Nothing has been printed and the value is 0, the enum value must
669              have been 0.  */
670           gdb_puts ("0", stream);
671         }
672       else
673         {
674           /* Something has been printed, close the parenthesis.  */
675           gdb_puts (")", stream);
676         }
677     }
678   else
679     print_longest (stream, 'd', 0, val);
680 }
681
682 /* generic_val_print helper for TYPE_CODE_ENUM.  */
683
684 static void
685 generic_val_print_enum (struct type *type,
686                         int embedded_offset, struct ui_file *stream,
687                         struct value *original_value,
688                         const struct value_print_options *options)
689 {
690   LONGEST val;
691   struct gdbarch *gdbarch = type->arch ();
692   int unit_size = gdbarch_addressable_memory_unit_size (gdbarch);
693
694   gdb_assert (!options->format);
695
696   const gdb_byte *valaddr = value_contents_for_printing (original_value).data ();
697
698   val = unpack_long (type, valaddr + embedded_offset * unit_size);
699
700   generic_val_print_enum_1 (type, val, stream);
701 }
702
703 /* generic_val_print helper for TYPE_CODE_FUNC and TYPE_CODE_METHOD.  */
704
705 static void
706 generic_val_print_func (struct type *type,
707                         int embedded_offset, CORE_ADDR address,
708                         struct ui_file *stream,
709                         struct value *original_value,
710                         const struct value_print_options *options)
711 {
712   struct gdbarch *gdbarch = type->arch ();
713
714   gdb_assert (!options->format);
715
716   /* FIXME, we should consider, at least for ANSI C language,
717      eliminating the distinction made between FUNCs and POINTERs to
718      FUNCs.  */
719   fprintf_filtered (stream, "{");
720   type_print (type, "", stream, -1);
721   fprintf_filtered (stream, "} ");
722   /* Try to print what function it points to, and its address.  */
723   print_address_demangle (options, gdbarch, address, stream, demangle);
724 }
725
726 /* generic_value_print helper for TYPE_CODE_BOOL.  */
727
728 static void
729 generic_value_print_bool
730   (struct value *value, struct ui_file *stream,
731    const struct value_print_options *options,
732    const struct generic_val_print_decorations *decorations)
733 {
734   if (options->format || options->output_format)
735     {
736       struct value_print_options opts = *options;
737       opts.format = (options->format ? options->format
738                      : options->output_format);
739       value_print_scalar_formatted (value, &opts, 0, stream);
740     }
741   else
742     {
743       const gdb_byte *valaddr = value_contents_for_printing (value).data ();
744       struct type *type = check_typedef (value_type (value));
745       LONGEST val = unpack_long (type, valaddr);
746       if (val == 0)
747         gdb_puts (decorations->false_name, stream);
748       else if (val == 1)
749         gdb_puts (decorations->true_name, stream);
750       else
751         print_longest (stream, 'd', 0, val);
752     }
753 }
754
755 /* generic_value_print helper for TYPE_CODE_INT.  */
756
757 static void
758 generic_value_print_int (struct value *val, struct ui_file *stream,
759                          const struct value_print_options *options)
760 {
761   struct value_print_options opts = *options;
762
763   opts.format = (options->format ? options->format
764                  : options->output_format);
765   value_print_scalar_formatted (val, &opts, 0, stream);
766 }
767
768 /* generic_value_print helper for TYPE_CODE_CHAR.  */
769
770 static void
771 generic_value_print_char (struct value *value, struct ui_file *stream,
772                           const struct value_print_options *options)
773 {
774   if (options->format || options->output_format)
775     {
776       struct value_print_options opts = *options;
777
778       opts.format = (options->format ? options->format
779                      : options->output_format);
780       value_print_scalar_formatted (value, &opts, 0, stream);
781     }
782   else
783     {
784       struct type *unresolved_type = value_type (value);
785       struct type *type = check_typedef (unresolved_type);
786       const gdb_byte *valaddr = value_contents_for_printing (value).data ();
787
788       LONGEST val = unpack_long (type, valaddr);
789       if (type->is_unsigned ())
790         fprintf_filtered (stream, "%u", (unsigned int) val);
791       else
792         fprintf_filtered (stream, "%d", (int) val);
793       gdb_puts (" ", stream);
794       current_language->printchar (val, unresolved_type, stream);
795     }
796 }
797
798 /* generic_val_print helper for TYPE_CODE_FLT and TYPE_CODE_DECFLOAT.  */
799
800 static void
801 generic_val_print_float (struct type *type, struct ui_file *stream,
802                          struct value *original_value,
803                          const struct value_print_options *options)
804 {
805   gdb_assert (!options->format);
806
807   const gdb_byte *valaddr = value_contents_for_printing (original_value).data ();
808
809   print_floating (valaddr, type, stream);
810 }
811
812 /* generic_val_print helper for TYPE_CODE_FIXED_POINT.  */
813
814 static void
815 generic_val_print_fixed_point (struct value *val, struct ui_file *stream,
816                                const struct value_print_options *options)
817 {
818   if (options->format)
819     value_print_scalar_formatted (val, options, 0, stream);
820   else
821     {
822       struct type *type = value_type (val);
823
824       const gdb_byte *valaddr = value_contents_for_printing (val).data ();
825       gdb_mpf f;
826
827       f.read_fixed_point (gdb::make_array_view (valaddr, TYPE_LENGTH (type)),
828                           type_byte_order (type), type->is_unsigned (),
829                           type->fixed_point_scaling_factor ());
830
831       const char *fmt = TYPE_LENGTH (type) < 4 ? "%.11Fg" : "%.17Fg";
832       std::string str = gmp_string_printf (fmt, f.val);
833       fprintf_filtered (stream, "%s", str.c_str ());
834     }
835 }
836
837 /* generic_value_print helper for TYPE_CODE_COMPLEX.  */
838
839 static void
840 generic_value_print_complex (struct value *val, struct ui_file *stream,
841                              const struct value_print_options *options,
842                              const struct generic_val_print_decorations
843                                *decorations)
844 {
845   fprintf_filtered (stream, "%s", decorations->complex_prefix);
846
847   struct value *real_part = value_real_part (val);
848   value_print_scalar_formatted (real_part, options, 0, stream);
849   fprintf_filtered (stream, "%s", decorations->complex_infix);
850
851   struct value *imag_part = value_imaginary_part (val);
852   value_print_scalar_formatted (imag_part, options, 0, stream);
853   fprintf_filtered (stream, "%s", decorations->complex_suffix);
854 }
855
856 /* generic_value_print helper for TYPE_CODE_MEMBERPTR.  */
857
858 static void
859 generic_value_print_memberptr
860   (struct value *val, struct ui_file *stream,
861    int recurse,
862    const struct value_print_options *options,
863    const struct generic_val_print_decorations *decorations)
864 {
865   if (!options->format)
866     {
867       /* Member pointers are essentially specific to C++, and so if we
868          encounter one, we should print it according to C++ rules.  */
869       struct type *type = check_typedef (value_type (val));
870       const gdb_byte *valaddr = value_contents_for_printing (val).data ();
871       cp_print_class_member (valaddr, type, stream, "&");
872     }
873   else
874     generic_value_print (val, stream, recurse, options, decorations);
875 }
876
877 /* See valprint.h.  */
878
879 void
880 generic_value_print (struct value *val, struct ui_file *stream, int recurse,
881                      const struct value_print_options *options,
882                      const struct generic_val_print_decorations *decorations)
883 {
884   struct type *type = value_type (val);
885
886   type = check_typedef (type);
887
888   if (is_fixed_point_type (type))
889     type = type->fixed_point_type_base_type ();
890
891   /* Widen a subrange to its target type, then use that type's
892      printer.  */
893   while (type->code () == TYPE_CODE_RANGE)
894     {
895       type = check_typedef (TYPE_TARGET_TYPE (type));
896       val = value_cast (type, val);
897     }
898
899   switch (type->code ())
900     {
901     case TYPE_CODE_ARRAY:
902       generic_val_print_array (val, stream, recurse, options, decorations);
903       break;
904
905     case TYPE_CODE_MEMBERPTR:
906       generic_value_print_memberptr (val, stream, recurse, options,
907                                      decorations);
908       break;
909
910     case TYPE_CODE_PTR:
911       generic_value_print_ptr (val, stream, options);
912       break;
913
914     case TYPE_CODE_REF:
915     case TYPE_CODE_RVALUE_REF:
916       generic_val_print_ref (type, 0, stream, recurse,
917                              val, options);
918       break;
919
920     case TYPE_CODE_ENUM:
921       if (options->format)
922         value_print_scalar_formatted (val, options, 0, stream);
923       else
924         generic_val_print_enum (type, 0, stream, val, options);
925       break;
926
927     case TYPE_CODE_FLAGS:
928       if (options->format)
929         value_print_scalar_formatted (val, options, 0, stream);
930       else
931         val_print_type_code_flags (type, val, 0, stream);
932       break;
933
934     case TYPE_CODE_FUNC:
935     case TYPE_CODE_METHOD:
936       if (options->format)
937         value_print_scalar_formatted (val, options, 0, stream);
938       else
939         generic_val_print_func (type, 0, value_address (val), stream,
940                                 val, options);
941       break;
942
943     case TYPE_CODE_BOOL:
944       generic_value_print_bool (val, stream, options, decorations);
945       break;
946
947     case TYPE_CODE_INT:
948       generic_value_print_int (val, stream, options);
949       break;
950
951     case TYPE_CODE_CHAR:
952       generic_value_print_char (val, stream, options);
953       break;
954
955     case TYPE_CODE_FLT:
956     case TYPE_CODE_DECFLOAT:
957       if (options->format)
958         value_print_scalar_formatted (val, options, 0, stream);
959       else
960         generic_val_print_float (type, stream, val, options);
961       break;
962
963     case TYPE_CODE_FIXED_POINT:
964       generic_val_print_fixed_point (val, stream, options);
965       break;
966
967     case TYPE_CODE_VOID:
968       gdb_puts (decorations->void_name, stream);
969       break;
970
971     case TYPE_CODE_ERROR:
972       fprintf_filtered (stream, "%s", TYPE_ERROR_NAME (type));
973       break;
974
975     case TYPE_CODE_UNDEF:
976       /* This happens (without TYPE_STUB set) on systems which don't use
977          dbx xrefs (NO_DBX_XREFS in gcc) if a file has a "struct foo *bar"
978          and no complete type for struct foo in that file.  */
979       fprintf_styled (stream, metadata_style.style (), _("<incomplete type>"));
980       break;
981
982     case TYPE_CODE_COMPLEX:
983       generic_value_print_complex (val, stream, options, decorations);
984       break;
985
986     case TYPE_CODE_METHODPTR:
987       cplus_print_method_ptr (value_contents_for_printing (val).data (), type,
988                               stream);
989       break;
990
991     case TYPE_CODE_UNION:
992     case TYPE_CODE_STRUCT:
993     default:
994       error (_("Unhandled type code %d in symbol table."),
995              type->code ());
996     }
997 }
998
999 /* Print using the given LANGUAGE the value VAL onto stream STREAM according
1000    to OPTIONS.
1001
1002    This is a preferable interface to val_print, above, because it uses
1003    GDB's value mechanism.  */
1004
1005 void
1006 common_val_print (struct value *value, struct ui_file *stream, int recurse,
1007                   const struct value_print_options *options,
1008                   const struct language_defn *language)
1009 {
1010   if (language->la_language == language_ada)
1011     /* The value might have a dynamic type, which would cause trouble
1012        below when trying to extract the value contents (since the value
1013        size is determined from the type size which is unknown).  So
1014        get a fixed representation of our value.  */
1015     value = ada_to_fixed_value (value);
1016
1017   if (value_lazy (value))
1018     value_fetch_lazy (value);
1019
1020   struct value_print_options local_opts = *options;
1021   struct type *type = value_type (value);
1022   struct type *real_type = check_typedef (type);
1023
1024   if (local_opts.prettyformat == Val_prettyformat_default)
1025     local_opts.prettyformat = (local_opts.prettyformat_structs
1026                                ? Val_prettyformat : Val_no_prettyformat);
1027
1028   QUIT;
1029
1030   /* Ensure that the type is complete and not just a stub.  If the type is
1031      only a stub and we can't find and substitute its complete type, then
1032      print appropriate string and return.  */
1033
1034   if (real_type->is_stub ())
1035     {
1036       fprintf_styled (stream, metadata_style.style (), _("<incomplete type>"));
1037       return;
1038     }
1039
1040   if (!valprint_check_validity (stream, real_type, 0, value))
1041     return;
1042
1043   if (!options->raw)
1044     {
1045       if (apply_ext_lang_val_pretty_printer (value, stream, recurse, options,
1046                                              language))
1047         return;
1048     }
1049
1050   /* Handle summary mode.  If the value is a scalar, print it;
1051      otherwise, print an ellipsis.  */
1052   if (options->summary && !val_print_scalar_type_p (type))
1053     {
1054       fprintf_filtered (stream, "...");
1055       return;
1056     }
1057
1058   /* If this value is too deep then don't print it.  */
1059   if (!val_print_scalar_or_string_type_p (type, language)
1060       && val_print_check_max_depth (stream, recurse, options, language))
1061     return;
1062
1063   try
1064     {
1065       language->value_print_inner (value, stream, recurse, &local_opts);
1066     }
1067   catch (const gdb_exception_error &except)
1068     {
1069       fprintf_styled (stream, metadata_style.style (),
1070                       _("<error reading variable: %s>"), except.what ());
1071     }
1072 }
1073
1074 /* See valprint.h.  */
1075
1076 bool
1077 val_print_check_max_depth (struct ui_file *stream, int recurse,
1078                            const struct value_print_options *options,
1079                            const struct language_defn *language)
1080 {
1081   if (options->max_depth > -1 && recurse >= options->max_depth)
1082     {
1083       gdb_assert (language->struct_too_deep_ellipsis () != NULL);
1084       gdb_puts (language->struct_too_deep_ellipsis (), stream);
1085       return true;
1086     }
1087
1088   return false;
1089 }
1090
1091 /* Check whether the value VAL is printable.  Return 1 if it is;
1092    return 0 and print an appropriate error message to STREAM according to
1093    OPTIONS if it is not.  */
1094
1095 static int
1096 value_check_printable (struct value *val, struct ui_file *stream,
1097                        const struct value_print_options *options)
1098 {
1099   if (val == 0)
1100     {
1101       fprintf_styled (stream, metadata_style.style (),
1102                       _("<address of value unknown>"));
1103       return 0;
1104     }
1105
1106   if (value_entirely_optimized_out (val))
1107     {
1108       if (options->summary && !val_print_scalar_type_p (value_type (val)))
1109         fprintf_filtered (stream, "...");
1110       else
1111         val_print_optimized_out (val, stream);
1112       return 0;
1113     }
1114
1115   if (value_entirely_unavailable (val))
1116     {
1117       if (options->summary && !val_print_scalar_type_p (value_type (val)))
1118         fprintf_filtered (stream, "...");
1119       else
1120         val_print_unavailable (stream);
1121       return 0;
1122     }
1123
1124   if (value_type (val)->code () == TYPE_CODE_INTERNAL_FUNCTION)
1125     {
1126       fprintf_styled (stream, metadata_style.style (),
1127                       _("<internal function %s>"),
1128                       value_internal_function_name (val));
1129       return 0;
1130     }
1131
1132   if (type_not_associated (value_type (val)))
1133     {
1134       val_print_not_associated (stream);
1135       return 0;
1136     }
1137
1138   if (type_not_allocated (value_type (val)))
1139     {
1140       val_print_not_allocated (stream);
1141       return 0;
1142     }
1143
1144   return 1;
1145 }
1146
1147 /* See valprint.h.  */
1148
1149 void
1150 common_val_print_checked (struct value *val, struct ui_file *stream,
1151                           int recurse,
1152                           const struct value_print_options *options,
1153                           const struct language_defn *language)
1154 {
1155   if (!value_check_printable (val, stream, options))
1156     return;
1157   common_val_print (val, stream, recurse, options, language);
1158 }
1159
1160 /* Print on stream STREAM the value VAL according to OPTIONS.  The value
1161    is printed using the current_language syntax.  */
1162
1163 void
1164 value_print (struct value *val, struct ui_file *stream,
1165              const struct value_print_options *options)
1166 {
1167   scoped_value_mark free_values;
1168
1169   if (!value_check_printable (val, stream, options))
1170     return;
1171
1172   if (!options->raw)
1173     {
1174       int r
1175         = apply_ext_lang_val_pretty_printer (val, stream, 0, options,
1176                                              current_language);
1177
1178       if (r)
1179         return;
1180     }
1181
1182   current_language->value_print (val, stream, options);
1183 }
1184
1185 static void
1186 val_print_type_code_flags (struct type *type, struct value *original_value,
1187                            int embedded_offset, struct ui_file *stream)
1188 {
1189   const gdb_byte *valaddr = (value_contents_for_printing (original_value).data ()
1190                              + embedded_offset);
1191   ULONGEST val = unpack_long (type, valaddr);
1192   int field, nfields = type->num_fields ();
1193   struct gdbarch *gdbarch = type->arch ();
1194   struct type *bool_type = builtin_type (gdbarch)->builtin_bool;
1195
1196   gdb_puts ("[", stream);
1197   for (field = 0; field < nfields; field++)
1198     {
1199       if (type->field (field).name ()[0] != '\0')
1200         {
1201           struct type *field_type = type->field (field).type ();
1202
1203           if (field_type == bool_type
1204               /* We require boolean types here to be one bit wide.  This is a
1205                  problematic place to notify the user of an internal error
1206                  though.  Instead just fall through and print the field as an
1207                  int.  */
1208               && TYPE_FIELD_BITSIZE (type, field) == 1)
1209             {
1210               if (val & ((ULONGEST)1 << type->field (field).loc_bitpos ()))
1211                 fprintf_filtered
1212                   (stream, " %ps",
1213                    styled_string (variable_name_style.style (),
1214                                   type->field (field).name ()));
1215             }
1216           else
1217             {
1218               unsigned field_len = TYPE_FIELD_BITSIZE (type, field);
1219               ULONGEST field_val = val >> type->field (field).loc_bitpos ();
1220
1221               if (field_len < sizeof (ULONGEST) * TARGET_CHAR_BIT)
1222                 field_val &= ((ULONGEST) 1 << field_len) - 1;
1223               fprintf_filtered (stream, " %ps=",
1224                                 styled_string (variable_name_style.style (),
1225                                                type->field (field).name ()));
1226               if (field_type->code () == TYPE_CODE_ENUM)
1227                 generic_val_print_enum_1 (field_type, field_val, stream);
1228               else
1229                 print_longest (stream, 'd', 0, field_val);
1230             }
1231         }
1232     }
1233   gdb_puts (" ]", stream);
1234 }
1235
1236 /* See valprint.h.  */
1237
1238 void
1239 value_print_scalar_formatted (struct value *val,
1240                               const struct value_print_options *options,
1241                               int size,
1242                               struct ui_file *stream)
1243 {
1244   struct type *type = check_typedef (value_type (val));
1245
1246   gdb_assert (val != NULL);
1247
1248   /* If we get here with a string format, try again without it.  Go
1249      all the way back to the language printers, which may call us
1250      again.  */
1251   if (options->format == 's')
1252     {
1253       struct value_print_options opts = *options;
1254       opts.format = 0;
1255       opts.deref_ref = 0;
1256       common_val_print (val, stream, 0, &opts, current_language);
1257       return;
1258     }
1259
1260   /* value_contents_for_printing fetches all VAL's contents.  They are
1261      needed to check whether VAL is optimized-out or unavailable
1262      below.  */
1263   const gdb_byte *valaddr = value_contents_for_printing (val).data ();
1264
1265   /* A scalar object that does not have all bits available can't be
1266      printed, because all bits contribute to its representation.  */
1267   if (value_bits_any_optimized_out (val, 0,
1268                                     TARGET_CHAR_BIT * TYPE_LENGTH (type)))
1269     val_print_optimized_out (val, stream);
1270   else if (!value_bytes_available (val, 0, TYPE_LENGTH (type)))
1271     val_print_unavailable (stream);
1272   else
1273     print_scalar_formatted (valaddr, type, options, size, stream);
1274 }
1275
1276 /* Print a number according to FORMAT which is one of d,u,x,o,b,h,w,g.
1277    The raison d'etre of this function is to consolidate printing of 
1278    LONG_LONG's into this one function.  The format chars b,h,w,g are 
1279    from print_scalar_formatted().  Numbers are printed using C
1280    format.
1281
1282    USE_C_FORMAT means to use C format in all cases.  Without it, 
1283    'o' and 'x' format do not include the standard C radix prefix
1284    (leading 0 or 0x). 
1285    
1286    Hilfinger/2004-09-09: USE_C_FORMAT was originally called USE_LOCAL
1287    and was intended to request formatting according to the current
1288    language and would be used for most integers that GDB prints.  The
1289    exceptional cases were things like protocols where the format of
1290    the integer is a protocol thing, not a user-visible thing).  The
1291    parameter remains to preserve the information of what things might
1292    be printed with language-specific format, should we ever resurrect
1293    that capability.  */
1294
1295 void
1296 print_longest (struct ui_file *stream, int format, int use_c_format,
1297                LONGEST val_long)
1298 {
1299   const char *val;
1300
1301   switch (format)
1302     {
1303     case 'd':
1304       val = int_string (val_long, 10, 1, 0, 1); break;
1305     case 'u':
1306       val = int_string (val_long, 10, 0, 0, 1); break;
1307     case 'x':
1308       val = int_string (val_long, 16, 0, 0, use_c_format); break;
1309     case 'b':
1310       val = int_string (val_long, 16, 0, 2, 1); break;
1311     case 'h':
1312       val = int_string (val_long, 16, 0, 4, 1); break;
1313     case 'w':
1314       val = int_string (val_long, 16, 0, 8, 1); break;
1315     case 'g':
1316       val = int_string (val_long, 16, 0, 16, 1); break;
1317       break;
1318     case 'o':
1319       val = int_string (val_long, 8, 0, 0, use_c_format); break;
1320     default:
1321       internal_error (__FILE__, __LINE__,
1322                       _("failed internal consistency check"));
1323     } 
1324   gdb_puts (val, stream);
1325 }
1326
1327 /* This used to be a macro, but I don't think it is called often enough
1328    to merit such treatment.  */
1329 /* Convert a LONGEST to an int.  This is used in contexts (e.g. number of
1330    arguments to a function, number in a value history, register number, etc.)
1331    where the value must not be larger than can fit in an int.  */
1332
1333 int
1334 longest_to_int (LONGEST arg)
1335 {
1336   /* Let the compiler do the work.  */
1337   int rtnval = (int) arg;
1338
1339   /* Check for overflows or underflows.  */
1340   if (sizeof (LONGEST) > sizeof (int))
1341     {
1342       if (rtnval != arg)
1343         {
1344           error (_("Value out of range."));
1345         }
1346     }
1347   return (rtnval);
1348 }
1349
1350 /* Print a floating point value of floating-point type TYPE,
1351    pointed to in GDB by VALADDR, on STREAM.  */
1352
1353 void
1354 print_floating (const gdb_byte *valaddr, struct type *type,
1355                 struct ui_file *stream)
1356 {
1357   std::string str = target_float_to_string (valaddr, type);
1358   gdb_puts (str.c_str (), stream);
1359 }
1360
1361 void
1362 print_binary_chars (struct ui_file *stream, const gdb_byte *valaddr,
1363                     unsigned len, enum bfd_endian byte_order, bool zero_pad)
1364 {
1365   const gdb_byte *p;
1366   unsigned int i;
1367   int b;
1368   bool seen_a_one = false;
1369
1370   /* Declared "int" so it will be signed.
1371      This ensures that right shift will shift in zeros.  */
1372
1373   const int mask = 0x080;
1374
1375   if (byte_order == BFD_ENDIAN_BIG)
1376     {
1377       for (p = valaddr;
1378            p < valaddr + len;
1379            p++)
1380         {
1381           /* Every byte has 8 binary characters; peel off
1382              and print from the MSB end.  */
1383
1384           for (i = 0; i < (HOST_CHAR_BIT * sizeof (*p)); i++)
1385             {
1386               if (*p & (mask >> i))
1387                 b = '1';
1388               else
1389                 b = '0';
1390
1391               if (zero_pad || seen_a_one || b == '1')
1392                 fputc_filtered (b, stream);
1393               if (b == '1')
1394                 seen_a_one = true;
1395             }
1396         }
1397     }
1398   else
1399     {
1400       for (p = valaddr + len - 1;
1401            p >= valaddr;
1402            p--)
1403         {
1404           for (i = 0; i < (HOST_CHAR_BIT * sizeof (*p)); i++)
1405             {
1406               if (*p & (mask >> i))
1407                 b = '1';
1408               else
1409                 b = '0';
1410
1411               if (zero_pad || seen_a_one || b == '1')
1412                 fputc_filtered (b, stream);
1413               if (b == '1')
1414                 seen_a_one = true;
1415             }
1416         }
1417     }
1418
1419   /* When not zero-padding, ensure that something is printed when the
1420      input is 0.  */
1421   if (!zero_pad && !seen_a_one)
1422     fputc_filtered ('0', stream);
1423 }
1424
1425 /* A helper for print_octal_chars that emits a single octal digit,
1426    optionally suppressing it if is zero and updating SEEN_A_ONE.  */
1427
1428 static void
1429 emit_octal_digit (struct ui_file *stream, bool *seen_a_one, int digit)
1430 {
1431   if (*seen_a_one || digit != 0)
1432     fprintf_filtered (stream, "%o", digit);
1433   if (digit != 0)
1434     *seen_a_one = true;
1435 }
1436
1437 /* VALADDR points to an integer of LEN bytes.
1438    Print it in octal on stream or format it in buf.  */
1439
1440 void
1441 print_octal_chars (struct ui_file *stream, const gdb_byte *valaddr,
1442                    unsigned len, enum bfd_endian byte_order)
1443 {
1444   const gdb_byte *p;
1445   unsigned char octa1, octa2, octa3, carry;
1446   int cycle;
1447
1448   /* Octal is 3 bits, which doesn't fit.  Yuk.  So we have to track
1449    * the extra bits, which cycle every three bytes:
1450    *
1451    * Byte side:       0            1             2          3
1452    *                         |             |            |            |
1453    * bit number   123 456 78 | 9 012 345 6 | 78 901 234 | 567 890 12 |
1454    *
1455    * Octal side:   0   1   carry  3   4  carry ...
1456    *
1457    * Cycle number:    0             1            2
1458    *
1459    * But of course we are printing from the high side, so we have to
1460    * figure out where in the cycle we are so that we end up with no
1461    * left over bits at the end.
1462    */
1463 #define BITS_IN_OCTAL 3
1464 #define HIGH_ZERO     0340
1465 #define LOW_ZERO      0034
1466 #define CARRY_ZERO    0003
1467   static_assert (HIGH_ZERO + LOW_ZERO + CARRY_ZERO == 0xff,
1468                  "cycle zero constants are wrong");
1469 #define HIGH_ONE      0200
1470 #define MID_ONE       0160
1471 #define LOW_ONE       0016
1472 #define CARRY_ONE     0001
1473   static_assert (HIGH_ONE + MID_ONE + LOW_ONE + CARRY_ONE == 0xff,
1474                  "cycle one constants are wrong");
1475 #define HIGH_TWO      0300
1476 #define MID_TWO       0070
1477 #define LOW_TWO       0007
1478   static_assert (HIGH_TWO + MID_TWO + LOW_TWO == 0xff,
1479                  "cycle two constants are wrong");
1480
1481   /* For 32 we start in cycle 2, with two bits and one bit carry;
1482      for 64 in cycle in cycle 1, with one bit and a two bit carry.  */
1483
1484   cycle = (len * HOST_CHAR_BIT) % BITS_IN_OCTAL;
1485   carry = 0;
1486
1487   gdb_puts ("0", stream);
1488   bool seen_a_one = false;
1489   if (byte_order == BFD_ENDIAN_BIG)
1490     {
1491       for (p = valaddr;
1492            p < valaddr + len;
1493            p++)
1494         {
1495           switch (cycle)
1496             {
1497             case 0:
1498               /* No carry in, carry out two bits.  */
1499
1500               octa1 = (HIGH_ZERO & *p) >> 5;
1501               octa2 = (LOW_ZERO & *p) >> 2;
1502               carry = (CARRY_ZERO & *p);
1503               emit_octal_digit (stream, &seen_a_one, octa1);
1504               emit_octal_digit (stream, &seen_a_one, octa2);
1505               break;
1506
1507             case 1:
1508               /* Carry in two bits, carry out one bit.  */
1509
1510               octa1 = (carry << 1) | ((HIGH_ONE & *p) >> 7);
1511               octa2 = (MID_ONE & *p) >> 4;
1512               octa3 = (LOW_ONE & *p) >> 1;
1513               carry = (CARRY_ONE & *p);
1514               emit_octal_digit (stream, &seen_a_one, octa1);
1515               emit_octal_digit (stream, &seen_a_one, octa2);
1516               emit_octal_digit (stream, &seen_a_one, octa3);
1517               break;
1518
1519             case 2:
1520               /* Carry in one bit, no carry out.  */
1521
1522               octa1 = (carry << 2) | ((HIGH_TWO & *p) >> 6);
1523               octa2 = (MID_TWO & *p) >> 3;
1524               octa3 = (LOW_TWO & *p);
1525               carry = 0;
1526               emit_octal_digit (stream, &seen_a_one, octa1);
1527               emit_octal_digit (stream, &seen_a_one, octa2);
1528               emit_octal_digit (stream, &seen_a_one, octa3);
1529               break;
1530
1531             default:
1532               error (_("Internal error in octal conversion;"));
1533             }
1534
1535           cycle++;
1536           cycle = cycle % BITS_IN_OCTAL;
1537         }
1538     }
1539   else
1540     {
1541       for (p = valaddr + len - 1;
1542            p >= valaddr;
1543            p--)
1544         {
1545           switch (cycle)
1546             {
1547             case 0:
1548               /* Carry out, no carry in */
1549
1550               octa1 = (HIGH_ZERO & *p) >> 5;
1551               octa2 = (LOW_ZERO & *p) >> 2;
1552               carry = (CARRY_ZERO & *p);
1553               emit_octal_digit (stream, &seen_a_one, octa1);
1554               emit_octal_digit (stream, &seen_a_one, octa2);
1555               break;
1556
1557             case 1:
1558               /* Carry in, carry out */
1559
1560               octa1 = (carry << 1) | ((HIGH_ONE & *p) >> 7);
1561               octa2 = (MID_ONE & *p) >> 4;
1562               octa3 = (LOW_ONE & *p) >> 1;
1563               carry = (CARRY_ONE & *p);
1564               emit_octal_digit (stream, &seen_a_one, octa1);
1565               emit_octal_digit (stream, &seen_a_one, octa2);
1566               emit_octal_digit (stream, &seen_a_one, octa3);
1567               break;
1568
1569             case 2:
1570               /* Carry in, no carry out */
1571
1572               octa1 = (carry << 2) | ((HIGH_TWO & *p) >> 6);
1573               octa2 = (MID_TWO & *p) >> 3;
1574               octa3 = (LOW_TWO & *p);
1575               carry = 0;
1576               emit_octal_digit (stream, &seen_a_one, octa1);
1577               emit_octal_digit (stream, &seen_a_one, octa2);
1578               emit_octal_digit (stream, &seen_a_one, octa3);
1579               break;
1580
1581             default:
1582               error (_("Internal error in octal conversion;"));
1583             }
1584
1585           cycle++;
1586           cycle = cycle % BITS_IN_OCTAL;
1587         }
1588     }
1589
1590 }
1591
1592 /* Possibly negate the integer represented by BYTES.  It contains LEN
1593    bytes in the specified byte order.  If the integer is negative,
1594    copy it into OUT_VEC, negate it, and return true.  Otherwise, do
1595    nothing and return false.  */
1596
1597 static bool
1598 maybe_negate_by_bytes (const gdb_byte *bytes, unsigned len,
1599                        enum bfd_endian byte_order,
1600                        gdb::byte_vector *out_vec)
1601 {
1602   gdb_byte sign_byte;
1603   gdb_assert (len > 0);
1604   if (byte_order == BFD_ENDIAN_BIG)
1605     sign_byte = bytes[0];
1606   else
1607     sign_byte = bytes[len - 1];
1608   if ((sign_byte & 0x80) == 0)
1609     return false;
1610
1611   out_vec->resize (len);
1612
1613   /* Compute -x == 1 + ~x.  */
1614   if (byte_order == BFD_ENDIAN_LITTLE)
1615     {
1616       unsigned carry = 1;
1617       for (unsigned i = 0; i < len; ++i)
1618         {
1619           unsigned tem = (0xff & ~bytes[i]) + carry;
1620           (*out_vec)[i] = tem & 0xff;
1621           carry = tem / 256;
1622         }
1623     }
1624   else
1625     {
1626       unsigned carry = 1;
1627       for (unsigned i = len; i > 0; --i)
1628         {
1629           unsigned tem = (0xff & ~bytes[i - 1]) + carry;
1630           (*out_vec)[i - 1] = tem & 0xff;
1631           carry = tem / 256;
1632         }
1633     }
1634
1635   return true;
1636 }
1637
1638 /* VALADDR points to an integer of LEN bytes.
1639    Print it in decimal on stream or format it in buf.  */
1640
1641 void
1642 print_decimal_chars (struct ui_file *stream, const gdb_byte *valaddr,
1643                      unsigned len, bool is_signed,
1644                      enum bfd_endian byte_order)
1645 {
1646 #define TEN             10
1647 #define CARRY_OUT(  x ) ((x) / TEN)     /* extend char to int */
1648 #define CARRY_LEFT( x ) ((x) % TEN)
1649 #define SHIFT( x )      ((x) << 4)
1650 #define LOW_NIBBLE(  x ) ( (x) & 0x00F)
1651 #define HIGH_NIBBLE( x ) (((x) & 0x0F0) >> 4)
1652
1653   const gdb_byte *p;
1654   int carry;
1655   int decimal_len;
1656   int i, j, decimal_digits;
1657   int dummy;
1658   int flip;
1659
1660   gdb::byte_vector negated_bytes;
1661   if (is_signed
1662       && maybe_negate_by_bytes (valaddr, len, byte_order, &negated_bytes))
1663     {
1664       gdb_puts ("-", stream);
1665       valaddr = negated_bytes.data ();
1666     }
1667
1668   /* Base-ten number is less than twice as many digits
1669      as the base 16 number, which is 2 digits per byte.  */
1670
1671   decimal_len = len * 2 * 2;
1672   std::vector<unsigned char> digits (decimal_len, 0);
1673
1674   /* Ok, we have an unknown number of bytes of data to be printed in
1675    * decimal.
1676    *
1677    * Given a hex number (in nibbles) as XYZ, we start by taking X and
1678    * decimalizing it as "x1 x2" in two decimal nibbles.  Then we multiply
1679    * the nibbles by 16, add Y and re-decimalize.  Repeat with Z.
1680    *
1681    * The trick is that "digits" holds a base-10 number, but sometimes
1682    * the individual digits are > 10.
1683    *
1684    * Outer loop is per nibble (hex digit) of input, from MSD end to
1685    * LSD end.
1686    */
1687   decimal_digits = 0;           /* Number of decimal digits so far */
1688   p = (byte_order == BFD_ENDIAN_BIG) ? valaddr : valaddr + len - 1;
1689   flip = 0;
1690   while ((byte_order == BFD_ENDIAN_BIG) ? (p < valaddr + len) : (p >= valaddr))
1691     {
1692       /*
1693        * Multiply current base-ten number by 16 in place.
1694        * Each digit was between 0 and 9, now is between
1695        * 0 and 144.
1696        */
1697       for (j = 0; j < decimal_digits; j++)
1698         {
1699           digits[j] = SHIFT (digits[j]);
1700         }
1701
1702       /* Take the next nibble off the input and add it to what
1703        * we've got in the LSB position.  Bottom 'digit' is now
1704        * between 0 and 159.
1705        *
1706        * "flip" is used to run this loop twice for each byte.
1707        */
1708       if (flip == 0)
1709         {
1710           /* Take top nibble.  */
1711
1712           digits[0] += HIGH_NIBBLE (*p);
1713           flip = 1;
1714         }
1715       else
1716         {
1717           /* Take low nibble and bump our pointer "p".  */
1718
1719           digits[0] += LOW_NIBBLE (*p);
1720           if (byte_order == BFD_ENDIAN_BIG)
1721             p++;
1722           else
1723             p--;
1724           flip = 0;
1725         }
1726
1727       /* Re-decimalize.  We have to do this often enough
1728        * that we don't overflow, but once per nibble is
1729        * overkill.  Easier this way, though.  Note that the
1730        * carry is often larger than 10 (e.g. max initial
1731        * carry out of lowest nibble is 15, could bubble all
1732        * the way up greater than 10).  So we have to do
1733        * the carrying beyond the last current digit.
1734        */
1735       carry = 0;
1736       for (j = 0; j < decimal_len - 1; j++)
1737         {
1738           digits[j] += carry;
1739
1740           /* "/" won't handle an unsigned char with
1741            * a value that if signed would be negative.
1742            * So extend to longword int via "dummy".
1743            */
1744           dummy = digits[j];
1745           carry = CARRY_OUT (dummy);
1746           digits[j] = CARRY_LEFT (dummy);
1747
1748           if (j >= decimal_digits && carry == 0)
1749             {
1750               /*
1751                * All higher digits are 0 and we
1752                * no longer have a carry.
1753                *
1754                * Note: "j" is 0-based, "decimal_digits" is
1755                *       1-based.
1756                */
1757               decimal_digits = j + 1;
1758               break;
1759             }
1760         }
1761     }
1762
1763   /* Ok, now "digits" is the decimal representation, with
1764      the "decimal_digits" actual digits.  Print!  */
1765
1766   for (i = decimal_digits - 1; i > 0 && digits[i] == 0; --i)
1767     ;
1768
1769   for (; i >= 0; i--)
1770     {
1771       fprintf_filtered (stream, "%1d", digits[i]);
1772     }
1773 }
1774
1775 /* VALADDR points to an integer of LEN bytes.  Print it in hex on stream.  */
1776
1777 void
1778 print_hex_chars (struct ui_file *stream, const gdb_byte *valaddr,
1779                  unsigned len, enum bfd_endian byte_order,
1780                  bool zero_pad)
1781 {
1782   const gdb_byte *p;
1783
1784   gdb_puts ("0x", stream);
1785   if (byte_order == BFD_ENDIAN_BIG)
1786     {
1787       p = valaddr;
1788
1789       if (!zero_pad)
1790         {
1791           /* Strip leading 0 bytes, but be sure to leave at least a
1792              single byte at the end.  */
1793           for (; p < valaddr + len - 1 && !*p; ++p)
1794             ;
1795         }
1796
1797       const gdb_byte *first = p;
1798       for (;
1799            p < valaddr + len;
1800            p++)
1801         {
1802           /* When not zero-padding, use a different format for the
1803              very first byte printed.  */
1804           if (!zero_pad && p == first)
1805             fprintf_filtered (stream, "%x", *p);
1806           else
1807             fprintf_filtered (stream, "%02x", *p);
1808         }
1809     }
1810   else
1811     {
1812       p = valaddr + len - 1;
1813
1814       if (!zero_pad)
1815         {
1816           /* Strip leading 0 bytes, but be sure to leave at least a
1817              single byte at the end.  */
1818           for (; p >= valaddr + 1 && !*p; --p)
1819             ;
1820         }
1821
1822       const gdb_byte *first = p;
1823       for (;
1824            p >= valaddr;
1825            p--)
1826         {
1827           /* When not zero-padding, use a different format for the
1828              very first byte printed.  */
1829           if (!zero_pad && p == first)
1830             fprintf_filtered (stream, "%x", *p);
1831           else
1832             fprintf_filtered (stream, "%02x", *p);
1833         }
1834     }
1835 }
1836
1837 /* Print function pointer with inferior address ADDRESS onto stdio
1838    stream STREAM.  */
1839
1840 void
1841 print_function_pointer_address (const struct value_print_options *options,
1842                                 struct gdbarch *gdbarch,
1843                                 CORE_ADDR address,
1844                                 struct ui_file *stream)
1845 {
1846   CORE_ADDR func_addr = gdbarch_convert_from_func_ptr_addr
1847     (gdbarch, address, current_inferior ()->top_target ());
1848
1849   /* If the function pointer is represented by a description, print
1850      the address of the description.  */
1851   if (options->addressprint && func_addr != address)
1852     {
1853       gdb_puts ("@", stream);
1854       gdb_puts (paddress (gdbarch, address), stream);
1855       gdb_puts (": ", stream);
1856     }
1857   print_address_demangle (options, gdbarch, func_addr, stream, demangle);
1858 }
1859
1860
1861 /* Print on STREAM using the given OPTIONS the index for the element
1862    at INDEX of an array whose index type is INDEX_TYPE.  */
1863     
1864 void  
1865 maybe_print_array_index (struct type *index_type, LONGEST index,
1866                          struct ui_file *stream,
1867                          const struct value_print_options *options)
1868 {
1869   if (!options->print_array_indexes)
1870     return; 
1871
1872   current_language->print_array_index (index_type, index, stream, options);
1873 }
1874
1875 /* See valprint.h.  */
1876
1877 void
1878 value_print_array_elements (struct value *val, struct ui_file *stream,
1879                             int recurse,
1880                             const struct value_print_options *options,
1881                             unsigned int i)
1882 {
1883   unsigned int things_printed = 0;
1884   unsigned len;
1885   struct type *elttype, *index_type;
1886   unsigned eltlen;
1887   /* Position of the array element we are examining to see
1888      whether it is repeated.  */
1889   unsigned int rep1;
1890   /* Number of repetitions we have detected so far.  */
1891   unsigned int reps;
1892   LONGEST low_bound, high_bound;
1893
1894   struct type *type = check_typedef (value_type (val));
1895
1896   elttype = TYPE_TARGET_TYPE (type);
1897   eltlen = type_length_units (check_typedef (elttype));
1898   index_type = type->index_type ();
1899   if (index_type->code () == TYPE_CODE_RANGE)
1900     index_type = TYPE_TARGET_TYPE (index_type);
1901
1902   if (get_array_bounds (type, &low_bound, &high_bound))
1903     {
1904       /* The array length should normally be HIGH_BOUND - LOW_BOUND +
1905          1.  But we have to be a little extra careful, because some
1906          languages such as Ada allow LOW_BOUND to be greater than
1907          HIGH_BOUND for empty arrays.  In that situation, the array
1908          length is just zero, not negative!  */
1909       if (low_bound > high_bound)
1910         len = 0;
1911       else
1912         len = high_bound - low_bound + 1;
1913     }
1914   else
1915     {
1916       warning (_("unable to get bounds of array, assuming null array"));
1917       low_bound = 0;
1918       len = 0;
1919     }
1920
1921   annotate_array_section_begin (i, elttype);
1922
1923   for (; i < len && things_printed < options->print_max; i++)
1924     {
1925       scoped_value_mark free_values;
1926
1927       if (i != 0)
1928         {
1929           if (options->prettyformat_arrays)
1930             {
1931               fprintf_filtered (stream, ",\n");
1932               print_spaces_filtered (2 + 2 * recurse, stream);
1933             }
1934           else
1935             fprintf_filtered (stream, ", ");
1936         }
1937       else if (options->prettyformat_arrays)
1938         {
1939           fprintf_filtered (stream, "\n");
1940           print_spaces_filtered (2 + 2 * recurse, stream);
1941         }
1942       stream->wrap_here (2 + 2 * recurse);
1943       maybe_print_array_index (index_type, i + low_bound,
1944                                stream, options);
1945
1946       rep1 = i + 1;
1947       reps = 1;
1948       /* Only check for reps if repeat_count_threshold is not set to
1949          UINT_MAX (unlimited).  */
1950       if (options->repeat_count_threshold < UINT_MAX)
1951         {
1952           while (rep1 < len
1953                  && value_contents_eq (val, i * eltlen,
1954                                        val, rep1 * eltlen,
1955                                        eltlen))
1956             {
1957               ++reps;
1958               ++rep1;
1959             }
1960         }
1961
1962       struct value *element = value_from_component (val, elttype, eltlen * i);
1963       common_val_print (element, stream, recurse + 1, options,
1964                         current_language);
1965
1966       if (reps > options->repeat_count_threshold)
1967         {
1968           annotate_elt_rep (reps);
1969           fprintf_filtered (stream, " %p[<repeats %u times>%p]",
1970                             metadata_style.style ().ptr (), reps, nullptr);
1971           annotate_elt_rep_end ();
1972
1973           i = rep1 - 1;
1974           things_printed += options->repeat_count_threshold;
1975         }
1976       else
1977         {
1978           annotate_elt ();
1979           things_printed++;
1980         }
1981     }
1982   annotate_array_section_end ();
1983   if (i < len)
1984     fprintf_filtered (stream, "...");
1985   if (options->prettyformat_arrays)
1986     {
1987       fprintf_filtered (stream, "\n");
1988       print_spaces_filtered (2 * recurse, stream);
1989     }
1990 }
1991
1992 /* Read LEN bytes of target memory at address MEMADDR, placing the
1993    results in GDB's memory at MYADDR.  Returns a count of the bytes
1994    actually read, and optionally a target_xfer_status value in the
1995    location pointed to by ERRPTR if ERRPTR is non-null.  */
1996
1997 /* FIXME: cagney/1999-10-14: Only used by val_print_string.  Can this
1998    function be eliminated.  */
1999
2000 static int
2001 partial_memory_read (CORE_ADDR memaddr, gdb_byte *myaddr,
2002                      int len, int *errptr)
2003 {
2004   int nread;                    /* Number of bytes actually read.  */
2005   int errcode;                  /* Error from last read.  */
2006
2007   /* First try a complete read.  */
2008   errcode = target_read_memory (memaddr, myaddr, len);
2009   if (errcode == 0)
2010     {
2011       /* Got it all.  */
2012       nread = len;
2013     }
2014   else
2015     {
2016       /* Loop, reading one byte at a time until we get as much as we can.  */
2017       for (errcode = 0, nread = 0; len > 0 && errcode == 0; nread++, len--)
2018         {
2019           errcode = target_read_memory (memaddr++, myaddr++, 1);
2020         }
2021       /* If an error, the last read was unsuccessful, so adjust count.  */
2022       if (errcode != 0)
2023         {
2024           nread--;
2025         }
2026     }
2027   if (errptr != NULL)
2028     {
2029       *errptr = errcode;
2030     }
2031   return (nread);
2032 }
2033
2034 /* Read a string from the inferior, at ADDR, with LEN characters of
2035    WIDTH bytes each.  Fetch at most FETCHLIMIT characters.  BUFFER
2036    will be set to a newly allocated buffer containing the string, and
2037    BYTES_READ will be set to the number of bytes read.  Returns 0 on
2038    success, or a target_xfer_status on failure.
2039
2040    If LEN > 0, reads the lesser of LEN or FETCHLIMIT characters
2041    (including eventual NULs in the middle or end of the string).
2042
2043    If LEN is -1, stops at the first null character (not necessarily
2044    the first null byte) up to a maximum of FETCHLIMIT characters.  Set
2045    FETCHLIMIT to UINT_MAX to read as many characters as possible from
2046    the string.
2047
2048    Unless an exception is thrown, BUFFER will always be allocated, even on
2049    failure.  In this case, some characters might have been read before the
2050    failure happened.  Check BYTES_READ to recognize this situation.  */
2051
2052 int
2053 read_string (CORE_ADDR addr, int len, int width, unsigned int fetchlimit,
2054              enum bfd_endian byte_order, gdb::unique_xmalloc_ptr<gdb_byte> *buffer,
2055              int *bytes_read)
2056 {
2057   int errcode;                  /* Errno returned from bad reads.  */
2058   unsigned int nfetch;          /* Chars to fetch / chars fetched.  */
2059   gdb_byte *bufptr;             /* Pointer to next available byte in
2060                                    buffer.  */
2061
2062   /* Loop until we either have all the characters, or we encounter
2063      some error, such as bumping into the end of the address space.  */
2064
2065   buffer->reset (nullptr);
2066
2067   if (len > 0)
2068     {
2069       /* We want fetchlimit chars, so we might as well read them all in
2070          one operation.  */
2071       unsigned int fetchlen = std::min ((unsigned) len, fetchlimit);
2072
2073       buffer->reset ((gdb_byte *) xmalloc (fetchlen * width));
2074       bufptr = buffer->get ();
2075
2076       nfetch = partial_memory_read (addr, bufptr, fetchlen * width, &errcode)
2077         / width;
2078       addr += nfetch * width;
2079       bufptr += nfetch * width;
2080     }
2081   else if (len == -1)
2082     {
2083       unsigned long bufsize = 0;
2084       unsigned int chunksize;   /* Size of each fetch, in chars.  */
2085       int found_nul;            /* Non-zero if we found the nul char.  */
2086       gdb_byte *limit;          /* First location past end of fetch buffer.  */
2087
2088       found_nul = 0;
2089       /* We are looking for a NUL terminator to end the fetching, so we
2090          might as well read in blocks that are large enough to be efficient,
2091          but not so large as to be slow if fetchlimit happens to be large.
2092          So we choose the minimum of 8 and fetchlimit.  We used to use 200
2093          instead of 8 but 200 is way too big for remote debugging over a
2094           serial line.  */
2095       chunksize = std::min (8u, fetchlimit);
2096
2097       do
2098         {
2099           QUIT;
2100           nfetch = std::min ((unsigned long) chunksize, fetchlimit - bufsize);
2101
2102           if (*buffer == NULL)
2103             buffer->reset ((gdb_byte *) xmalloc (nfetch * width));
2104           else
2105             buffer->reset ((gdb_byte *) xrealloc (buffer->release (),
2106                                                   (nfetch + bufsize) * width));
2107
2108           bufptr = buffer->get () + bufsize * width;
2109           bufsize += nfetch;
2110
2111           /* Read as much as we can.  */
2112           nfetch = partial_memory_read (addr, bufptr, nfetch * width, &errcode)
2113                     / width;
2114
2115           /* Scan this chunk for the null character that terminates the string
2116              to print.  If found, we don't need to fetch any more.  Note
2117              that bufptr is explicitly left pointing at the next character
2118              after the null character, or at the next character after the end
2119              of the buffer.  */
2120
2121           limit = bufptr + nfetch * width;
2122           while (bufptr < limit)
2123             {
2124               unsigned long c;
2125
2126               c = extract_unsigned_integer (bufptr, width, byte_order);
2127               addr += width;
2128               bufptr += width;
2129               if (c == 0)
2130                 {
2131                   /* We don't care about any error which happened after
2132                      the NUL terminator.  */
2133                   errcode = 0;
2134                   found_nul = 1;
2135                   break;
2136                 }
2137             }
2138         }
2139       while (errcode == 0       /* no error */
2140              && bufptr - buffer->get () < fetchlimit * width    /* no overrun */
2141              && !found_nul);    /* haven't found NUL yet */
2142     }
2143   else
2144     {                           /* Length of string is really 0!  */
2145       /* We always allocate *buffer.  */
2146       buffer->reset ((gdb_byte *) xmalloc (1));
2147       bufptr = buffer->get ();
2148       errcode = 0;
2149     }
2150
2151   /* bufptr and addr now point immediately beyond the last byte which we
2152      consider part of the string (including a '\0' which ends the string).  */
2153   *bytes_read = bufptr - buffer->get ();
2154
2155   QUIT;
2156
2157   return errcode;
2158 }
2159
2160 /* Return true if print_wchar can display W without resorting to a
2161    numeric escape, false otherwise.  */
2162
2163 static int
2164 wchar_printable (gdb_wchar_t w)
2165 {
2166   return (gdb_iswprint (w)
2167           || w == LCST ('\a') || w == LCST ('\b')
2168           || w == LCST ('\f') || w == LCST ('\n')
2169           || w == LCST ('\r') || w == LCST ('\t')
2170           || w == LCST ('\v'));
2171 }
2172
2173 /* A helper function that converts the contents of STRING to wide
2174    characters and then appends them to OUTPUT.  */
2175
2176 static void
2177 append_string_as_wide (const char *string,
2178                        struct obstack *output)
2179 {
2180   for (; *string; ++string)
2181     {
2182       gdb_wchar_t w = gdb_btowc (*string);
2183       obstack_grow (output, &w, sizeof (gdb_wchar_t));
2184     }
2185 }
2186
2187 /* Print a wide character W to OUTPUT.  ORIG is a pointer to the
2188    original (target) bytes representing the character, ORIG_LEN is the
2189    number of valid bytes.  WIDTH is the number of bytes in a base
2190    characters of the type.  OUTPUT is an obstack to which wide
2191    characters are emitted.  QUOTER is a (narrow) character indicating
2192    the style of quotes surrounding the character to be printed.
2193    NEED_ESCAPE is an in/out flag which is used to track numeric
2194    escapes across calls.  */
2195
2196 static void
2197 print_wchar (gdb_wint_t w, const gdb_byte *orig,
2198              int orig_len, int width,
2199              enum bfd_endian byte_order,
2200              struct obstack *output,
2201              int quoter, int *need_escapep)
2202 {
2203   int need_escape = *need_escapep;
2204
2205   *need_escapep = 0;
2206
2207   /* iswprint implementation on Windows returns 1 for tab character.
2208      In order to avoid different printout on this host, we explicitly
2209      use wchar_printable function.  */
2210   switch (w)
2211     {
2212       case LCST ('\a'):
2213         obstack_grow_wstr (output, LCST ("\\a"));
2214         break;
2215       case LCST ('\b'):
2216         obstack_grow_wstr (output, LCST ("\\b"));
2217         break;
2218       case LCST ('\f'):
2219         obstack_grow_wstr (output, LCST ("\\f"));
2220         break;
2221       case LCST ('\n'):
2222         obstack_grow_wstr (output, LCST ("\\n"));
2223         break;
2224       case LCST ('\r'):
2225         obstack_grow_wstr (output, LCST ("\\r"));
2226         break;
2227       case LCST ('\t'):
2228         obstack_grow_wstr (output, LCST ("\\t"));
2229         break;
2230       case LCST ('\v'):
2231         obstack_grow_wstr (output, LCST ("\\v"));
2232         break;
2233       default:
2234         {
2235           if (wchar_printable (w) && (!need_escape || (!gdb_iswdigit (w)
2236                                                        && w != LCST ('8')
2237                                                        && w != LCST ('9'))))
2238             {
2239               gdb_wchar_t wchar = w;
2240
2241               if (w == gdb_btowc (quoter) || w == LCST ('\\'))
2242                 obstack_grow_wstr (output, LCST ("\\"));
2243               obstack_grow (output, &wchar, sizeof (gdb_wchar_t));
2244             }
2245           else
2246             {
2247               int i;
2248
2249               for (i = 0; i + width <= orig_len; i += width)
2250                 {
2251                   char octal[30];
2252                   ULONGEST value;
2253
2254                   value = extract_unsigned_integer (&orig[i], width,
2255                                                   byte_order);
2256                   /* If the value fits in 3 octal digits, print it that
2257                      way.  Otherwise, print it as a hex escape.  */
2258                   if (value <= 0777)
2259                     xsnprintf (octal, sizeof (octal), "\\%.3o",
2260                                (int) (value & 0777));
2261                   else
2262                     xsnprintf (octal, sizeof (octal), "\\x%lx", (long) value);
2263                   append_string_as_wide (octal, output);
2264                 }
2265               /* If we somehow have extra bytes, print them now.  */
2266               while (i < orig_len)
2267                 {
2268                   char octal[5];
2269
2270                   xsnprintf (octal, sizeof (octal), "\\%.3o", orig[i] & 0xff);
2271                   append_string_as_wide (octal, output);
2272                   ++i;
2273                 }
2274
2275               *need_escapep = 1;
2276             }
2277           break;
2278         }
2279     }
2280 }
2281
2282 /* Print the character C on STREAM as part of the contents of a
2283    literal string whose delimiter is QUOTER.  ENCODING names the
2284    encoding of C.  */
2285
2286 void
2287 generic_emit_char (int c, struct type *type, struct ui_file *stream,
2288                    int quoter, const char *encoding)
2289 {
2290   enum bfd_endian byte_order
2291     = type_byte_order (type);
2292   gdb_byte *c_buf;
2293   int need_escape = 0;
2294
2295   c_buf = (gdb_byte *) alloca (TYPE_LENGTH (type));
2296   pack_long (c_buf, type, c);
2297
2298   wchar_iterator iter (c_buf, TYPE_LENGTH (type), encoding, TYPE_LENGTH (type));
2299
2300   /* This holds the printable form of the wchar_t data.  */
2301   auto_obstack wchar_buf;
2302
2303   while (1)
2304     {
2305       int num_chars;
2306       gdb_wchar_t *chars;
2307       const gdb_byte *buf;
2308       size_t buflen;
2309       int print_escape = 1;
2310       enum wchar_iterate_result result;
2311
2312       num_chars = iter.iterate (&result, &chars, &buf, &buflen);
2313       if (num_chars < 0)
2314         break;
2315       if (num_chars > 0)
2316         {
2317           /* If all characters are printable, print them.  Otherwise,
2318              we're going to have to print an escape sequence.  We
2319              check all characters because we want to print the target
2320              bytes in the escape sequence, and we don't know character
2321              boundaries there.  */
2322           int i;
2323
2324           print_escape = 0;
2325           for (i = 0; i < num_chars; ++i)
2326             if (!wchar_printable (chars[i]))
2327               {
2328                 print_escape = 1;
2329                 break;
2330               }
2331
2332           if (!print_escape)
2333             {
2334               for (i = 0; i < num_chars; ++i)
2335                 print_wchar (chars[i], buf, buflen,
2336                              TYPE_LENGTH (type), byte_order,
2337                              &wchar_buf, quoter, &need_escape);
2338             }
2339         }
2340
2341       /* This handles the NUM_CHARS == 0 case as well.  */
2342       if (print_escape)
2343         print_wchar (gdb_WEOF, buf, buflen, TYPE_LENGTH (type),
2344                      byte_order, &wchar_buf, quoter, &need_escape);
2345     }
2346
2347   /* The output in the host encoding.  */
2348   auto_obstack output;
2349
2350   convert_between_encodings (INTERMEDIATE_ENCODING, host_charset (),
2351                              (gdb_byte *) obstack_base (&wchar_buf),
2352                              obstack_object_size (&wchar_buf),
2353                              sizeof (gdb_wchar_t), &output, translit_char);
2354   obstack_1grow (&output, '\0');
2355
2356   gdb_puts ((const char *) obstack_base (&output), stream);
2357 }
2358
2359 /* Return the repeat count of the next character/byte in ITER,
2360    storing the result in VEC.  */
2361
2362 static int
2363 count_next_character (wchar_iterator *iter,
2364                       std::vector<converted_character> *vec)
2365 {
2366   struct converted_character *current;
2367
2368   if (vec->empty ())
2369     {
2370       struct converted_character tmp;
2371       gdb_wchar_t *chars;
2372
2373       tmp.num_chars
2374         = iter->iterate (&tmp.result, &chars, &tmp.buf, &tmp.buflen);
2375       if (tmp.num_chars > 0)
2376         {
2377           gdb_assert (tmp.num_chars < MAX_WCHARS);
2378           memcpy (tmp.chars, chars, tmp.num_chars * sizeof (gdb_wchar_t));
2379         }
2380       vec->push_back (tmp);
2381     }
2382
2383   current = &vec->back ();
2384
2385   /* Count repeated characters or bytes.  */
2386   current->repeat_count = 1;
2387   if (current->num_chars == -1)
2388     {
2389       /* EOF  */
2390       return -1;
2391     }
2392   else
2393     {
2394       gdb_wchar_t *chars;
2395       struct converted_character d;
2396       int repeat;
2397
2398       d.repeat_count = 0;
2399
2400       while (1)
2401         {
2402           /* Get the next character.  */
2403           d.num_chars = iter->iterate (&d.result, &chars, &d.buf, &d.buflen);
2404
2405           /* If a character was successfully converted, save the character
2406              into the converted character.  */
2407           if (d.num_chars > 0)
2408             {
2409               gdb_assert (d.num_chars < MAX_WCHARS);
2410               memcpy (d.chars, chars, WCHAR_BUFLEN (d.num_chars));
2411             }
2412
2413           /* Determine if the current character is the same as this
2414              new character.  */
2415           if (d.num_chars == current->num_chars && d.result == current->result)
2416             {
2417               /* There are two cases to consider:
2418
2419                  1) Equality of converted character (num_chars > 0)
2420                  2) Equality of non-converted character (num_chars == 0)  */
2421               if ((current->num_chars > 0
2422                    && memcmp (current->chars, d.chars,
2423                               WCHAR_BUFLEN (current->num_chars)) == 0)
2424                   || (current->num_chars == 0
2425                       && current->buflen == d.buflen
2426                       && memcmp (current->buf, d.buf, current->buflen) == 0))
2427                 ++current->repeat_count;
2428               else
2429                 break;
2430             }
2431           else
2432             break;
2433         }
2434
2435       /* Push this next converted character onto the result vector.  */
2436       repeat = current->repeat_count;
2437       vec->push_back (d);
2438       return repeat;
2439     }
2440 }
2441
2442 /* Print the characters in CHARS to the OBSTACK.  QUOTE_CHAR is the quote
2443    character to use with string output.  WIDTH is the size of the output
2444    character type.  BYTE_ORDER is the target byte order.  OPTIONS
2445    is the user's print options.  */
2446
2447 static void
2448 print_converted_chars_to_obstack (struct obstack *obstack,
2449                                   const std::vector<converted_character> &chars,
2450                                   int quote_char, int width,
2451                                   enum bfd_endian byte_order,
2452                                   const struct value_print_options *options)
2453 {
2454   unsigned int idx;
2455   const converted_character *elem;
2456   enum {START, SINGLE, REPEAT, INCOMPLETE, FINISH} state, last;
2457   gdb_wchar_t wide_quote_char = gdb_btowc (quote_char);
2458   int need_escape = 0;
2459
2460   /* Set the start state.  */
2461   idx = 0;
2462   last = state = START;
2463   elem = NULL;
2464
2465   while (1)
2466     {
2467       switch (state)
2468         {
2469         case START:
2470           /* Nothing to do.  */
2471           break;
2472
2473         case SINGLE:
2474           {
2475             int j;
2476
2477             /* We are outputting a single character
2478                (< options->repeat_count_threshold).  */
2479
2480             if (last != SINGLE)
2481               {
2482                 /* We were outputting some other type of content, so we
2483                    must output and a comma and a quote.  */
2484                 if (last != START)
2485                   obstack_grow_wstr (obstack, LCST (", "));
2486                 obstack_grow (obstack, &wide_quote_char, sizeof (gdb_wchar_t));
2487               }
2488             /* Output the character.  */
2489             for (j = 0; j < elem->repeat_count; ++j)
2490               {
2491                 if (elem->result == wchar_iterate_ok)
2492                   print_wchar (elem->chars[0], elem->buf, elem->buflen, width,
2493                                byte_order, obstack, quote_char, &need_escape);
2494                 else
2495                   print_wchar (gdb_WEOF, elem->buf, elem->buflen, width,
2496                                byte_order, obstack, quote_char, &need_escape);
2497               }
2498           }
2499           break;
2500
2501         case REPEAT:
2502           {
2503             int j;
2504
2505             /* We are outputting a character with a repeat count
2506                greater than options->repeat_count_threshold.  */
2507
2508             if (last == SINGLE)
2509               {
2510                 /* We were outputting a single string.  Terminate the
2511                    string.  */
2512                 obstack_grow (obstack, &wide_quote_char, sizeof (gdb_wchar_t));
2513               }
2514             if (last != START)
2515               obstack_grow_wstr (obstack, LCST (", "));
2516
2517             /* Output the character and repeat string.  */
2518             obstack_grow_wstr (obstack, LCST ("'"));
2519             if (elem->result == wchar_iterate_ok)
2520               print_wchar (elem->chars[0], elem->buf, elem->buflen, width,
2521                            byte_order, obstack, quote_char, &need_escape);
2522             else
2523               print_wchar (gdb_WEOF, elem->buf, elem->buflen, width,
2524                            byte_order, obstack, quote_char, &need_escape);
2525             obstack_grow_wstr (obstack, LCST ("'"));
2526             std::string s = string_printf (_(" <repeats %u times>"),
2527                                            elem->repeat_count);
2528             for (j = 0; s[j]; ++j)
2529               {
2530                 gdb_wchar_t w = gdb_btowc (s[j]);
2531                 obstack_grow (obstack, &w, sizeof (gdb_wchar_t));
2532               }
2533           }
2534           break;
2535
2536         case INCOMPLETE:
2537           /* We are outputting an incomplete sequence.  */
2538           if (last == SINGLE)
2539             {
2540               /* If we were outputting a string of SINGLE characters,
2541                  terminate the quote.  */
2542               obstack_grow (obstack, &wide_quote_char, sizeof (gdb_wchar_t));
2543             }
2544           if (last != START)
2545             obstack_grow_wstr (obstack, LCST (", "));
2546
2547           /* Output the incomplete sequence string.  */
2548           obstack_grow_wstr (obstack, LCST ("<incomplete sequence "));
2549           print_wchar (gdb_WEOF, elem->buf, elem->buflen, width, byte_order,
2550                        obstack, 0, &need_escape);
2551           obstack_grow_wstr (obstack, LCST (">"));
2552
2553           /* We do not attempt to output anything after this.  */
2554           state = FINISH;
2555           break;
2556
2557         case FINISH:
2558           /* All done.  If we were outputting a string of SINGLE
2559              characters, the string must be terminated.  Otherwise,
2560              REPEAT and INCOMPLETE are always left properly terminated.  */
2561           if (last == SINGLE)
2562             obstack_grow (obstack, &wide_quote_char, sizeof (gdb_wchar_t));
2563
2564           return;
2565         }
2566
2567       /* Get the next element and state.  */
2568       last = state;
2569       if (state != FINISH)
2570         {
2571           elem = &chars[idx++];
2572           switch (elem->result)
2573             {
2574             case wchar_iterate_ok:
2575             case wchar_iterate_invalid:
2576               if (elem->repeat_count > options->repeat_count_threshold)
2577                 state = REPEAT;
2578               else
2579                 state = SINGLE;
2580               break;
2581
2582             case wchar_iterate_incomplete:
2583               state = INCOMPLETE;
2584               break;
2585
2586             case wchar_iterate_eof:
2587               state = FINISH;
2588               break;
2589             }
2590         }
2591     }
2592 }
2593
2594 /* Print the character string STRING, printing at most LENGTH
2595    characters.  LENGTH is -1 if the string is nul terminated.  TYPE is
2596    the type of each character.  OPTIONS holds the printing options;
2597    printing stops early if the number hits print_max; repeat counts
2598    are printed as appropriate.  Print ellipses at the end if we had to
2599    stop before printing LENGTH characters, or if FORCE_ELLIPSES.
2600    QUOTE_CHAR is the character to print at each end of the string.  If
2601    C_STYLE_TERMINATOR is true, and the last character is 0, then it is
2602    omitted.  */
2603
2604 void
2605 generic_printstr (struct ui_file *stream, struct type *type, 
2606                   const gdb_byte *string, unsigned int length, 
2607                   const char *encoding, int force_ellipses,
2608                   int quote_char, int c_style_terminator,
2609                   const struct value_print_options *options)
2610 {
2611   enum bfd_endian byte_order = type_byte_order (type);
2612   unsigned int i;
2613   int width = TYPE_LENGTH (type);
2614   int finished = 0;
2615   struct converted_character *last;
2616
2617   if (length == -1)
2618     {
2619       unsigned long current_char = 1;
2620
2621       for (i = 0; current_char; ++i)
2622         {
2623           QUIT;
2624           current_char = extract_unsigned_integer (string + i * width,
2625                                                    width, byte_order);
2626         }
2627       length = i;
2628     }
2629
2630   /* If the string was not truncated due to `set print elements', and
2631      the last byte of it is a null, we don't print that, in
2632      traditional C style.  */
2633   if (c_style_terminator
2634       && !force_ellipses
2635       && length > 0
2636       && (extract_unsigned_integer (string + (length - 1) * width,
2637                                     width, byte_order) == 0))
2638     length--;
2639
2640   if (length == 0)
2641     {
2642       gdb_puts ("\"\"", stream);
2643       return;
2644     }
2645
2646   /* Arrange to iterate over the characters, in wchar_t form.  */
2647   wchar_iterator iter (string, length * width, encoding, width);
2648   std::vector<converted_character> converted_chars;
2649
2650   /* Convert characters until the string is over or the maximum
2651      number of printed characters has been reached.  */
2652   i = 0;
2653   while (i < options->print_max)
2654     {
2655       int r;
2656
2657       QUIT;
2658
2659       /* Grab the next character and repeat count.  */
2660       r = count_next_character (&iter, &converted_chars);
2661
2662       /* If less than zero, the end of the input string was reached.  */
2663       if (r < 0)
2664         break;
2665
2666       /* Otherwise, add the count to the total print count and get
2667          the next character.  */
2668       i += r;
2669     }
2670
2671   /* Get the last element and determine if the entire string was
2672      processed.  */
2673   last = &converted_chars.back ();
2674   finished = (last->result == wchar_iterate_eof);
2675
2676   /* Ensure that CONVERTED_CHARS is terminated.  */
2677   last->result = wchar_iterate_eof;
2678
2679   /* WCHAR_BUF is the obstack we use to represent the string in
2680      wchar_t form.  */
2681   auto_obstack wchar_buf;
2682
2683   /* Print the output string to the obstack.  */
2684   print_converted_chars_to_obstack (&wchar_buf, converted_chars, quote_char,
2685                                     width, byte_order, options);
2686
2687   if (force_ellipses || !finished)
2688     obstack_grow_wstr (&wchar_buf, LCST ("..."));
2689
2690   /* OUTPUT is where we collect `char's for printing.  */
2691   auto_obstack output;
2692
2693   convert_between_encodings (INTERMEDIATE_ENCODING, host_charset (),
2694                              (gdb_byte *) obstack_base (&wchar_buf),
2695                              obstack_object_size (&wchar_buf),
2696                              sizeof (gdb_wchar_t), &output, translit_char);
2697   obstack_1grow (&output, '\0');
2698
2699   gdb_puts ((const char *) obstack_base (&output), stream);
2700 }
2701
2702 /* Print a string from the inferior, starting at ADDR and printing up to LEN
2703    characters, of WIDTH bytes a piece, to STREAM.  If LEN is -1, printing
2704    stops at the first null byte, otherwise printing proceeds (including null
2705    bytes) until either print_max or LEN characters have been printed,
2706    whichever is smaller.  ENCODING is the name of the string's
2707    encoding.  It can be NULL, in which case the target encoding is
2708    assumed.  */
2709
2710 int
2711 val_print_string (struct type *elttype, const char *encoding,
2712                   CORE_ADDR addr, int len,
2713                   struct ui_file *stream,
2714                   const struct value_print_options *options)
2715 {
2716   int force_ellipsis = 0;       /* Force ellipsis to be printed if nonzero.  */
2717   int err;                      /* Non-zero if we got a bad read.  */
2718   int found_nul;                /* Non-zero if we found the nul char.  */
2719   unsigned int fetchlimit;      /* Maximum number of chars to print.  */
2720   int bytes_read;
2721   gdb::unique_xmalloc_ptr<gdb_byte> buffer;     /* Dynamically growable fetch buffer.  */
2722   struct gdbarch *gdbarch = elttype->arch ();
2723   enum bfd_endian byte_order = type_byte_order (elttype);
2724   int width = TYPE_LENGTH (elttype);
2725
2726   /* First we need to figure out the limit on the number of characters we are
2727      going to attempt to fetch and print.  This is actually pretty simple.  If
2728      LEN >= zero, then the limit is the minimum of LEN and print_max.  If
2729      LEN is -1, then the limit is print_max.  This is true regardless of
2730      whether print_max is zero, UINT_MAX (unlimited), or something in between,
2731      because finding the null byte (or available memory) is what actually
2732      limits the fetch.  */
2733
2734   fetchlimit = (len == -1 ? options->print_max : std::min ((unsigned) len,
2735                                                            options->print_max));
2736
2737   err = read_string (addr, len, width, fetchlimit, byte_order,
2738                      &buffer, &bytes_read);
2739
2740   addr += bytes_read;
2741
2742   /* We now have either successfully filled the buffer to fetchlimit,
2743      or terminated early due to an error or finding a null char when
2744      LEN is -1.  */
2745
2746   /* Determine found_nul by looking at the last character read.  */
2747   found_nul = 0;
2748   if (bytes_read >= width)
2749     found_nul = extract_unsigned_integer (buffer.get () + bytes_read - width,
2750                                           width, byte_order) == 0;
2751   if (len == -1 && !found_nul)
2752     {
2753       gdb_byte *peekbuf;
2754
2755       /* We didn't find a NUL terminator we were looking for.  Attempt
2756          to peek at the next character.  If not successful, or it is not
2757          a null byte, then force ellipsis to be printed.  */
2758
2759       peekbuf = (gdb_byte *) alloca (width);
2760
2761       if (target_read_memory (addr, peekbuf, width) == 0
2762           && extract_unsigned_integer (peekbuf, width, byte_order) != 0)
2763         force_ellipsis = 1;
2764     }
2765   else if ((len >= 0 && err != 0) || (len > bytes_read / width))
2766     {
2767       /* Getting an error when we have a requested length, or fetching less
2768          than the number of characters actually requested, always make us
2769          print ellipsis.  */
2770       force_ellipsis = 1;
2771     }
2772
2773   /* If we get an error before fetching anything, don't print a string.
2774      But if we fetch something and then get an error, print the string
2775      and then the error message.  */
2776   if (err == 0 || bytes_read > 0)
2777     current_language->printstr (stream, elttype, buffer.get (),
2778                                 bytes_read / width,
2779                                 encoding, force_ellipsis, options);
2780
2781   if (err != 0)
2782     {
2783       std::string str = memory_error_message (TARGET_XFER_E_IO, gdbarch, addr);
2784
2785       fprintf_filtered (stream, _("<error: %ps>"),
2786                         styled_string (metadata_style.style (),
2787                                        str.c_str ()));
2788     }
2789
2790   return (bytes_read / width);
2791 }
2792
2793 /* Handle 'show print max-depth'.  */
2794
2795 static void
2796 show_print_max_depth (struct ui_file *file, int from_tty,
2797                       struct cmd_list_element *c, const char *value)
2798 {
2799   fprintf_filtered (file, _("Maximum print depth is %s.\n"), value);
2800 }
2801 \f
2802
2803 /* The 'set input-radix' command writes to this auxiliary variable.
2804    If the requested radix is valid, INPUT_RADIX is updated; otherwise,
2805    it is left unchanged.  */
2806
2807 static unsigned input_radix_1 = 10;
2808
2809 /* Validate an input or output radix setting, and make sure the user
2810    knows what they really did here.  Radix setting is confusing, e.g.
2811    setting the input radix to "10" never changes it!  */
2812
2813 static void
2814 set_input_radix (const char *args, int from_tty, struct cmd_list_element *c)
2815 {
2816   set_input_radix_1 (from_tty, input_radix_1);
2817 }
2818
2819 static void
2820 set_input_radix_1 (int from_tty, unsigned radix)
2821 {
2822   /* We don't currently disallow any input radix except 0 or 1, which don't
2823      make any mathematical sense.  In theory, we can deal with any input
2824      radix greater than 1, even if we don't have unique digits for every
2825      value from 0 to radix-1, but in practice we lose on large radix values.
2826      We should either fix the lossage or restrict the radix range more.
2827      (FIXME).  */
2828
2829   if (radix < 2)
2830     {
2831       input_radix_1 = input_radix;
2832       error (_("Nonsense input radix ``decimal %u''; input radix unchanged."),
2833              radix);
2834     }
2835   input_radix_1 = input_radix = radix;
2836   if (from_tty)
2837     {
2838       printf_filtered (_("Input radix now set to "
2839                          "decimal %u, hex %x, octal %o.\n"),
2840                        radix, radix, radix);
2841     }
2842 }
2843
2844 /* The 'set output-radix' command writes to this auxiliary variable.
2845    If the requested radix is valid, OUTPUT_RADIX is updated,
2846    otherwise, it is left unchanged.  */
2847
2848 static unsigned output_radix_1 = 10;
2849
2850 static void
2851 set_output_radix (const char *args, int from_tty, struct cmd_list_element *c)
2852 {
2853   set_output_radix_1 (from_tty, output_radix_1);
2854 }
2855
2856 static void
2857 set_output_radix_1 (int from_tty, unsigned radix)
2858 {
2859   /* Validate the radix and disallow ones that we aren't prepared to
2860      handle correctly, leaving the radix unchanged.  */
2861   switch (radix)
2862     {
2863     case 16:
2864       user_print_options.output_format = 'x';   /* hex */
2865       break;
2866     case 10:
2867       user_print_options.output_format = 0;     /* decimal */
2868       break;
2869     case 8:
2870       user_print_options.output_format = 'o';   /* octal */
2871       break;
2872     default:
2873       output_radix_1 = output_radix;
2874       error (_("Unsupported output radix ``decimal %u''; "
2875                "output radix unchanged."),
2876              radix);
2877     }
2878   output_radix_1 = output_radix = radix;
2879   if (from_tty)
2880     {
2881       printf_filtered (_("Output radix now set to "
2882                          "decimal %u, hex %x, octal %o.\n"),
2883                        radix, radix, radix);
2884     }
2885 }
2886
2887 /* Set both the input and output radix at once.  Try to set the output radix
2888    first, since it has the most restrictive range.  An radix that is valid as
2889    an output radix is also valid as an input radix.
2890
2891    It may be useful to have an unusual input radix.  If the user wishes to
2892    set an input radix that is not valid as an output radix, he needs to use
2893    the 'set input-radix' command.  */
2894
2895 static void
2896 set_radix (const char *arg, int from_tty)
2897 {
2898   unsigned radix;
2899
2900   radix = (arg == NULL) ? 10 : parse_and_eval_long (arg);
2901   set_output_radix_1 (0, radix);
2902   set_input_radix_1 (0, radix);
2903   if (from_tty)
2904     {
2905       printf_filtered (_("Input and output radices now set to "
2906                          "decimal %u, hex %x, octal %o.\n"),
2907                        radix, radix, radix);
2908     }
2909 }
2910
2911 /* Show both the input and output radices.  */
2912
2913 static void
2914 show_radix (const char *arg, int from_tty)
2915 {
2916   if (from_tty)
2917     {
2918       if (input_radix == output_radix)
2919         {
2920           printf_filtered (_("Input and output radices set to "
2921                              "decimal %u, hex %x, octal %o.\n"),
2922                            input_radix, input_radix, input_radix);
2923         }
2924       else
2925         {
2926           printf_filtered (_("Input radix set to decimal "
2927                              "%u, hex %x, octal %o.\n"),
2928                            input_radix, input_radix, input_radix);
2929           printf_filtered (_("Output radix set to decimal "
2930                              "%u, hex %x, octal %o.\n"),
2931                            output_radix, output_radix, output_radix);
2932         }
2933     }
2934 }
2935 \f
2936
2937 /* Controls printing of vtbl's.  */
2938 static void
2939 show_vtblprint (struct ui_file *file, int from_tty,
2940                 struct cmd_list_element *c, const char *value)
2941 {
2942   fprintf_filtered (file, _("\
2943 Printing of C++ virtual function tables is %s.\n"),
2944                     value);
2945 }
2946
2947 /* Controls looking up an object's derived type using what we find in
2948    its vtables.  */
2949 static void
2950 show_objectprint (struct ui_file *file, int from_tty,
2951                   struct cmd_list_element *c,
2952                   const char *value)
2953 {
2954   fprintf_filtered (file, _("\
2955 Printing of object's derived type based on vtable info is %s.\n"),
2956                     value);
2957 }
2958
2959 static void
2960 show_static_field_print (struct ui_file *file, int from_tty,
2961                          struct cmd_list_element *c,
2962                          const char *value)
2963 {
2964   fprintf_filtered (file,
2965                     _("Printing of C++ static members is %s.\n"),
2966                     value);
2967 }
2968
2969 \f
2970
2971 /* A couple typedefs to make writing the options a bit more
2972    convenient.  */
2973 using boolean_option_def
2974   = gdb::option::boolean_option_def<value_print_options>;
2975 using uinteger_option_def
2976   = gdb::option::uinteger_option_def<value_print_options>;
2977 using zuinteger_unlimited_option_def
2978   = gdb::option::zuinteger_unlimited_option_def<value_print_options>;
2979
2980 /* Definitions of options for the "print" and "compile print"
2981    commands.  */
2982 static const gdb::option::option_def value_print_option_defs[] = {
2983
2984   boolean_option_def {
2985     "address",
2986     [] (value_print_options *opt) { return &opt->addressprint; },
2987     show_addressprint, /* show_cmd_cb */
2988     N_("Set printing of addresses."),
2989     N_("Show printing of addresses."),
2990     NULL, /* help_doc */
2991   },
2992
2993   boolean_option_def {
2994     "array",
2995     [] (value_print_options *opt) { return &opt->prettyformat_arrays; },
2996     show_prettyformat_arrays, /* show_cmd_cb */
2997     N_("Set pretty formatting of arrays."),
2998     N_("Show pretty formatting of arrays."),
2999     NULL, /* help_doc */
3000   },
3001
3002   boolean_option_def {
3003     "array-indexes",
3004     [] (value_print_options *opt) { return &opt->print_array_indexes; },
3005     show_print_array_indexes, /* show_cmd_cb */
3006     N_("Set printing of array indexes."),
3007     N_("Show printing of array indexes."),
3008     NULL, /* help_doc */
3009   },
3010
3011   uinteger_option_def {
3012     "elements",
3013     [] (value_print_options *opt) { return &opt->print_max; },
3014     show_print_max, /* show_cmd_cb */
3015     N_("Set limit on string chars or array elements to print."),
3016     N_("Show limit on string chars or array elements to print."),
3017     N_("\"unlimited\" causes there to be no limit."),
3018   },
3019
3020   zuinteger_unlimited_option_def {
3021     "max-depth",
3022     [] (value_print_options *opt) { return &opt->max_depth; },
3023     show_print_max_depth, /* show_cmd_cb */
3024     N_("Set maximum print depth for nested structures, unions and arrays."),
3025     N_("Show maximum print depth for nested structures, unions, and arrays."),
3026     N_("When structures, unions, or arrays are nested beyond this depth then they\n\
3027 will be replaced with either '{...}' or '(...)' depending on the language.\n\
3028 Use \"unlimited\" to print the complete structure.")
3029   },
3030
3031   boolean_option_def {
3032     "memory-tag-violations",
3033     [] (value_print_options *opt) { return &opt->memory_tag_violations; },
3034     show_memory_tag_violations, /* show_cmd_cb */
3035     N_("Set printing of memory tag violations for pointers."),
3036     N_("Show printing of memory tag violations for pointers."),
3037     N_("Issue a warning when the printed value is a pointer\n\
3038 whose logical tag doesn't match the allocation tag of the memory\n\
3039 location it points to."),
3040   },
3041
3042   boolean_option_def {
3043     "null-stop",
3044     [] (value_print_options *opt) { return &opt->stop_print_at_null; },
3045     show_stop_print_at_null, /* show_cmd_cb */
3046     N_("Set printing of char arrays to stop at first null char."),
3047     N_("Show printing of char arrays to stop at first null char."),
3048     NULL, /* help_doc */
3049   },
3050
3051   boolean_option_def {
3052     "object",
3053     [] (value_print_options *opt) { return &opt->objectprint; },
3054     show_objectprint, /* show_cmd_cb */
3055     _("Set printing of C++ virtual function tables."),
3056     _("Show printing of C++ virtual function tables."),
3057     NULL, /* help_doc */
3058   },
3059
3060   boolean_option_def {
3061     "pretty",
3062     [] (value_print_options *opt) { return &opt->prettyformat_structs; },
3063     show_prettyformat_structs, /* show_cmd_cb */
3064     N_("Set pretty formatting of structures."),
3065     N_("Show pretty formatting of structures."),
3066     NULL, /* help_doc */
3067   },
3068
3069   boolean_option_def {
3070     "raw-values",
3071     [] (value_print_options *opt) { return &opt->raw; },
3072     NULL, /* show_cmd_cb */
3073     N_("Set whether to print values in raw form."),
3074     N_("Show whether to print values in raw form."),
3075     N_("If set, values are printed in raw form, bypassing any\n\
3076 pretty-printers for that value.")
3077   },
3078
3079   uinteger_option_def {
3080     "repeats",
3081     [] (value_print_options *opt) { return &opt->repeat_count_threshold; },
3082     show_repeat_count_threshold, /* show_cmd_cb */
3083     N_("Set threshold for repeated print elements."),
3084     N_("Show threshold for repeated print elements."),
3085     N_("\"unlimited\" causes all elements to be individually printed."),
3086   },
3087
3088   boolean_option_def {
3089     "static-members",
3090     [] (value_print_options *opt) { return &opt->static_field_print; },
3091     show_static_field_print, /* show_cmd_cb */
3092     N_("Set printing of C++ static members."),
3093     N_("Show printing of C++ static members."),
3094     NULL, /* help_doc */
3095   },
3096
3097   boolean_option_def {
3098     "symbol",
3099     [] (value_print_options *opt) { return &opt->symbol_print; },
3100     show_symbol_print, /* show_cmd_cb */
3101     N_("Set printing of symbol names when printing pointers."),
3102     N_("Show printing of symbol names when printing pointers."),
3103     NULL, /* help_doc */
3104   },
3105
3106   boolean_option_def {
3107     "union",
3108     [] (value_print_options *opt) { return &opt->unionprint; },
3109     show_unionprint, /* show_cmd_cb */
3110     N_("Set printing of unions interior to structures."),
3111     N_("Show printing of unions interior to structures."),
3112     NULL, /* help_doc */
3113   },
3114
3115   boolean_option_def {
3116     "vtbl",
3117     [] (value_print_options *opt) { return &opt->vtblprint; },
3118     show_vtblprint, /* show_cmd_cb */
3119     N_("Set printing of C++ virtual function tables."),
3120     N_("Show printing of C++ virtual function tables."),
3121     NULL, /* help_doc */
3122   },
3123 };
3124
3125 /* See valprint.h.  */
3126
3127 gdb::option::option_def_group
3128 make_value_print_options_def_group (value_print_options *opts)
3129 {
3130   return {{value_print_option_defs}, opts};
3131 }
3132
3133 #if GDB_SELF_TEST
3134
3135 /* Test printing of TYPE_CODE_FLAGS values.  */
3136
3137 static void
3138 test_print_flags (gdbarch *arch)
3139 {
3140   type *flags_type = arch_flags_type (arch, "test_type", 32);
3141   type *field_type = builtin_type (arch)->builtin_uint32;
3142
3143   /* Value:  1010 1010
3144      Fields: CCCB BAAA */
3145   append_flags_type_field (flags_type, 0, 3, field_type, "A");
3146   append_flags_type_field (flags_type, 3, 2, field_type, "B");
3147   append_flags_type_field (flags_type, 5, 3, field_type, "C");
3148
3149   value *val = allocate_value (flags_type);
3150   gdb_byte *contents = value_contents_writeable (val).data ();
3151   store_unsigned_integer (contents, 4, gdbarch_byte_order (arch), 0xaa);
3152
3153   string_file out;
3154   val_print_type_code_flags (flags_type, val, 0, &out);
3155   SELF_CHECK (out.string () == "[ A=2 B=1 C=5 ]");
3156 }
3157
3158 #endif
3159
3160 void _initialize_valprint ();
3161 void
3162 _initialize_valprint ()
3163 {
3164 #if GDB_SELF_TEST
3165   selftests::register_test_foreach_arch ("print-flags", test_print_flags);
3166 #endif
3167
3168   set_show_commands setshow_print_cmds
3169     = add_setshow_prefix_cmd ("print", no_class,
3170                               _("Generic command for setting how things print."),
3171                               _("Generic command for showing print settings."),
3172                               &setprintlist, &showprintlist,
3173                               &setlist, &showlist);
3174   add_alias_cmd ("p", setshow_print_cmds.set, no_class, 1, &setlist);
3175   /* Prefer set print to set prompt.  */
3176   add_alias_cmd ("pr", setshow_print_cmds.set, no_class, 1, &setlist);
3177   add_alias_cmd ("p", setshow_print_cmds.show, no_class, 1, &showlist);
3178   add_alias_cmd ("pr", setshow_print_cmds.show, no_class, 1, &showlist);
3179
3180   set_show_commands setshow_print_raw_cmds
3181     = add_setshow_prefix_cmd
3182         ("raw", no_class,
3183          _("Generic command for setting what things to print in \"raw\" mode."),
3184          _("Generic command for showing \"print raw\" settings."),
3185          &setprintrawlist, &showprintrawlist, &setprintlist, &showprintlist);
3186   deprecate_cmd (setshow_print_raw_cmds.set, nullptr);
3187   deprecate_cmd (setshow_print_raw_cmds.show, nullptr);
3188
3189   gdb::option::add_setshow_cmds_for_options
3190     (class_support, &user_print_options, value_print_option_defs,
3191      &setprintlist, &showprintlist);
3192
3193   add_setshow_zuinteger_cmd ("input-radix", class_support, &input_radix_1,
3194                              _("\
3195 Set default input radix for entering numbers."), _("\
3196 Show default input radix for entering numbers."), NULL,
3197                              set_input_radix,
3198                              show_input_radix,
3199                              &setlist, &showlist);
3200
3201   add_setshow_zuinteger_cmd ("output-radix", class_support, &output_radix_1,
3202                              _("\
3203 Set default output radix for printing of values."), _("\
3204 Show default output radix for printing of values."), NULL,
3205                              set_output_radix,
3206                              show_output_radix,
3207                              &setlist, &showlist);
3208
3209   /* The "set radix" and "show radix" commands are special in that
3210      they are like normal set and show commands but allow two normally
3211      independent variables to be either set or shown with a single
3212      command.  So the usual deprecated_add_set_cmd() and [deleted]
3213      add_show_from_set() commands aren't really appropriate.  */
3214   /* FIXME: i18n: With the new add_setshow_integer command, that is no
3215      longer true - show can display anything.  */
3216   add_cmd ("radix", class_support, set_radix, _("\
3217 Set default input and output number radices.\n\
3218 Use 'set input-radix' or 'set output-radix' to independently set each.\n\
3219 Without an argument, sets both radices back to the default value of 10."),
3220            &setlist);
3221   add_cmd ("radix", class_support, show_radix, _("\
3222 Show the default input and output number radices.\n\
3223 Use 'show input-radix' or 'show output-radix' to independently show each."),
3224            &showlist);
3225 }
This page took 0.206636 seconds and 2 git commands to generate.