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