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