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