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