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