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