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