* value.h (val_print): Return void.
[platform/upstream/binutils.git] / gdb / valprint.c
1 /* Print values for GDB, the GNU debugger.
2
3    Copyright (C) 1986, 1988-2012 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 "gdb_string.h"
22 #include "symtab.h"
23 #include "gdbtypes.h"
24 #include "value.h"
25 #include "gdbcore.h"
26 #include "gdbcmd.h"
27 #include "target.h"
28 #include "language.h"
29 #include "annotate.h"
30 #include "valprint.h"
31 #include "floatformat.h"
32 #include "doublest.h"
33 #include "exceptions.h"
34 #include "dfp.h"
35 #include "python/python.h"
36 #include "ada-lang.h"
37 #include "gdb_obstack.h"
38 #include "charset.h"
39 #include <ctype.h>
40
41 #include <errno.h>
42
43 /* Prototypes for local functions */
44
45 static int partial_memory_read (CORE_ADDR memaddr, gdb_byte *myaddr,
46                                 int len, int *errnoptr);
47
48 static void show_print (char *, int);
49
50 static void set_print (char *, int);
51
52 static void set_radix (char *, int);
53
54 static void show_radix (char *, int);
55
56 static void set_input_radix (char *, int, struct cmd_list_element *);
57
58 static void set_input_radix_1 (int, unsigned);
59
60 static void set_output_radix (char *, int, struct cmd_list_element *);
61
62 static void set_output_radix_1 (int, unsigned);
63
64 void _initialize_valprint (void);
65
66 #define PRINT_MAX_DEFAULT 200   /* Start print_max off at this value.  */
67
68 struct value_print_options user_print_options =
69 {
70   Val_pretty_default,           /* pretty */
71   0,                            /* prettyprint_arrays */
72   0,                            /* prettyprint_structs */
73   0,                            /* vtblprint */
74   1,                            /* unionprint */
75   1,                            /* addressprint */
76   0,                            /* objectprint */
77   PRINT_MAX_DEFAULT,            /* print_max */
78   10,                           /* repeat_count_threshold */
79   0,                            /* output_format */
80   0,                            /* format */
81   0,                            /* stop_print_at_null */
82   0,                            /* inspect_it */
83   0,                            /* print_array_indexes */
84   0,                            /* deref_ref */
85   1,                            /* static_field_print */
86   1,                            /* pascal_static_field_print */
87   0,                            /* raw */
88   0                             /* summary */
89 };
90
91 /* Initialize *OPTS to be a copy of the user print options.  */
92 void
93 get_user_print_options (struct value_print_options *opts)
94 {
95   *opts = user_print_options;
96 }
97
98 /* Initialize *OPTS to be a copy of the user print options, but with
99    pretty-printing disabled.  */
100 void
101 get_raw_print_options (struct value_print_options *opts)
102 {  
103   *opts = user_print_options;
104   opts->pretty = Val_no_prettyprint;
105 }
106
107 /* Initialize *OPTS to be a copy of the user print options, but using
108    FORMAT as the formatting option.  */
109 void
110 get_formatted_print_options (struct value_print_options *opts,
111                              char format)
112 {
113   *opts = user_print_options;
114   opts->format = format;
115 }
116
117 static void
118 show_print_max (struct ui_file *file, int from_tty,
119                 struct cmd_list_element *c, const char *value)
120 {
121   fprintf_filtered (file,
122                     _("Limit on string chars or array "
123                       "elements to print is %s.\n"),
124                     value);
125 }
126
127
128 /* Default input and output radixes, and output format letter.  */
129
130 unsigned input_radix = 10;
131 static void
132 show_input_radix (struct ui_file *file, int from_tty,
133                   struct cmd_list_element *c, const char *value)
134 {
135   fprintf_filtered (file,
136                     _("Default input radix for entering numbers is %s.\n"),
137                     value);
138 }
139
140 unsigned output_radix = 10;
141 static void
142 show_output_radix (struct ui_file *file, int from_tty,
143                    struct cmd_list_element *c, const char *value)
144 {
145   fprintf_filtered (file,
146                     _("Default output radix for printing of values is %s.\n"),
147                     value);
148 }
149
150 /* By default we print arrays without printing the index of each element in
151    the array.  This behavior can be changed by setting PRINT_ARRAY_INDEXES.  */
152
153 static void
154 show_print_array_indexes (struct ui_file *file, int from_tty,
155                           struct cmd_list_element *c, const char *value)
156 {
157   fprintf_filtered (file, _("Printing of array indexes is %s.\n"), value);
158 }
159
160 /* Print repeat counts if there are more than this many repetitions of an
161    element in an array.  Referenced by the low level language dependent
162    print routines.  */
163
164 static void
165 show_repeat_count_threshold (struct ui_file *file, int from_tty,
166                              struct cmd_list_element *c, const char *value)
167 {
168   fprintf_filtered (file, _("Threshold for repeated print elements is %s.\n"),
169                     value);
170 }
171
172 /* If nonzero, stops printing of char arrays at first null.  */
173
174 static void
175 show_stop_print_at_null (struct ui_file *file, int from_tty,
176                          struct cmd_list_element *c, const char *value)
177 {
178   fprintf_filtered (file,
179                     _("Printing of char arrays to stop "
180                       "at first null char is %s.\n"),
181                     value);
182 }
183
184 /* Controls pretty printing of structures.  */
185
186 static void
187 show_prettyprint_structs (struct ui_file *file, int from_tty,
188                           struct cmd_list_element *c, const char *value)
189 {
190   fprintf_filtered (file, _("Prettyprinting of structures is %s.\n"), value);
191 }
192
193 /* Controls pretty printing of arrays.  */
194
195 static void
196 show_prettyprint_arrays (struct ui_file *file, int from_tty,
197                          struct cmd_list_element *c, const char *value)
198 {
199   fprintf_filtered (file, _("Prettyprinting of arrays is %s.\n"), value);
200 }
201
202 /* If nonzero, causes unions inside structures or other unions to be
203    printed.  */
204
205 static void
206 show_unionprint (struct ui_file *file, int from_tty,
207                  struct cmd_list_element *c, const char *value)
208 {
209   fprintf_filtered (file,
210                     _("Printing of unions interior to structures is %s.\n"),
211                     value);
212 }
213
214 /* If nonzero, causes machine addresses to be printed in certain contexts.  */
215
216 static void
217 show_addressprint (struct ui_file *file, int from_tty,
218                    struct cmd_list_element *c, const char *value)
219 {
220   fprintf_filtered (file, _("Printing of addresses is %s.\n"), value);
221 }
222 \f
223
224 /* A helper function for val_print.  When printing in "summary" mode,
225    we want to print scalar arguments, but not aggregate arguments.
226    This function distinguishes between the two.  */
227
228 static int
229 scalar_type_p (struct type *type)
230 {
231   CHECK_TYPEDEF (type);
232   while (TYPE_CODE (type) == TYPE_CODE_REF)
233     {
234       type = TYPE_TARGET_TYPE (type);
235       CHECK_TYPEDEF (type);
236     }
237   switch (TYPE_CODE (type))
238     {
239     case TYPE_CODE_ARRAY:
240     case TYPE_CODE_STRUCT:
241     case TYPE_CODE_UNION:
242     case TYPE_CODE_SET:
243     case TYPE_CODE_STRING:
244     case TYPE_CODE_BITSTRING:
245       return 0;
246     default:
247       return 1;
248     }
249 }
250
251 /* Helper function to check the validity of some bits of a value.
252
253    If TYPE represents some aggregate type (e.g., a structure), return 1.
254    
255    Otherwise, any of the bytes starting at OFFSET and extending for
256    TYPE_LENGTH(TYPE) bytes are invalid, print a message to STREAM and
257    return 0.  The checking is done using FUNCS.
258    
259    Otherwise, return 1.  */
260
261 static int
262 valprint_check_validity (struct ui_file *stream,
263                          struct type *type,
264                          int embedded_offset,
265                          const struct value *val)
266 {
267   CHECK_TYPEDEF (type);
268
269   if (TYPE_CODE (type) != TYPE_CODE_UNION
270       && TYPE_CODE (type) != TYPE_CODE_STRUCT
271       && TYPE_CODE (type) != TYPE_CODE_ARRAY)
272     {
273       if (!value_bits_valid (val, TARGET_CHAR_BIT * embedded_offset,
274                              TARGET_CHAR_BIT * TYPE_LENGTH (type)))
275         {
276           val_print_optimized_out (stream);
277           return 0;
278         }
279
280       if (value_bits_synthetic_pointer (val, TARGET_CHAR_BIT * embedded_offset,
281                                         TARGET_CHAR_BIT * TYPE_LENGTH (type)))
282         {
283           fputs_filtered (_("<synthetic pointer>"), stream);
284           return 0;
285         }
286
287       if (!value_bytes_available (val, embedded_offset, TYPE_LENGTH (type)))
288         {
289           val_print_unavailable (stream);
290           return 0;
291         }
292     }
293
294   return 1;
295 }
296
297 void
298 val_print_optimized_out (struct ui_file *stream)
299 {
300   fprintf_filtered (stream, _("<optimized out>"));
301 }
302
303 void
304 val_print_unavailable (struct ui_file *stream)
305 {
306   fprintf_filtered (stream, _("<unavailable>"));
307 }
308
309 void
310 val_print_invalid_address (struct ui_file *stream)
311 {
312   fprintf_filtered (stream, _("<invalid address>"));
313 }
314
315 /* Print using the given LANGUAGE the data of type TYPE located at
316    VALADDR + EMBEDDED_OFFSET (within GDB), which came from the
317    inferior at address ADDRESS + EMBEDDED_OFFSET, onto stdio stream
318    STREAM according to OPTIONS.  VAL is the whole object that came
319    from ADDRESS.  VALADDR must point to the head of VAL's contents
320    buffer.
321
322    The language printers will pass down an adjusted EMBEDDED_OFFSET to
323    further helper subroutines as subfields of TYPE are printed.  In
324    such cases, VALADDR is passed down unadjusted, as well as VAL, so
325    that VAL can be queried for metadata about the contents data being
326    printed, using EMBEDDED_OFFSET as an offset into VAL's contents
327    buffer.  For example: "has this field been optimized out", or "I'm
328    printing an object while inspecting a traceframe; has this
329    particular piece of data been collected?".
330
331    RECURSE indicates the amount of indentation to supply before
332    continuation lines; this amount is roughly twice the value of
333    RECURSE.  */
334
335 void
336 val_print (struct type *type, const gdb_byte *valaddr, int embedded_offset,
337            CORE_ADDR address, struct ui_file *stream, int recurse,
338            const struct value *val,
339            const struct value_print_options *options,
340            const struct language_defn *language)
341 {
342   volatile struct gdb_exception except;
343   int ret = 0;
344   struct value_print_options local_opts = *options;
345   struct type *real_type = check_typedef (type);
346
347   if (local_opts.pretty == Val_pretty_default)
348     local_opts.pretty = (local_opts.prettyprint_structs
349                          ? Val_prettyprint : Val_no_prettyprint);
350
351   QUIT;
352
353   /* Ensure that the type is complete and not just a stub.  If the type is
354      only a stub and we can't find and substitute its complete type, then
355      print appropriate string and return.  */
356
357   if (TYPE_STUB (real_type))
358     {
359       fprintf_filtered (stream, _("<incomplete type>"));
360       gdb_flush (stream);
361       return;
362     }
363
364   if (!valprint_check_validity (stream, real_type, embedded_offset, val))
365     return;
366
367   if (!options->raw)
368     {
369       ret = apply_val_pretty_printer (type, valaddr, embedded_offset,
370                                       address, stream, recurse,
371                                       val, options, language);
372       if (ret)
373         return;
374     }
375
376   /* Handle summary mode.  If the value is a scalar, print it;
377      otherwise, print an ellipsis.  */
378   if (options->summary && !scalar_type_p (type))
379     {
380       fprintf_filtered (stream, "...");
381       return;
382     }
383
384   TRY_CATCH (except, RETURN_MASK_ERROR)
385     {
386       ret = language->la_val_print (type, valaddr, embedded_offset, address,
387                                     stream, recurse, val,
388                                     &local_opts);
389     }
390   if (except.reason < 0)
391     fprintf_filtered (stream, _("<error reading variable>"));
392 }
393
394 /* Check whether the value VAL is printable.  Return 1 if it is;
395    return 0 and print an appropriate error message to STREAM according to
396    OPTIONS if it is not.  */
397
398 static int
399 value_check_printable (struct value *val, struct ui_file *stream,
400                        const struct value_print_options *options)
401 {
402   if (val == 0)
403     {
404       fprintf_filtered (stream, _("<address of value unknown>"));
405       return 0;
406     }
407
408   if (value_entirely_optimized_out (val))
409     {
410       if (options->summary && !scalar_type_p (value_type (val)))
411         fprintf_filtered (stream, "...");
412       else
413         val_print_optimized_out (stream);
414       return 0;
415     }
416
417   if (TYPE_CODE (value_type (val)) == TYPE_CODE_INTERNAL_FUNCTION)
418     {
419       fprintf_filtered (stream, _("<internal function %s>"),
420                         value_internal_function_name (val));
421       return 0;
422     }
423
424   return 1;
425 }
426
427 /* Print using the given LANGUAGE the value VAL onto stream STREAM according
428    to OPTIONS.
429
430    This is a preferable interface to val_print, above, because it uses
431    GDB's value mechanism.  */
432
433 void
434 common_val_print (struct value *val, struct ui_file *stream, int recurse,
435                   const struct value_print_options *options,
436                   const struct language_defn *language)
437 {
438   if (!value_check_printable (val, stream, options))
439     return;
440
441   if (language->la_language == language_ada)
442     /* The value might have a dynamic type, which would cause trouble
443        below when trying to extract the value contents (since the value
444        size is determined from the type size which is unknown).  So
445        get a fixed representation of our value.  */
446     val = ada_to_fixed_value (val);
447
448   val_print (value_type (val), value_contents_for_printing (val),
449              value_embedded_offset (val), value_address (val),
450              stream, recurse,
451              val, options, language);
452 }
453
454 /* Print on stream STREAM the value VAL according to OPTIONS.  The value
455    is printed using the current_language syntax.  */
456
457 void
458 value_print (struct value *val, struct ui_file *stream,
459              const struct value_print_options *options)
460 {
461   if (!value_check_printable (val, stream, options))
462     return;
463
464   if (!options->raw)
465     {
466       int r = apply_val_pretty_printer (value_type (val),
467                                         value_contents_for_printing (val),
468                                         value_embedded_offset (val),
469                                         value_address (val),
470                                         stream, 0,
471                                         val, options, current_language);
472
473       if (r)
474         return;
475     }
476
477   LA_VALUE_PRINT (val, stream, options);
478 }
479
480 /* Called by various <lang>_val_print routines to print
481    TYPE_CODE_INT's.  TYPE is the type.  VALADDR is the address of the
482    value.  STREAM is where to print the value.  */
483
484 void
485 val_print_type_code_int (struct type *type, const gdb_byte *valaddr,
486                          struct ui_file *stream)
487 {
488   enum bfd_endian byte_order = gdbarch_byte_order (get_type_arch (type));
489
490   if (TYPE_LENGTH (type) > sizeof (LONGEST))
491     {
492       LONGEST val;
493
494       if (TYPE_UNSIGNED (type)
495           && extract_long_unsigned_integer (valaddr, TYPE_LENGTH (type),
496                                             byte_order, &val))
497         {
498           print_longest (stream, 'u', 0, val);
499         }
500       else
501         {
502           /* Signed, or we couldn't turn an unsigned value into a
503              LONGEST.  For signed values, one could assume two's
504              complement (a reasonable assumption, I think) and do
505              better than this.  */
506           print_hex_chars (stream, (unsigned char *) valaddr,
507                            TYPE_LENGTH (type), byte_order);
508         }
509     }
510   else
511     {
512       print_longest (stream, TYPE_UNSIGNED (type) ? 'u' : 'd', 0,
513                      unpack_long (type, valaddr));
514     }
515 }
516
517 void
518 val_print_type_code_flags (struct type *type, const gdb_byte *valaddr,
519                            struct ui_file *stream)
520 {
521   ULONGEST val = unpack_long (type, valaddr);
522   int bitpos, nfields = TYPE_NFIELDS (type);
523
524   fputs_filtered ("[ ", stream);
525   for (bitpos = 0; bitpos < nfields; bitpos++)
526     {
527       if (TYPE_FIELD_BITPOS (type, bitpos) != -1
528           && (val & ((ULONGEST)1 << bitpos)))
529         {
530           if (TYPE_FIELD_NAME (type, bitpos))
531             fprintf_filtered (stream, "%s ", TYPE_FIELD_NAME (type, bitpos));
532           else
533             fprintf_filtered (stream, "#%d ", bitpos);
534         }
535     }
536   fputs_filtered ("]", stream);
537 }
538
539 /* Print a scalar of data of type TYPE, pointed to in GDB by VALADDR,
540    according to OPTIONS and SIZE on STREAM.  Format i is not supported
541    at this level.
542
543    This is how the elements of an array or structure are printed
544    with a format.  */
545
546 void
547 val_print_scalar_formatted (struct type *type,
548                             const gdb_byte *valaddr, int embedded_offset,
549                             const struct value *val,
550                             const struct value_print_options *options,
551                             int size,
552                             struct ui_file *stream)
553 {
554   gdb_assert (val != NULL);
555   gdb_assert (valaddr == value_contents_for_printing_const (val));
556
557   /* If we get here with a string format, try again without it.  Go
558      all the way back to the language printers, which may call us
559      again.  */
560   if (options->format == 's')
561     {
562       struct value_print_options opts = *options;
563       opts.format = 0;
564       opts.deref_ref = 0;
565       val_print (type, valaddr, embedded_offset, 0, stream, 0, val, &opts,
566                  current_language);
567       return;
568     }
569
570   /* A scalar object that does not have all bits available can't be
571      printed, because all bits contribute to its representation.  */
572   if (!value_bits_valid (val, TARGET_CHAR_BIT * embedded_offset,
573                               TARGET_CHAR_BIT * TYPE_LENGTH (type)))
574     val_print_optimized_out (stream);
575   else if (!value_bytes_available (val, embedded_offset, TYPE_LENGTH (type)))
576     val_print_unavailable (stream);
577   else
578     print_scalar_formatted (valaddr + embedded_offset, type,
579                             options, size, stream);
580 }
581
582 /* Print a number according to FORMAT which is one of d,u,x,o,b,h,w,g.
583    The raison d'etre of this function is to consolidate printing of 
584    LONG_LONG's into this one function.  The format chars b,h,w,g are 
585    from print_scalar_formatted().  Numbers are printed using C
586    format.
587
588    USE_C_FORMAT means to use C format in all cases.  Without it, 
589    'o' and 'x' format do not include the standard C radix prefix
590    (leading 0 or 0x). 
591    
592    Hilfinger/2004-09-09: USE_C_FORMAT was originally called USE_LOCAL
593    and was intended to request formating according to the current
594    language and would be used for most integers that GDB prints.  The
595    exceptional cases were things like protocols where the format of
596    the integer is a protocol thing, not a user-visible thing).  The
597    parameter remains to preserve the information of what things might
598    be printed with language-specific format, should we ever resurrect
599    that capability.  */
600
601 void
602 print_longest (struct ui_file *stream, int format, int use_c_format,
603                LONGEST val_long)
604 {
605   const char *val;
606
607   switch (format)
608     {
609     case 'd':
610       val = int_string (val_long, 10, 1, 0, 1); break;
611     case 'u':
612       val = int_string (val_long, 10, 0, 0, 1); break;
613     case 'x':
614       val = int_string (val_long, 16, 0, 0, use_c_format); break;
615     case 'b':
616       val = int_string (val_long, 16, 0, 2, 1); break;
617     case 'h':
618       val = int_string (val_long, 16, 0, 4, 1); break;
619     case 'w':
620       val = int_string (val_long, 16, 0, 8, 1); break;
621     case 'g':
622       val = int_string (val_long, 16, 0, 16, 1); break;
623       break;
624     case 'o':
625       val = int_string (val_long, 8, 0, 0, use_c_format); break;
626     default:
627       internal_error (__FILE__, __LINE__,
628                       _("failed internal consistency check"));
629     } 
630   fputs_filtered (val, stream);
631 }
632
633 /* This used to be a macro, but I don't think it is called often enough
634    to merit such treatment.  */
635 /* Convert a LONGEST to an int.  This is used in contexts (e.g. number of
636    arguments to a function, number in a value history, register number, etc.)
637    where the value must not be larger than can fit in an int.  */
638
639 int
640 longest_to_int (LONGEST arg)
641 {
642   /* Let the compiler do the work.  */
643   int rtnval = (int) arg;
644
645   /* Check for overflows or underflows.  */
646   if (sizeof (LONGEST) > sizeof (int))
647     {
648       if (rtnval != arg)
649         {
650           error (_("Value out of range."));
651         }
652     }
653   return (rtnval);
654 }
655
656 /* Print a floating point value of type TYPE (not always a
657    TYPE_CODE_FLT), pointed to in GDB by VALADDR, on STREAM.  */
658
659 void
660 print_floating (const gdb_byte *valaddr, struct type *type,
661                 struct ui_file *stream)
662 {
663   DOUBLEST doub;
664   int inv;
665   const struct floatformat *fmt = NULL;
666   unsigned len = TYPE_LENGTH (type);
667   enum float_kind kind;
668
669   /* If it is a floating-point, check for obvious problems.  */
670   if (TYPE_CODE (type) == TYPE_CODE_FLT)
671     fmt = floatformat_from_type (type);
672   if (fmt != NULL)
673     {
674       kind = floatformat_classify (fmt, valaddr);
675       if (kind == float_nan)
676         {
677           if (floatformat_is_negative (fmt, valaddr))
678             fprintf_filtered (stream, "-");
679           fprintf_filtered (stream, "nan(");
680           fputs_filtered ("0x", stream);
681           fputs_filtered (floatformat_mantissa (fmt, valaddr), stream);
682           fprintf_filtered (stream, ")");
683           return;
684         }
685       else if (kind == float_infinite)
686         {
687           if (floatformat_is_negative (fmt, valaddr))
688             fputs_filtered ("-", stream);
689           fputs_filtered ("inf", stream);
690           return;
691         }
692     }
693
694   /* NOTE: cagney/2002-01-15: The TYPE passed into print_floating()
695      isn't necessarily a TYPE_CODE_FLT.  Consequently, unpack_double
696      needs to be used as that takes care of any necessary type
697      conversions.  Such conversions are of course direct to DOUBLEST
698      and disregard any possible target floating point limitations.
699      For instance, a u64 would be converted and displayed exactly on a
700      host with 80 bit DOUBLEST but with loss of information on a host
701      with 64 bit DOUBLEST.  */
702
703   doub = unpack_double (type, valaddr, &inv);
704   if (inv)
705     {
706       fprintf_filtered (stream, "<invalid float value>");
707       return;
708     }
709
710   /* FIXME: kettenis/2001-01-20: The following code makes too much
711      assumptions about the host and target floating point format.  */
712
713   /* NOTE: cagney/2002-02-03: Since the TYPE of what was passed in may
714      not necessarily be a TYPE_CODE_FLT, the below ignores that and
715      instead uses the type's length to determine the precision of the
716      floating-point value being printed.  */
717
718   if (len < sizeof (double))
719       fprintf_filtered (stream, "%.9g", (double) doub);
720   else if (len == sizeof (double))
721       fprintf_filtered (stream, "%.17g", (double) doub);
722   else
723 #ifdef PRINTF_HAS_LONG_DOUBLE
724     fprintf_filtered (stream, "%.35Lg", doub);
725 #else
726     /* This at least wins with values that are representable as
727        doubles.  */
728     fprintf_filtered (stream, "%.17g", (double) doub);
729 #endif
730 }
731
732 void
733 print_decimal_floating (const gdb_byte *valaddr, struct type *type,
734                         struct ui_file *stream)
735 {
736   enum bfd_endian byte_order = gdbarch_byte_order (get_type_arch (type));
737   char decstr[MAX_DECIMAL_STRING];
738   unsigned len = TYPE_LENGTH (type);
739
740   decimal_to_string (valaddr, len, byte_order, decstr);
741   fputs_filtered (decstr, stream);
742   return;
743 }
744
745 void
746 print_binary_chars (struct ui_file *stream, const gdb_byte *valaddr,
747                     unsigned len, enum bfd_endian byte_order)
748 {
749
750 #define BITS_IN_BYTES 8
751
752   const gdb_byte *p;
753   unsigned int i;
754   int b;
755
756   /* Declared "int" so it will be signed.
757      This ensures that right shift will shift in zeros.  */
758
759   const int mask = 0x080;
760
761   /* FIXME: We should be not printing leading zeroes in most cases.  */
762
763   if (byte_order == BFD_ENDIAN_BIG)
764     {
765       for (p = valaddr;
766            p < valaddr + len;
767            p++)
768         {
769           /* Every byte has 8 binary characters; peel off
770              and print from the MSB end.  */
771
772           for (i = 0; i < (BITS_IN_BYTES * sizeof (*p)); i++)
773             {
774               if (*p & (mask >> i))
775                 b = 1;
776               else
777                 b = 0;
778
779               fprintf_filtered (stream, "%1d", b);
780             }
781         }
782     }
783   else
784     {
785       for (p = valaddr + len - 1;
786            p >= valaddr;
787            p--)
788         {
789           for (i = 0; i < (BITS_IN_BYTES * sizeof (*p)); i++)
790             {
791               if (*p & (mask >> i))
792                 b = 1;
793               else
794                 b = 0;
795
796               fprintf_filtered (stream, "%1d", b);
797             }
798         }
799     }
800 }
801
802 /* VALADDR points to an integer of LEN bytes.
803    Print it in octal on stream or format it in buf.  */
804
805 void
806 print_octal_chars (struct ui_file *stream, const gdb_byte *valaddr,
807                    unsigned len, enum bfd_endian byte_order)
808 {
809   const gdb_byte *p;
810   unsigned char octa1, octa2, octa3, carry;
811   int cycle;
812
813   /* FIXME: We should be not printing leading zeroes in most cases.  */
814
815
816   /* Octal is 3 bits, which doesn't fit.  Yuk.  So we have to track
817    * the extra bits, which cycle every three bytes:
818    *
819    * Byte side:       0            1             2          3
820    *                         |             |            |            |
821    * bit number   123 456 78 | 9 012 345 6 | 78 901 234 | 567 890 12 |
822    *
823    * Octal side:   0   1   carry  3   4  carry ...
824    *
825    * Cycle number:    0             1            2
826    *
827    * But of course we are printing from the high side, so we have to
828    * figure out where in the cycle we are so that we end up with no
829    * left over bits at the end.
830    */
831 #define BITS_IN_OCTAL 3
832 #define HIGH_ZERO     0340
833 #define LOW_ZERO      0016
834 #define CARRY_ZERO    0003
835 #define HIGH_ONE      0200
836 #define MID_ONE       0160
837 #define LOW_ONE       0016
838 #define CARRY_ONE     0001
839 #define HIGH_TWO      0300
840 #define MID_TWO       0070
841 #define LOW_TWO       0007
842
843   /* For 32 we start in cycle 2, with two bits and one bit carry;
844      for 64 in cycle in cycle 1, with one bit and a two bit carry.  */
845
846   cycle = (len * BITS_IN_BYTES) % BITS_IN_OCTAL;
847   carry = 0;
848
849   fputs_filtered ("0", stream);
850   if (byte_order == BFD_ENDIAN_BIG)
851     {
852       for (p = valaddr;
853            p < valaddr + len;
854            p++)
855         {
856           switch (cycle)
857             {
858             case 0:
859               /* No carry in, carry out two bits.  */
860
861               octa1 = (HIGH_ZERO & *p) >> 5;
862               octa2 = (LOW_ZERO & *p) >> 2;
863               carry = (CARRY_ZERO & *p);
864               fprintf_filtered (stream, "%o", octa1);
865               fprintf_filtered (stream, "%o", octa2);
866               break;
867
868             case 1:
869               /* Carry in two bits, carry out one bit.  */
870
871               octa1 = (carry << 1) | ((HIGH_ONE & *p) >> 7);
872               octa2 = (MID_ONE & *p) >> 4;
873               octa3 = (LOW_ONE & *p) >> 1;
874               carry = (CARRY_ONE & *p);
875               fprintf_filtered (stream, "%o", octa1);
876               fprintf_filtered (stream, "%o", octa2);
877               fprintf_filtered (stream, "%o", octa3);
878               break;
879
880             case 2:
881               /* Carry in one bit, no carry out.  */
882
883               octa1 = (carry << 2) | ((HIGH_TWO & *p) >> 6);
884               octa2 = (MID_TWO & *p) >> 3;
885               octa3 = (LOW_TWO & *p);
886               carry = 0;
887               fprintf_filtered (stream, "%o", octa1);
888               fprintf_filtered (stream, "%o", octa2);
889               fprintf_filtered (stream, "%o", octa3);
890               break;
891
892             default:
893               error (_("Internal error in octal conversion;"));
894             }
895
896           cycle++;
897           cycle = cycle % BITS_IN_OCTAL;
898         }
899     }
900   else
901     {
902       for (p = valaddr + len - 1;
903            p >= valaddr;
904            p--)
905         {
906           switch (cycle)
907             {
908             case 0:
909               /* Carry out, no carry in */
910
911               octa1 = (HIGH_ZERO & *p) >> 5;
912               octa2 = (LOW_ZERO & *p) >> 2;
913               carry = (CARRY_ZERO & *p);
914               fprintf_filtered (stream, "%o", octa1);
915               fprintf_filtered (stream, "%o", octa2);
916               break;
917
918             case 1:
919               /* Carry in, carry out */
920
921               octa1 = (carry << 1) | ((HIGH_ONE & *p) >> 7);
922               octa2 = (MID_ONE & *p) >> 4;
923               octa3 = (LOW_ONE & *p) >> 1;
924               carry = (CARRY_ONE & *p);
925               fprintf_filtered (stream, "%o", octa1);
926               fprintf_filtered (stream, "%o", octa2);
927               fprintf_filtered (stream, "%o", octa3);
928               break;
929
930             case 2:
931               /* Carry in, no carry out */
932
933               octa1 = (carry << 2) | ((HIGH_TWO & *p) >> 6);
934               octa2 = (MID_TWO & *p) >> 3;
935               octa3 = (LOW_TWO & *p);
936               carry = 0;
937               fprintf_filtered (stream, "%o", octa1);
938               fprintf_filtered (stream, "%o", octa2);
939               fprintf_filtered (stream, "%o", octa3);
940               break;
941
942             default:
943               error (_("Internal error in octal conversion;"));
944             }
945
946           cycle++;
947           cycle = cycle % BITS_IN_OCTAL;
948         }
949     }
950
951 }
952
953 /* VALADDR points to an integer of LEN bytes.
954    Print it in decimal on stream or format it in buf.  */
955
956 void
957 print_decimal_chars (struct ui_file *stream, const gdb_byte *valaddr,
958                      unsigned len, enum bfd_endian byte_order)
959 {
960 #define TEN             10
961 #define CARRY_OUT(  x ) ((x) / TEN)     /* extend char to int */
962 #define CARRY_LEFT( x ) ((x) % TEN)
963 #define SHIFT( x )      ((x) << 4)
964 #define LOW_NIBBLE(  x ) ( (x) & 0x00F)
965 #define HIGH_NIBBLE( x ) (((x) & 0x0F0) >> 4)
966
967   const gdb_byte *p;
968   unsigned char *digits;
969   int carry;
970   int decimal_len;
971   int i, j, decimal_digits;
972   int dummy;
973   int flip;
974
975   /* Base-ten number is less than twice as many digits
976      as the base 16 number, which is 2 digits per byte.  */
977
978   decimal_len = len * 2 * 2;
979   digits = xmalloc (decimal_len);
980
981   for (i = 0; i < decimal_len; i++)
982     {
983       digits[i] = 0;
984     }
985
986   /* Ok, we have an unknown number of bytes of data to be printed in
987    * decimal.
988    *
989    * Given a hex number (in nibbles) as XYZ, we start by taking X and
990    * decemalizing it as "x1 x2" in two decimal nibbles.  Then we multiply
991    * the nibbles by 16, add Y and re-decimalize.  Repeat with Z.
992    *
993    * The trick is that "digits" holds a base-10 number, but sometimes
994    * the individual digits are > 10.
995    *
996    * Outer loop is per nibble (hex digit) of input, from MSD end to
997    * LSD end.
998    */
999   decimal_digits = 0;           /* Number of decimal digits so far */
1000   p = (byte_order == BFD_ENDIAN_BIG) ? valaddr : valaddr + len - 1;
1001   flip = 0;
1002   while ((byte_order == BFD_ENDIAN_BIG) ? (p < valaddr + len) : (p >= valaddr))
1003     {
1004       /*
1005        * Multiply current base-ten number by 16 in place.
1006        * Each digit was between 0 and 9, now is between
1007        * 0 and 144.
1008        */
1009       for (j = 0; j < decimal_digits; j++)
1010         {
1011           digits[j] = SHIFT (digits[j]);
1012         }
1013
1014       /* Take the next nibble off the input and add it to what
1015        * we've got in the LSB position.  Bottom 'digit' is now
1016        * between 0 and 159.
1017        *
1018        * "flip" is used to run this loop twice for each byte.
1019        */
1020       if (flip == 0)
1021         {
1022           /* Take top nibble.  */
1023
1024           digits[0] += HIGH_NIBBLE (*p);
1025           flip = 1;
1026         }
1027       else
1028         {
1029           /* Take low nibble and bump our pointer "p".  */
1030
1031           digits[0] += LOW_NIBBLE (*p);
1032           if (byte_order == BFD_ENDIAN_BIG)
1033             p++;
1034           else
1035             p--;
1036           flip = 0;
1037         }
1038
1039       /* Re-decimalize.  We have to do this often enough
1040        * that we don't overflow, but once per nibble is
1041        * overkill.  Easier this way, though.  Note that the
1042        * carry is often larger than 10 (e.g. max initial
1043        * carry out of lowest nibble is 15, could bubble all
1044        * the way up greater than 10).  So we have to do
1045        * the carrying beyond the last current digit.
1046        */
1047       carry = 0;
1048       for (j = 0; j < decimal_len - 1; j++)
1049         {
1050           digits[j] += carry;
1051
1052           /* "/" won't handle an unsigned char with
1053            * a value that if signed would be negative.
1054            * So extend to longword int via "dummy".
1055            */
1056           dummy = digits[j];
1057           carry = CARRY_OUT (dummy);
1058           digits[j] = CARRY_LEFT (dummy);
1059
1060           if (j >= decimal_digits && carry == 0)
1061             {
1062               /*
1063                * All higher digits are 0 and we
1064                * no longer have a carry.
1065                *
1066                * Note: "j" is 0-based, "decimal_digits" is
1067                *       1-based.
1068                */
1069               decimal_digits = j + 1;
1070               break;
1071             }
1072         }
1073     }
1074
1075   /* Ok, now "digits" is the decimal representation, with
1076      the "decimal_digits" actual digits.  Print!  */
1077
1078   for (i = decimal_digits - 1; i >= 0; i--)
1079     {
1080       fprintf_filtered (stream, "%1d", digits[i]);
1081     }
1082   xfree (digits);
1083 }
1084
1085 /* VALADDR points to an integer of LEN bytes.  Print it in hex on stream.  */
1086
1087 void
1088 print_hex_chars (struct ui_file *stream, const gdb_byte *valaddr,
1089                  unsigned len, enum bfd_endian byte_order)
1090 {
1091   const gdb_byte *p;
1092
1093   /* FIXME: We should be not printing leading zeroes in most cases.  */
1094
1095   fputs_filtered ("0x", stream);
1096   if (byte_order == BFD_ENDIAN_BIG)
1097     {
1098       for (p = valaddr;
1099            p < valaddr + len;
1100            p++)
1101         {
1102           fprintf_filtered (stream, "%02x", *p);
1103         }
1104     }
1105   else
1106     {
1107       for (p = valaddr + len - 1;
1108            p >= valaddr;
1109            p--)
1110         {
1111           fprintf_filtered (stream, "%02x", *p);
1112         }
1113     }
1114 }
1115
1116 /* VALADDR points to a char integer of LEN bytes.
1117    Print it out in appropriate language form on stream.
1118    Omit any leading zero chars.  */
1119
1120 void
1121 print_char_chars (struct ui_file *stream, struct type *type,
1122                   const gdb_byte *valaddr,
1123                   unsigned len, enum bfd_endian byte_order)
1124 {
1125   const gdb_byte *p;
1126
1127   if (byte_order == BFD_ENDIAN_BIG)
1128     {
1129       p = valaddr;
1130       while (p < valaddr + len - 1 && *p == 0)
1131         ++p;
1132
1133       while (p < valaddr + len)
1134         {
1135           LA_EMIT_CHAR (*p, type, stream, '\'');
1136           ++p;
1137         }
1138     }
1139   else
1140     {
1141       p = valaddr + len - 1;
1142       while (p > valaddr && *p == 0)
1143         --p;
1144
1145       while (p >= valaddr)
1146         {
1147           LA_EMIT_CHAR (*p, type, stream, '\'');
1148           --p;
1149         }
1150     }
1151 }
1152
1153 /* Print function pointer with inferior address ADDRESS onto stdio
1154    stream STREAM.  */
1155
1156 void
1157 print_function_pointer_address (struct gdbarch *gdbarch,
1158                                 CORE_ADDR address,
1159                                 struct ui_file *stream,
1160                                 int addressprint)
1161 {
1162   CORE_ADDR func_addr
1163     = gdbarch_convert_from_func_ptr_addr (gdbarch, address,
1164                                           &current_target);
1165
1166   /* If the function pointer is represented by a description, print
1167      the address of the description.  */
1168   if (addressprint && func_addr != address)
1169     {
1170       fputs_filtered ("@", stream);
1171       fputs_filtered (paddress (gdbarch, address), stream);
1172       fputs_filtered (": ", stream);
1173     }
1174   print_address_demangle (gdbarch, func_addr, stream, demangle);
1175 }
1176
1177
1178 /* Print on STREAM using the given OPTIONS the index for the element
1179    at INDEX of an array whose index type is INDEX_TYPE.  */
1180     
1181 void  
1182 maybe_print_array_index (struct type *index_type, LONGEST index,
1183                          struct ui_file *stream,
1184                          const struct value_print_options *options)
1185 {
1186   struct value *index_value;
1187
1188   if (!options->print_array_indexes)
1189     return; 
1190     
1191   index_value = value_from_longest (index_type, index);
1192
1193   LA_PRINT_ARRAY_INDEX (index_value, stream, options);
1194 }
1195
1196 /*  Called by various <lang>_val_print routines to print elements of an
1197    array in the form "<elem1>, <elem2>, <elem3>, ...".
1198
1199    (FIXME?)  Assumes array element separator is a comma, which is correct
1200    for all languages currently handled.
1201    (FIXME?)  Some languages have a notation for repeated array elements,
1202    perhaps we should try to use that notation when appropriate.  */
1203
1204 void
1205 val_print_array_elements (struct type *type,
1206                           const gdb_byte *valaddr, int embedded_offset,
1207                           CORE_ADDR address, struct ui_file *stream,
1208                           int recurse,
1209                           const struct value *val,
1210                           const struct value_print_options *options,
1211                           unsigned int i)
1212 {
1213   unsigned int things_printed = 0;
1214   unsigned len;
1215   struct type *elttype, *index_type;
1216   unsigned eltlen;
1217   /* Position of the array element we are examining to see
1218      whether it is repeated.  */
1219   unsigned int rep1;
1220   /* Number of repetitions we have detected so far.  */
1221   unsigned int reps;
1222   LONGEST low_bound, high_bound;
1223
1224   elttype = TYPE_TARGET_TYPE (type);
1225   eltlen = TYPE_LENGTH (check_typedef (elttype));
1226   index_type = TYPE_INDEX_TYPE (type);
1227
1228   if (get_array_bounds (type, &low_bound, &high_bound))
1229     {
1230       /* The array length should normally be HIGH_BOUND - LOW_BOUND + 1.
1231          But we have to be a little extra careful, because some languages
1232          such as Ada allow LOW_BOUND to be greater than HIGH_BOUND for
1233          empty arrays.  In that situation, the array length is just zero,
1234          not negative!  */
1235       if (low_bound > high_bound)
1236         len = 0;
1237       else
1238         len = high_bound - low_bound + 1;
1239     }
1240   else
1241     {
1242       warning (_("unable to get bounds of array, assuming null array"));
1243       low_bound = 0;
1244       len = 0;
1245     }
1246
1247   annotate_array_section_begin (i, elttype);
1248
1249   for (; i < len && things_printed < options->print_max; i++)
1250     {
1251       if (i != 0)
1252         {
1253           if (options->prettyprint_arrays)
1254             {
1255               fprintf_filtered (stream, ",\n");
1256               print_spaces_filtered (2 + 2 * recurse, stream);
1257             }
1258           else
1259             {
1260               fprintf_filtered (stream, ", ");
1261             }
1262         }
1263       wrap_here (n_spaces (2 + 2 * recurse));
1264       maybe_print_array_index (index_type, i + low_bound,
1265                                stream, options);
1266
1267       rep1 = i + 1;
1268       reps = 1;
1269       /* Only check for reps if repeat_count_threshold is not set to
1270          UINT_MAX (unlimited).  */
1271       if (options->repeat_count_threshold < UINT_MAX)
1272         {
1273           while (rep1 < len
1274                  && value_available_contents_eq (val,
1275                                                  embedded_offset + i * eltlen,
1276                                                  val,
1277                                                  (embedded_offset
1278                                                   + rep1 * eltlen),
1279                                                  eltlen))
1280             {
1281               ++reps;
1282               ++rep1;
1283             }
1284         }
1285
1286       if (reps > options->repeat_count_threshold)
1287         {
1288           val_print (elttype, valaddr, embedded_offset + i * eltlen,
1289                      address, stream, recurse + 1, val, options,
1290                      current_language);
1291           annotate_elt_rep (reps);
1292           fprintf_filtered (stream, " <repeats %u times>", reps);
1293           annotate_elt_rep_end ();
1294
1295           i = rep1 - 1;
1296           things_printed += options->repeat_count_threshold;
1297         }
1298       else
1299         {
1300           val_print (elttype, valaddr, embedded_offset + i * eltlen,
1301                      address,
1302                      stream, recurse + 1, val, options, current_language);
1303           annotate_elt ();
1304           things_printed++;
1305         }
1306     }
1307   annotate_array_section_end ();
1308   if (i < len)
1309     {
1310       fprintf_filtered (stream, "...");
1311     }
1312 }
1313
1314 /* Read LEN bytes of target memory at address MEMADDR, placing the
1315    results in GDB's memory at MYADDR.  Returns a count of the bytes
1316    actually read, and optionally an errno value in the location
1317    pointed to by ERRNOPTR if ERRNOPTR is non-null.  */
1318
1319 /* FIXME: cagney/1999-10-14: Only used by val_print_string.  Can this
1320    function be eliminated.  */
1321
1322 static int
1323 partial_memory_read (CORE_ADDR memaddr, gdb_byte *myaddr,
1324                      int len, int *errnoptr)
1325 {
1326   int nread;                    /* Number of bytes actually read.  */
1327   int errcode;                  /* Error from last read.  */
1328
1329   /* First try a complete read.  */
1330   errcode = target_read_memory (memaddr, myaddr, len);
1331   if (errcode == 0)
1332     {
1333       /* Got it all.  */
1334       nread = len;
1335     }
1336   else
1337     {
1338       /* Loop, reading one byte at a time until we get as much as we can.  */
1339       for (errcode = 0, nread = 0; len > 0 && errcode == 0; nread++, len--)
1340         {
1341           errcode = target_read_memory (memaddr++, myaddr++, 1);
1342         }
1343       /* If an error, the last read was unsuccessful, so adjust count.  */
1344       if (errcode != 0)
1345         {
1346           nread--;
1347         }
1348     }
1349   if (errnoptr != NULL)
1350     {
1351       *errnoptr = errcode;
1352     }
1353   return (nread);
1354 }
1355
1356 /* Read a string from the inferior, at ADDR, with LEN characters of WIDTH bytes
1357    each.  Fetch at most FETCHLIMIT characters.  BUFFER will be set to a newly
1358    allocated buffer containing the string, which the caller is responsible to
1359    free, and BYTES_READ will be set to the number of bytes read.  Returns 0 on
1360    success, or errno on failure.
1361
1362    If LEN > 0, reads exactly LEN characters (including eventual NULs in
1363    the middle or end of the string).  If LEN is -1, stops at the first
1364    null character (not necessarily the first null byte) up to a maximum
1365    of FETCHLIMIT characters.  Set FETCHLIMIT to UINT_MAX to read as many
1366    characters as possible from the string.
1367
1368    Unless an exception is thrown, BUFFER will always be allocated, even on
1369    failure.  In this case, some characters might have been read before the
1370    failure happened.  Check BYTES_READ to recognize this situation.
1371
1372    Note: There was a FIXME asking to make this code use target_read_string,
1373    but this function is more general (can read past null characters, up to
1374    given LEN).  Besides, it is used much more often than target_read_string
1375    so it is more tested.  Perhaps callers of target_read_string should use
1376    this function instead?  */
1377
1378 int
1379 read_string (CORE_ADDR addr, int len, int width, unsigned int fetchlimit,
1380              enum bfd_endian byte_order, gdb_byte **buffer, int *bytes_read)
1381 {
1382   int found_nul;                /* Non-zero if we found the nul char.  */
1383   int errcode;                  /* Errno returned from bad reads.  */
1384   unsigned int nfetch;          /* Chars to fetch / chars fetched.  */
1385   unsigned int chunksize;       /* Size of each fetch, in chars.  */
1386   gdb_byte *bufptr;             /* Pointer to next available byte in
1387                                    buffer.  */
1388   gdb_byte *limit;              /* First location past end of fetch buffer.  */
1389   struct cleanup *old_chain = NULL;     /* Top of the old cleanup chain.  */
1390
1391   /* Decide how large of chunks to try to read in one operation.  This
1392      is also pretty simple.  If LEN >= zero, then we want fetchlimit chars,
1393      so we might as well read them all in one operation.  If LEN is -1, we
1394      are looking for a NUL terminator to end the fetching, so we might as
1395      well read in blocks that are large enough to be efficient, but not so
1396      large as to be slow if fetchlimit happens to be large.  So we choose the
1397      minimum of 8 and fetchlimit.  We used to use 200 instead of 8 but
1398      200 is way too big for remote debugging over a serial line.  */
1399
1400   chunksize = (len == -1 ? min (8, fetchlimit) : fetchlimit);
1401
1402   /* Loop until we either have all the characters, or we encounter
1403      some error, such as bumping into the end of the address space.  */
1404
1405   found_nul = 0;
1406   *buffer = NULL;
1407
1408   old_chain = make_cleanup (free_current_contents, buffer);
1409
1410   if (len > 0)
1411     {
1412       *buffer = (gdb_byte *) xmalloc (len * width);
1413       bufptr = *buffer;
1414
1415       nfetch = partial_memory_read (addr, bufptr, len * width, &errcode)
1416         / width;
1417       addr += nfetch * width;
1418       bufptr += nfetch * width;
1419     }
1420   else if (len == -1)
1421     {
1422       unsigned long bufsize = 0;
1423
1424       do
1425         {
1426           QUIT;
1427           nfetch = min (chunksize, fetchlimit - bufsize);
1428
1429           if (*buffer == NULL)
1430             *buffer = (gdb_byte *) xmalloc (nfetch * width);
1431           else
1432             *buffer = (gdb_byte *) xrealloc (*buffer,
1433                                              (nfetch + bufsize) * width);
1434
1435           bufptr = *buffer + bufsize * width;
1436           bufsize += nfetch;
1437
1438           /* Read as much as we can.  */
1439           nfetch = partial_memory_read (addr, bufptr, nfetch * width, &errcode)
1440                     / width;
1441
1442           /* Scan this chunk for the null character that terminates the string
1443              to print.  If found, we don't need to fetch any more.  Note
1444              that bufptr is explicitly left pointing at the next character
1445              after the null character, or at the next character after the end
1446              of the buffer.  */
1447
1448           limit = bufptr + nfetch * width;
1449           while (bufptr < limit)
1450             {
1451               unsigned long c;
1452
1453               c = extract_unsigned_integer (bufptr, width, byte_order);
1454               addr += width;
1455               bufptr += width;
1456               if (c == 0)
1457                 {
1458                   /* We don't care about any error which happened after
1459                      the NUL terminator.  */
1460                   errcode = 0;
1461                   found_nul = 1;
1462                   break;
1463                 }
1464             }
1465         }
1466       while (errcode == 0       /* no error */
1467              && bufptr - *buffer < fetchlimit * width   /* no overrun */
1468              && !found_nul);    /* haven't found NUL yet */
1469     }
1470   else
1471     {                           /* Length of string is really 0!  */
1472       /* We always allocate *buffer.  */
1473       *buffer = bufptr = xmalloc (1);
1474       errcode = 0;
1475     }
1476
1477   /* bufptr and addr now point immediately beyond the last byte which we
1478      consider part of the string (including a '\0' which ends the string).  */
1479   *bytes_read = bufptr - *buffer;
1480
1481   QUIT;
1482
1483   discard_cleanups (old_chain);
1484
1485   return errcode;
1486 }
1487
1488 /* Return true if print_wchar can display W without resorting to a
1489    numeric escape, false otherwise.  */
1490
1491 static int
1492 wchar_printable (gdb_wchar_t w)
1493 {
1494   return (gdb_iswprint (w)
1495           || w == LCST ('\a') || w == LCST ('\b')
1496           || w == LCST ('\f') || w == LCST ('\n')
1497           || w == LCST ('\r') || w == LCST ('\t')
1498           || w == LCST ('\v'));
1499 }
1500
1501 /* A helper function that converts the contents of STRING to wide
1502    characters and then appends them to OUTPUT.  */
1503
1504 static void
1505 append_string_as_wide (const char *string,
1506                        struct obstack *output)
1507 {
1508   for (; *string; ++string)
1509     {
1510       gdb_wchar_t w = gdb_btowc (*string);
1511       obstack_grow (output, &w, sizeof (gdb_wchar_t));
1512     }
1513 }
1514
1515 /* Print a wide character W to OUTPUT.  ORIG is a pointer to the
1516    original (target) bytes representing the character, ORIG_LEN is the
1517    number of valid bytes.  WIDTH is the number of bytes in a base
1518    characters of the type.  OUTPUT is an obstack to which wide
1519    characters are emitted.  QUOTER is a (narrow) character indicating
1520    the style of quotes surrounding the character to be printed.
1521    NEED_ESCAPE is an in/out flag which is used to track numeric
1522    escapes across calls.  */
1523
1524 static void
1525 print_wchar (gdb_wint_t w, const gdb_byte *orig,
1526              int orig_len, int width,
1527              enum bfd_endian byte_order,
1528              struct obstack *output,
1529              int quoter, int *need_escapep)
1530 {
1531   int need_escape = *need_escapep;
1532
1533   *need_escapep = 0;
1534   if (gdb_iswprint (w) && (!need_escape || (!gdb_iswdigit (w)
1535                                             && w != LCST ('8')
1536                                             && w != LCST ('9'))))
1537     {
1538       gdb_wchar_t wchar = w;
1539
1540       if (w == gdb_btowc (quoter) || w == LCST ('\\'))
1541         obstack_grow_wstr (output, LCST ("\\"));
1542       obstack_grow (output, &wchar, sizeof (gdb_wchar_t));
1543     }
1544   else
1545     {
1546       switch (w)
1547         {
1548         case LCST ('\a'):
1549           obstack_grow_wstr (output, LCST ("\\a"));
1550           break;
1551         case LCST ('\b'):
1552           obstack_grow_wstr (output, LCST ("\\b"));
1553           break;
1554         case LCST ('\f'):
1555           obstack_grow_wstr (output, LCST ("\\f"));
1556           break;
1557         case LCST ('\n'):
1558           obstack_grow_wstr (output, LCST ("\\n"));
1559           break;
1560         case LCST ('\r'):
1561           obstack_grow_wstr (output, LCST ("\\r"));
1562           break;
1563         case LCST ('\t'):
1564           obstack_grow_wstr (output, LCST ("\\t"));
1565           break;
1566         case LCST ('\v'):
1567           obstack_grow_wstr (output, LCST ("\\v"));
1568           break;
1569         default:
1570           {
1571             int i;
1572
1573             for (i = 0; i + width <= orig_len; i += width)
1574               {
1575                 char octal[30];
1576                 ULONGEST value;
1577
1578                 value = extract_unsigned_integer (&orig[i], width,
1579                                                   byte_order);
1580                 /* If the value fits in 3 octal digits, print it that
1581                    way.  Otherwise, print it as a hex escape.  */
1582                 if (value <= 0777)
1583                   sprintf (octal, "\\%.3o", (int) (value & 0777));
1584                 else
1585                   sprintf (octal, "\\x%lx", (long) value);
1586                 append_string_as_wide (octal, output);
1587               }
1588             /* If we somehow have extra bytes, print them now.  */
1589             while (i < orig_len)
1590               {
1591                 char octal[5];
1592
1593                 sprintf (octal, "\\%.3o", orig[i] & 0xff);
1594                 append_string_as_wide (octal, output);
1595                 ++i;
1596               }
1597
1598             *need_escapep = 1;
1599           }
1600           break;
1601         }
1602     }
1603 }
1604
1605 /* Print the character C on STREAM as part of the contents of a
1606    literal string whose delimiter is QUOTER.  ENCODING names the
1607    encoding of C.  */
1608
1609 void
1610 generic_emit_char (int c, struct type *type, struct ui_file *stream,
1611                    int quoter, const char *encoding)
1612 {
1613   enum bfd_endian byte_order
1614     = gdbarch_byte_order (get_type_arch (type));
1615   struct obstack wchar_buf, output;
1616   struct cleanup *cleanups;
1617   gdb_byte *buf;
1618   struct wchar_iterator *iter;
1619   int need_escape = 0;
1620
1621   buf = alloca (TYPE_LENGTH (type));
1622   pack_long (buf, type, c);
1623
1624   iter = make_wchar_iterator (buf, TYPE_LENGTH (type),
1625                               encoding, TYPE_LENGTH (type));
1626   cleanups = make_cleanup_wchar_iterator (iter);
1627
1628   /* This holds the printable form of the wchar_t data.  */
1629   obstack_init (&wchar_buf);
1630   make_cleanup_obstack_free (&wchar_buf);
1631
1632   while (1)
1633     {
1634       int num_chars;
1635       gdb_wchar_t *chars;
1636       const gdb_byte *buf;
1637       size_t buflen;
1638       int print_escape = 1;
1639       enum wchar_iterate_result result;
1640
1641       num_chars = wchar_iterate (iter, &result, &chars, &buf, &buflen);
1642       if (num_chars < 0)
1643         break;
1644       if (num_chars > 0)
1645         {
1646           /* If all characters are printable, print them.  Otherwise,
1647              we're going to have to print an escape sequence.  We
1648              check all characters because we want to print the target
1649              bytes in the escape sequence, and we don't know character
1650              boundaries there.  */
1651           int i;
1652
1653           print_escape = 0;
1654           for (i = 0; i < num_chars; ++i)
1655             if (!wchar_printable (chars[i]))
1656               {
1657                 print_escape = 1;
1658                 break;
1659               }
1660
1661           if (!print_escape)
1662             {
1663               for (i = 0; i < num_chars; ++i)
1664                 print_wchar (chars[i], buf, buflen,
1665                              TYPE_LENGTH (type), byte_order,
1666                              &wchar_buf, quoter, &need_escape);
1667             }
1668         }
1669
1670       /* This handles the NUM_CHARS == 0 case as well.  */
1671       if (print_escape)
1672         print_wchar (gdb_WEOF, buf, buflen, TYPE_LENGTH (type),
1673                      byte_order, &wchar_buf, quoter, &need_escape);
1674     }
1675
1676   /* The output in the host encoding.  */
1677   obstack_init (&output);
1678   make_cleanup_obstack_free (&output);
1679
1680   convert_between_encodings (INTERMEDIATE_ENCODING, host_charset (),
1681                              obstack_base (&wchar_buf),
1682                              obstack_object_size (&wchar_buf),
1683                              1, &output, translit_char);
1684   obstack_1grow (&output, '\0');
1685
1686   fputs_filtered (obstack_base (&output), stream);
1687
1688   do_cleanups (cleanups);
1689 }
1690
1691 /* Print the character string STRING, printing at most LENGTH
1692    characters.  LENGTH is -1 if the string is nul terminated.  TYPE is
1693    the type of each character.  OPTIONS holds the printing options;
1694    printing stops early if the number hits print_max; repeat counts
1695    are printed as appropriate.  Print ellipses at the end if we had to
1696    stop before printing LENGTH characters, or if FORCE_ELLIPSES.
1697    QUOTE_CHAR is the character to print at each end of the string.  If
1698    C_STYLE_TERMINATOR is true, and the last character is 0, then it is
1699    omitted.  */
1700
1701 void
1702 generic_printstr (struct ui_file *stream, struct type *type, 
1703                   const gdb_byte *string, unsigned int length, 
1704                   const char *encoding, int force_ellipses,
1705                   int quote_char, int c_style_terminator,
1706                   const struct value_print_options *options)
1707 {
1708   enum bfd_endian byte_order = gdbarch_byte_order (get_type_arch (type));
1709   unsigned int i;
1710   unsigned int things_printed = 0;
1711   int in_quotes = 0;
1712   int need_comma = 0;
1713   int width = TYPE_LENGTH (type);
1714   struct obstack wchar_buf, output;
1715   struct cleanup *cleanup;
1716   struct wchar_iterator *iter;
1717   int finished = 0;
1718   int need_escape = 0;
1719   gdb_wchar_t wide_quote_char = gdb_btowc (quote_char);
1720
1721   if (length == -1)
1722     {
1723       unsigned long current_char = 1;
1724
1725       for (i = 0; current_char; ++i)
1726         {
1727           QUIT;
1728           current_char = extract_unsigned_integer (string + i * width,
1729                                                    width, byte_order);
1730         }
1731       length = i;
1732     }
1733
1734   /* If the string was not truncated due to `set print elements', and
1735      the last byte of it is a null, we don't print that, in
1736      traditional C style.  */
1737   if (c_style_terminator
1738       && !force_ellipses
1739       && length > 0
1740       && (extract_unsigned_integer (string + (length - 1) * width,
1741                                     width, byte_order) == 0))
1742     length--;
1743
1744   if (length == 0)
1745     {
1746       fputs_filtered ("\"\"", stream);
1747       return;
1748     }
1749
1750   /* Arrange to iterate over the characters, in wchar_t form.  */
1751   iter = make_wchar_iterator (string, length * width, encoding, width);
1752   cleanup = make_cleanup_wchar_iterator (iter);
1753
1754   /* WCHAR_BUF is the obstack we use to represent the string in
1755      wchar_t form.  */
1756   obstack_init (&wchar_buf);
1757   make_cleanup_obstack_free (&wchar_buf);
1758
1759   while (!finished && things_printed < options->print_max)
1760     {
1761       int num_chars;
1762       enum wchar_iterate_result result;
1763       gdb_wchar_t *chars;
1764       const gdb_byte *buf;
1765       size_t buflen;
1766
1767       QUIT;
1768
1769       if (need_comma)
1770         {
1771           obstack_grow_wstr (&wchar_buf, LCST (", "));
1772           need_comma = 0;
1773         }
1774
1775       num_chars = wchar_iterate (iter, &result, &chars, &buf, &buflen);
1776       /* We only look at repetitions when we were able to convert a
1777          single character in isolation.  This makes the code simpler
1778          and probably does the sensible thing in the majority of
1779          cases.  */
1780       while (num_chars == 1 && things_printed < options->print_max)
1781         {
1782           /* Count the number of repetitions.  */
1783           unsigned int reps = 0;
1784           gdb_wchar_t current_char = chars[0];
1785           const gdb_byte *orig_buf = buf;
1786           int orig_len = buflen;
1787
1788           if (need_comma)
1789             {
1790               obstack_grow_wstr (&wchar_buf, LCST (", "));
1791               need_comma = 0;
1792             }
1793
1794           while (num_chars == 1 && current_char == chars[0])
1795             {
1796               num_chars = wchar_iterate (iter, &result, &chars,
1797                                          &buf, &buflen);
1798               ++reps;
1799             }
1800
1801           /* Emit CURRENT_CHAR according to the repetition count and
1802              options.  */
1803           if (reps > options->repeat_count_threshold)
1804             {
1805               if (in_quotes)
1806                 {
1807                   if (options->inspect_it)
1808                     obstack_grow_wstr (&wchar_buf, LCST ("\\"));
1809                   obstack_grow (&wchar_buf, &wide_quote_char,
1810                                 sizeof (gdb_wchar_t));
1811                   obstack_grow_wstr (&wchar_buf, LCST (", "));
1812                   in_quotes = 0;
1813                 }
1814               obstack_grow_wstr (&wchar_buf, LCST ("'"));
1815               need_escape = 0;
1816               print_wchar (current_char, orig_buf, orig_len, width,
1817                            byte_order, &wchar_buf, '\'', &need_escape);
1818               obstack_grow_wstr (&wchar_buf, LCST ("'"));
1819               {
1820                 /* Painful gyrations.  */
1821                 int j;
1822                 char *s = xstrprintf (_(" <repeats %u times>"), reps);
1823
1824                 for (j = 0; s[j]; ++j)
1825                   {
1826                     gdb_wchar_t w = gdb_btowc (s[j]);
1827                     obstack_grow (&wchar_buf, &w, sizeof (gdb_wchar_t));
1828                   }
1829                 xfree (s);
1830               }
1831               things_printed += options->repeat_count_threshold;
1832               need_comma = 1;
1833             }
1834           else
1835             {
1836               /* Saw the character one or more times, but fewer than
1837                  the repetition threshold.  */
1838               if (!in_quotes)
1839                 {
1840                   if (options->inspect_it)
1841                     obstack_grow_wstr (&wchar_buf, LCST ("\\"));
1842                   obstack_grow (&wchar_buf, &wide_quote_char,
1843                                 sizeof (gdb_wchar_t));
1844                   in_quotes = 1;
1845                   need_escape = 0;
1846                 }
1847
1848               while (reps-- > 0)
1849                 {
1850                   print_wchar (current_char, orig_buf,
1851                                orig_len, width,
1852                                byte_order, &wchar_buf,
1853                                quote_char, &need_escape);
1854                   ++things_printed;
1855                 }
1856             }
1857         }
1858
1859       /* NUM_CHARS and the other outputs from wchar_iterate are valid
1860          here regardless of which branch was taken above.  */
1861       if (num_chars < 0)
1862         {
1863           /* Hit EOF.  */
1864           finished = 1;
1865           break;
1866         }
1867
1868       switch (result)
1869         {
1870         case wchar_iterate_invalid:
1871           if (!in_quotes)
1872             {
1873               if (options->inspect_it)
1874                 obstack_grow_wstr (&wchar_buf, LCST ("\\"));
1875               obstack_grow (&wchar_buf, &wide_quote_char,
1876                             sizeof (gdb_wchar_t));
1877               in_quotes = 1;
1878             }
1879           need_escape = 0;
1880           print_wchar (gdb_WEOF, buf, buflen, width, byte_order,
1881                        &wchar_buf, quote_char, &need_escape);
1882           break;
1883
1884         case wchar_iterate_incomplete:
1885           if (in_quotes)
1886             {
1887               if (options->inspect_it)
1888                 obstack_grow_wstr (&wchar_buf, LCST ("\\"));
1889               obstack_grow (&wchar_buf, &wide_quote_char,
1890                             sizeof (gdb_wchar_t));
1891               obstack_grow_wstr (&wchar_buf, LCST (","));
1892               in_quotes = 0;
1893             }
1894           obstack_grow_wstr (&wchar_buf,
1895                              LCST (" <incomplete sequence "));
1896           print_wchar (gdb_WEOF, buf, buflen, width,
1897                        byte_order, &wchar_buf,
1898                        0, &need_escape);
1899           obstack_grow_wstr (&wchar_buf, LCST (">"));
1900           finished = 1;
1901           break;
1902         }
1903     }
1904
1905   /* Terminate the quotes if necessary.  */
1906   if (in_quotes)
1907     {
1908       if (options->inspect_it)
1909         obstack_grow_wstr (&wchar_buf, LCST ("\\"));
1910       obstack_grow (&wchar_buf, &wide_quote_char,
1911                     sizeof (gdb_wchar_t));
1912     }
1913
1914   if (force_ellipses || !finished)
1915     obstack_grow_wstr (&wchar_buf, LCST ("..."));
1916
1917   /* OUTPUT is where we collect `char's for printing.  */
1918   obstack_init (&output);
1919   make_cleanup_obstack_free (&output);
1920
1921   convert_between_encodings (INTERMEDIATE_ENCODING, host_charset (),
1922                              obstack_base (&wchar_buf),
1923                              obstack_object_size (&wchar_buf),
1924                              1, &output, translit_char);
1925   obstack_1grow (&output, '\0');
1926
1927   fputs_filtered (obstack_base (&output), stream);
1928
1929   do_cleanups (cleanup);
1930 }
1931
1932 /* Print a string from the inferior, starting at ADDR and printing up to LEN
1933    characters, of WIDTH bytes a piece, to STREAM.  If LEN is -1, printing
1934    stops at the first null byte, otherwise printing proceeds (including null
1935    bytes) until either print_max or LEN characters have been printed,
1936    whichever is smaller.  ENCODING is the name of the string's
1937    encoding.  It can be NULL, in which case the target encoding is
1938    assumed.  */
1939
1940 int
1941 val_print_string (struct type *elttype, const char *encoding,
1942                   CORE_ADDR addr, int len,
1943                   struct ui_file *stream,
1944                   const struct value_print_options *options)
1945 {
1946   int force_ellipsis = 0;       /* Force ellipsis to be printed if nonzero.  */
1947   int errcode;                  /* Errno returned from bad reads.  */
1948   int found_nul;                /* Non-zero if we found the nul char.  */
1949   unsigned int fetchlimit;      /* Maximum number of chars to print.  */
1950   int bytes_read;
1951   gdb_byte *buffer = NULL;      /* Dynamically growable fetch buffer.  */
1952   struct cleanup *old_chain = NULL;     /* Top of the old cleanup chain.  */
1953   struct gdbarch *gdbarch = get_type_arch (elttype);
1954   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
1955   int width = TYPE_LENGTH (elttype);
1956
1957   /* First we need to figure out the limit on the number of characters we are
1958      going to attempt to fetch and print.  This is actually pretty simple.  If
1959      LEN >= zero, then the limit is the minimum of LEN and print_max.  If
1960      LEN is -1, then the limit is print_max.  This is true regardless of
1961      whether print_max is zero, UINT_MAX (unlimited), or something in between,
1962      because finding the null byte (or available memory) is what actually
1963      limits the fetch.  */
1964
1965   fetchlimit = (len == -1 ? options->print_max : min (len,
1966                                                       options->print_max));
1967
1968   errcode = read_string (addr, len, width, fetchlimit, byte_order,
1969                          &buffer, &bytes_read);
1970   old_chain = make_cleanup (xfree, buffer);
1971
1972   addr += bytes_read;
1973
1974   /* We now have either successfully filled the buffer to fetchlimit,
1975      or terminated early due to an error or finding a null char when
1976      LEN is -1.  */
1977
1978   /* Determine found_nul by looking at the last character read.  */
1979   found_nul = extract_unsigned_integer (buffer + bytes_read - width, width,
1980                                         byte_order) == 0;
1981   if (len == -1 && !found_nul)
1982     {
1983       gdb_byte *peekbuf;
1984
1985       /* We didn't find a NUL terminator we were looking for.  Attempt
1986          to peek at the next character.  If not successful, or it is not
1987          a null byte, then force ellipsis to be printed.  */
1988
1989       peekbuf = (gdb_byte *) alloca (width);
1990
1991       if (target_read_memory (addr, peekbuf, width) == 0
1992           && extract_unsigned_integer (peekbuf, width, byte_order) != 0)
1993         force_ellipsis = 1;
1994     }
1995   else if ((len >= 0 && errcode != 0) || (len > bytes_read / width))
1996     {
1997       /* Getting an error when we have a requested length, or fetching less
1998          than the number of characters actually requested, always make us
1999          print ellipsis.  */
2000       force_ellipsis = 1;
2001     }
2002
2003   /* If we get an error before fetching anything, don't print a string.
2004      But if we fetch something and then get an error, print the string
2005      and then the error message.  */
2006   if (errcode == 0 || bytes_read > 0)
2007     {
2008       if (options->addressprint)
2009         {
2010           fputs_filtered (" ", stream);
2011         }
2012       LA_PRINT_STRING (stream, elttype, buffer, bytes_read / width,
2013                        encoding, force_ellipsis, options);
2014     }
2015
2016   if (errcode != 0)
2017     {
2018       if (errcode == EIO)
2019         {
2020           fprintf_filtered (stream, " <Address ");
2021           fputs_filtered (paddress (gdbarch, addr), stream);
2022           fprintf_filtered (stream, " out of bounds>");
2023         }
2024       else
2025         {
2026           fprintf_filtered (stream, " <Error reading address ");
2027           fputs_filtered (paddress (gdbarch, addr), stream);
2028           fprintf_filtered (stream, ": %s>", safe_strerror (errcode));
2029         }
2030     }
2031
2032   gdb_flush (stream);
2033   do_cleanups (old_chain);
2034
2035   return (bytes_read / width);
2036 }
2037 \f
2038
2039 /* The 'set input-radix' command writes to this auxiliary variable.
2040    If the requested radix is valid, INPUT_RADIX is updated; otherwise,
2041    it is left unchanged.  */
2042
2043 static unsigned input_radix_1 = 10;
2044
2045 /* Validate an input or output radix setting, and make sure the user
2046    knows what they really did here.  Radix setting is confusing, e.g.
2047    setting the input radix to "10" never changes it!  */
2048
2049 static void
2050 set_input_radix (char *args, int from_tty, struct cmd_list_element *c)
2051 {
2052   set_input_radix_1 (from_tty, input_radix_1);
2053 }
2054
2055 static void
2056 set_input_radix_1 (int from_tty, unsigned radix)
2057 {
2058   /* We don't currently disallow any input radix except 0 or 1, which don't
2059      make any mathematical sense.  In theory, we can deal with any input
2060      radix greater than 1, even if we don't have unique digits for every
2061      value from 0 to radix-1, but in practice we lose on large radix values.
2062      We should either fix the lossage or restrict the radix range more.
2063      (FIXME).  */
2064
2065   if (radix < 2)
2066     {
2067       input_radix_1 = input_radix;
2068       error (_("Nonsense input radix ``decimal %u''; input radix unchanged."),
2069              radix);
2070     }
2071   input_radix_1 = input_radix = radix;
2072   if (from_tty)
2073     {
2074       printf_filtered (_("Input radix now set to "
2075                          "decimal %u, hex %x, octal %o.\n"),
2076                        radix, radix, radix);
2077     }
2078 }
2079
2080 /* The 'set output-radix' command writes to this auxiliary variable.
2081    If the requested radix is valid, OUTPUT_RADIX is updated,
2082    otherwise, it is left unchanged.  */
2083
2084 static unsigned output_radix_1 = 10;
2085
2086 static void
2087 set_output_radix (char *args, int from_tty, struct cmd_list_element *c)
2088 {
2089   set_output_radix_1 (from_tty, output_radix_1);
2090 }
2091
2092 static void
2093 set_output_radix_1 (int from_tty, unsigned radix)
2094 {
2095   /* Validate the radix and disallow ones that we aren't prepared to
2096      handle correctly, leaving the radix unchanged.  */
2097   switch (radix)
2098     {
2099     case 16:
2100       user_print_options.output_format = 'x';   /* hex */
2101       break;
2102     case 10:
2103       user_print_options.output_format = 0;     /* decimal */
2104       break;
2105     case 8:
2106       user_print_options.output_format = 'o';   /* octal */
2107       break;
2108     default:
2109       output_radix_1 = output_radix;
2110       error (_("Unsupported output radix ``decimal %u''; "
2111                "output radix unchanged."),
2112              radix);
2113     }
2114   output_radix_1 = output_radix = radix;
2115   if (from_tty)
2116     {
2117       printf_filtered (_("Output radix now set to "
2118                          "decimal %u, hex %x, octal %o.\n"),
2119                        radix, radix, radix);
2120     }
2121 }
2122
2123 /* Set both the input and output radix at once.  Try to set the output radix
2124    first, since it has the most restrictive range.  An radix that is valid as
2125    an output radix is also valid as an input radix.
2126
2127    It may be useful to have an unusual input radix.  If the user wishes to
2128    set an input radix that is not valid as an output radix, he needs to use
2129    the 'set input-radix' command.  */
2130
2131 static void
2132 set_radix (char *arg, int from_tty)
2133 {
2134   unsigned radix;
2135
2136   radix = (arg == NULL) ? 10 : parse_and_eval_long (arg);
2137   set_output_radix_1 (0, radix);
2138   set_input_radix_1 (0, radix);
2139   if (from_tty)
2140     {
2141       printf_filtered (_("Input and output radices now set to "
2142                          "decimal %u, hex %x, octal %o.\n"),
2143                        radix, radix, radix);
2144     }
2145 }
2146
2147 /* Show both the input and output radices.  */
2148
2149 static void
2150 show_radix (char *arg, int from_tty)
2151 {
2152   if (from_tty)
2153     {
2154       if (input_radix == output_radix)
2155         {
2156           printf_filtered (_("Input and output radices set to "
2157                              "decimal %u, hex %x, octal %o.\n"),
2158                            input_radix, input_radix, input_radix);
2159         }
2160       else
2161         {
2162           printf_filtered (_("Input radix set to decimal "
2163                              "%u, hex %x, octal %o.\n"),
2164                            input_radix, input_radix, input_radix);
2165           printf_filtered (_("Output radix set to decimal "
2166                              "%u, hex %x, octal %o.\n"),
2167                            output_radix, output_radix, output_radix);
2168         }
2169     }
2170 }
2171 \f
2172
2173 static void
2174 set_print (char *arg, int from_tty)
2175 {
2176   printf_unfiltered (
2177      "\"set print\" must be followed by the name of a print subcommand.\n");
2178   help_list (setprintlist, "set print ", -1, gdb_stdout);
2179 }
2180
2181 static void
2182 show_print (char *args, int from_tty)
2183 {
2184   cmd_show_list (showprintlist, from_tty, "");
2185 }
2186 \f
2187 void
2188 _initialize_valprint (void)
2189 {
2190   add_prefix_cmd ("print", no_class, set_print,
2191                   _("Generic command for setting how things print."),
2192                   &setprintlist, "set print ", 0, &setlist);
2193   add_alias_cmd ("p", "print", no_class, 1, &setlist);
2194   /* Prefer set print to set prompt.  */
2195   add_alias_cmd ("pr", "print", no_class, 1, &setlist);
2196
2197   add_prefix_cmd ("print", no_class, show_print,
2198                   _("Generic command for showing print settings."),
2199                   &showprintlist, "show print ", 0, &showlist);
2200   add_alias_cmd ("p", "print", no_class, 1, &showlist);
2201   add_alias_cmd ("pr", "print", no_class, 1, &showlist);
2202
2203   add_setshow_uinteger_cmd ("elements", no_class,
2204                             &user_print_options.print_max, _("\
2205 Set limit on string chars or array elements to print."), _("\
2206 Show limit on string chars or array elements to print."), _("\
2207 \"set print elements 0\" causes there to be no limit."),
2208                             NULL,
2209                             show_print_max,
2210                             &setprintlist, &showprintlist);
2211
2212   add_setshow_boolean_cmd ("null-stop", no_class,
2213                            &user_print_options.stop_print_at_null, _("\
2214 Set printing of char arrays to stop at first null char."), _("\
2215 Show printing of char arrays to stop at first null char."), NULL,
2216                            NULL,
2217                            show_stop_print_at_null,
2218                            &setprintlist, &showprintlist);
2219
2220   add_setshow_uinteger_cmd ("repeats", no_class,
2221                             &user_print_options.repeat_count_threshold, _("\
2222 Set threshold for repeated print elements."), _("\
2223 Show threshold for repeated print elements."), _("\
2224 \"set print repeats 0\" causes all elements to be individually printed."),
2225                             NULL,
2226                             show_repeat_count_threshold,
2227                             &setprintlist, &showprintlist);
2228
2229   add_setshow_boolean_cmd ("pretty", class_support,
2230                            &user_print_options.prettyprint_structs, _("\
2231 Set prettyprinting of structures."), _("\
2232 Show prettyprinting of structures."), NULL,
2233                            NULL,
2234                            show_prettyprint_structs,
2235                            &setprintlist, &showprintlist);
2236
2237   add_setshow_boolean_cmd ("union", class_support,
2238                            &user_print_options.unionprint, _("\
2239 Set printing of unions interior to structures."), _("\
2240 Show printing of unions interior to structures."), NULL,
2241                            NULL,
2242                            show_unionprint,
2243                            &setprintlist, &showprintlist);
2244
2245   add_setshow_boolean_cmd ("array", class_support,
2246                            &user_print_options.prettyprint_arrays, _("\
2247 Set prettyprinting of arrays."), _("\
2248 Show prettyprinting of arrays."), NULL,
2249                            NULL,
2250                            show_prettyprint_arrays,
2251                            &setprintlist, &showprintlist);
2252
2253   add_setshow_boolean_cmd ("address", class_support,
2254                            &user_print_options.addressprint, _("\
2255 Set printing of addresses."), _("\
2256 Show printing of addresses."), NULL,
2257                            NULL,
2258                            show_addressprint,
2259                            &setprintlist, &showprintlist);
2260
2261   add_setshow_zuinteger_cmd ("input-radix", class_support, &input_radix_1,
2262                              _("\
2263 Set default input radix for entering numbers."), _("\
2264 Show default input radix for entering numbers."), NULL,
2265                              set_input_radix,
2266                              show_input_radix,
2267                              &setlist, &showlist);
2268
2269   add_setshow_zuinteger_cmd ("output-radix", class_support, &output_radix_1,
2270                              _("\
2271 Set default output radix for printing of values."), _("\
2272 Show default output radix for printing of values."), NULL,
2273                              set_output_radix,
2274                              show_output_radix,
2275                              &setlist, &showlist);
2276
2277   /* The "set radix" and "show radix" commands are special in that
2278      they are like normal set and show commands but allow two normally
2279      independent variables to be either set or shown with a single
2280      command.  So the usual deprecated_add_set_cmd() and [deleted]
2281      add_show_from_set() commands aren't really appropriate.  */
2282   /* FIXME: i18n: With the new add_setshow_integer command, that is no
2283      longer true - show can display anything.  */
2284   add_cmd ("radix", class_support, set_radix, _("\
2285 Set default input and output number radices.\n\
2286 Use 'set input-radix' or 'set output-radix' to independently set each.\n\
2287 Without an argument, sets both radices back to the default value of 10."),
2288            &setlist);
2289   add_cmd ("radix", class_support, show_radix, _("\
2290 Show the default input and output number radices.\n\
2291 Use 'show input-radix' or 'show output-radix' to independently show each."),
2292            &showlist);
2293
2294   add_setshow_boolean_cmd ("array-indexes", class_support,
2295                            &user_print_options.print_array_indexes, _("\
2296 Set printing of array indexes."), _("\
2297 Show printing of array indexes"), NULL, NULL, show_print_array_indexes,
2298                            &setprintlist, &showprintlist);
2299 }