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