Remove obsolete TYPE_FLAG_... values
[external/binutils.git] / gdb / valprint.c
1 /* Print values for GDB, the GNU debugger.
2
3    Copyright (C) 1986-2016 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 "symtab.h"
22 #include "gdbtypes.h"
23 #include "value.h"
24 #include "gdbcore.h"
25 #include "gdbcmd.h"
26 #include "target.h"
27 #include "language.h"
28 #include "annotate.h"
29 #include "valprint.h"
30 #include "floatformat.h"
31 #include "doublest.h"
32 #include "dfp.h"
33 #include "extension.h"
34 #include "ada-lang.h"
35 #include "gdb_obstack.h"
36 #include "charset.h"
37 #include "typeprint.h"
38 #include <ctype.h>
39
40 /* Maximum number of wchars returned from wchar_iterate.  */
41 #define MAX_WCHARS 4
42
43 /* A convenience macro to compute the size of a wchar_t buffer containing X
44    characters.  */
45 #define WCHAR_BUFLEN(X) ((X) * sizeof (gdb_wchar_t))
46
47 /* Character buffer size saved while iterating over wchars.  */
48 #define WCHAR_BUFLEN_MAX WCHAR_BUFLEN (MAX_WCHARS)
49
50 /* A structure to encapsulate state information from iterated
51    character conversions.  */
52 struct converted_character
53 {
54   /* The number of characters converted.  */
55   int num_chars;
56
57   /* The result of the conversion.  See charset.h for more.  */
58   enum wchar_iterate_result result;
59
60   /* The (saved) converted character(s).  */
61   gdb_wchar_t chars[WCHAR_BUFLEN_MAX];
62
63   /* The first converted target byte.  */
64   const gdb_byte *buf;
65
66   /* The number of bytes converted.  */
67   size_t buflen;
68
69   /* How many times this character(s) is repeated.  */
70   int repeat_count;
71 };
72
73 typedef struct converted_character converted_character_d;
74 DEF_VEC_O (converted_character_d);
75
76 /* Command lists for set/show print raw.  */
77 struct cmd_list_element *setprintrawlist;
78 struct cmd_list_element *showprintrawlist;
79
80 /* Prototypes for local functions */
81
82 static int partial_memory_read (CORE_ADDR memaddr, gdb_byte *myaddr,
83                                 int len, int *errptr);
84
85 static void show_print (char *, int);
86
87 static void set_print (char *, int);
88
89 static void set_radix (char *, int);
90
91 static void show_radix (char *, int);
92
93 static void set_input_radix (char *, int, struct cmd_list_element *);
94
95 static void set_input_radix_1 (int, unsigned);
96
97 static void set_output_radix (char *, int, struct cmd_list_element *);
98
99 static void set_output_radix_1 (int, unsigned);
100
101 static void val_print_type_code_flags (struct type *type,
102                                        const gdb_byte *valaddr,
103                                        struct ui_file *stream);
104
105 void _initialize_valprint (void);
106
107 #define PRINT_MAX_DEFAULT 200   /* Start print_max off at this value.  */
108
109 struct value_print_options user_print_options =
110 {
111   Val_prettyformat_default,     /* prettyformat */
112   0,                            /* prettyformat_arrays */
113   0,                            /* prettyformat_structs */
114   0,                            /* vtblprint */
115   1,                            /* unionprint */
116   1,                            /* addressprint */
117   0,                            /* objectprint */
118   PRINT_MAX_DEFAULT,            /* print_max */
119   10,                           /* repeat_count_threshold */
120   0,                            /* output_format */
121   0,                            /* format */
122   0,                            /* stop_print_at_null */
123   0,                            /* print_array_indexes */
124   0,                            /* deref_ref */
125   1,                            /* static_field_print */
126   1,                            /* pascal_static_field_print */
127   0,                            /* raw */
128   0,                            /* summary */
129   1                             /* symbol_print */
130 };
131
132 /* Initialize *OPTS to be a copy of the user print options.  */
133 void
134 get_user_print_options (struct value_print_options *opts)
135 {
136   *opts = user_print_options;
137 }
138
139 /* Initialize *OPTS to be a copy of the user print options, but with
140    pretty-formatting disabled.  */
141 void
142 get_no_prettyformat_print_options (struct value_print_options *opts)
143 {  
144   *opts = user_print_options;
145   opts->prettyformat = Val_no_prettyformat;
146 }
147
148 /* Initialize *OPTS to be a copy of the user print options, but using
149    FORMAT as the formatting option.  */
150 void
151 get_formatted_print_options (struct value_print_options *opts,
152                              char format)
153 {
154   *opts = user_print_options;
155   opts->format = format;
156 }
157
158 static void
159 show_print_max (struct ui_file *file, int from_tty,
160                 struct cmd_list_element *c, const char *value)
161 {
162   fprintf_filtered (file,
163                     _("Limit on string chars or array "
164                       "elements to print is %s.\n"),
165                     value);
166 }
167
168
169 /* Default input and output radixes, and output format letter.  */
170
171 unsigned input_radix = 10;
172 static void
173 show_input_radix (struct ui_file *file, int from_tty,
174                   struct cmd_list_element *c, const char *value)
175 {
176   fprintf_filtered (file,
177                     _("Default input radix for entering numbers is %s.\n"),
178                     value);
179 }
180
181 unsigned output_radix = 10;
182 static void
183 show_output_radix (struct ui_file *file, int from_tty,
184                    struct cmd_list_element *c, const char *value)
185 {
186   fprintf_filtered (file,
187                     _("Default output radix for printing of values is %s.\n"),
188                     value);
189 }
190
191 /* By default we print arrays without printing the index of each element in
192    the array.  This behavior can be changed by setting PRINT_ARRAY_INDEXES.  */
193
194 static void
195 show_print_array_indexes (struct ui_file *file, int from_tty,
196                           struct cmd_list_element *c, const char *value)
197 {
198   fprintf_filtered (file, _("Printing of array indexes is %s.\n"), value);
199 }
200
201 /* Print repeat counts if there are more than this many repetitions of an
202    element in an array.  Referenced by the low level language dependent
203    print routines.  */
204
205 static void
206 show_repeat_count_threshold (struct ui_file *file, int from_tty,
207                              struct cmd_list_element *c, const char *value)
208 {
209   fprintf_filtered (file, _("Threshold for repeated print elements is %s.\n"),
210                     value);
211 }
212
213 /* If nonzero, stops printing of char arrays at first null.  */
214
215 static void
216 show_stop_print_at_null (struct ui_file *file, int from_tty,
217                          struct cmd_list_element *c, const char *value)
218 {
219   fprintf_filtered (file,
220                     _("Printing of char arrays to stop "
221                       "at first null char is %s.\n"),
222                     value);
223 }
224
225 /* Controls pretty printing of structures.  */
226
227 static void
228 show_prettyformat_structs (struct ui_file *file, int from_tty,
229                           struct cmd_list_element *c, const char *value)
230 {
231   fprintf_filtered (file, _("Pretty formatting of structures is %s.\n"), value);
232 }
233
234 /* Controls pretty printing of arrays.  */
235
236 static void
237 show_prettyformat_arrays (struct ui_file *file, int from_tty,
238                          struct cmd_list_element *c, const char *value)
239 {
240   fprintf_filtered (file, _("Pretty formatting of arrays is %s.\n"), value);
241 }
242
243 /* If nonzero, causes unions inside structures or other unions to be
244    printed.  */
245
246 static void
247 show_unionprint (struct ui_file *file, int from_tty,
248                  struct cmd_list_element *c, const char *value)
249 {
250   fprintf_filtered (file,
251                     _("Printing of unions interior to structures is %s.\n"),
252                     value);
253 }
254
255 /* If nonzero, causes machine addresses to be printed in certain contexts.  */
256
257 static void
258 show_addressprint (struct ui_file *file, int from_tty,
259                    struct cmd_list_element *c, const char *value)
260 {
261   fprintf_filtered (file, _("Printing of addresses is %s.\n"), value);
262 }
263
264 static void
265 show_symbol_print (struct ui_file *file, int from_tty,
266                    struct cmd_list_element *c, const char *value)
267 {
268   fprintf_filtered (file,
269                     _("Printing of symbols when printing pointers is %s.\n"),
270                     value);
271 }
272
273 \f
274
275 /* A helper function for val_print.  When printing in "summary" mode,
276    we want to print scalar arguments, but not aggregate arguments.
277    This function distinguishes between the two.  */
278
279 int
280 val_print_scalar_type_p (struct type *type)
281 {
282   type = check_typedef (type);
283   while (TYPE_CODE (type) == TYPE_CODE_REF)
284     {
285       type = TYPE_TARGET_TYPE (type);
286       type = check_typedef (type);
287     }
288   switch (TYPE_CODE (type))
289     {
290     case TYPE_CODE_ARRAY:
291     case TYPE_CODE_STRUCT:
292     case TYPE_CODE_UNION:
293     case TYPE_CODE_SET:
294     case TYPE_CODE_STRING:
295       return 0;
296     default:
297       return 1;
298     }
299 }
300
301 /* See its definition in value.h.  */
302
303 int
304 valprint_check_validity (struct ui_file *stream,
305                          struct type *type,
306                          LONGEST embedded_offset,
307                          const struct value *val)
308 {
309   type = check_typedef (type);
310
311   if (type_not_associated (type))
312     {
313       val_print_not_associated (stream);
314       return 0;
315     }
316
317   if (type_not_allocated (type))
318     {
319       val_print_not_allocated (stream);
320       return 0;
321     }
322
323   if (TYPE_CODE (type) != TYPE_CODE_UNION
324       && TYPE_CODE (type) != TYPE_CODE_STRUCT
325       && TYPE_CODE (type) != TYPE_CODE_ARRAY)
326     {
327       if (value_bits_any_optimized_out (val,
328                                         TARGET_CHAR_BIT * embedded_offset,
329                                         TARGET_CHAR_BIT * TYPE_LENGTH (type)))
330         {
331           val_print_optimized_out (val, stream);
332           return 0;
333         }
334
335       if (value_bits_synthetic_pointer (val, TARGET_CHAR_BIT * embedded_offset,
336                                         TARGET_CHAR_BIT * TYPE_LENGTH (type)))
337         {
338           const int is_ref = TYPE_CODE (type) == TYPE_CODE_REF;
339           int ref_is_addressable = 0;
340
341           if (is_ref)
342             {
343               const struct value *deref_val = coerce_ref_if_computed (val);
344
345               if (deref_val != NULL)
346                 ref_is_addressable = value_lval_const (deref_val) == lval_memory;
347             }
348
349           if (!is_ref || !ref_is_addressable)
350             fputs_filtered (_("<synthetic pointer>"), stream);
351
352           /* C++ references should be valid even if they're synthetic.  */
353           return is_ref;
354         }
355
356       if (!value_bytes_available (val, embedded_offset, TYPE_LENGTH (type)))
357         {
358           val_print_unavailable (stream);
359           return 0;
360         }
361     }
362
363   return 1;
364 }
365
366 void
367 val_print_optimized_out (const struct value *val, struct ui_file *stream)
368 {
369   if (val != NULL && value_lval_const (val) == lval_register)
370     val_print_not_saved (stream);
371   else
372     fprintf_filtered (stream, _("<optimized out>"));
373 }
374
375 void
376 val_print_not_saved (struct ui_file *stream)
377 {
378   fprintf_filtered (stream, _("<not saved>"));
379 }
380
381 void
382 val_print_unavailable (struct ui_file *stream)
383 {
384   fprintf_filtered (stream, _("<unavailable>"));
385 }
386
387 void
388 val_print_invalid_address (struct ui_file *stream)
389 {
390   fprintf_filtered (stream, _("<invalid address>"));
391 }
392
393 /* Print a pointer based on the type of its target.
394
395    Arguments to this functions are roughly the same as those in
396    generic_val_print.  A difference is that ADDRESS is the address to print,
397    with embedded_offset already added.  ELTTYPE represents
398    the pointed type after check_typedef.  */
399
400 static void
401 print_unpacked_pointer (struct type *type, struct type *elttype,
402                         CORE_ADDR address, struct ui_file *stream,
403                         const struct value_print_options *options)
404 {
405   struct gdbarch *gdbarch = get_type_arch (type);
406
407   if (TYPE_CODE (elttype) == TYPE_CODE_FUNC)
408     {
409       /* Try to print what function it points to.  */
410       print_function_pointer_address (options, gdbarch, address, stream);
411       return;
412     }
413
414   if (options->symbol_print)
415     print_address_demangle (options, gdbarch, address, stream, demangle);
416   else if (options->addressprint)
417     fputs_filtered (paddress (gdbarch, address), stream);
418 }
419
420 /* generic_val_print helper for TYPE_CODE_ARRAY.  */
421
422 static void
423 generic_val_print_array (struct type *type, const gdb_byte *valaddr,
424                          int embedded_offset, CORE_ADDR address,
425                          struct ui_file *stream, int recurse,
426                          const struct value *original_value,
427                          const struct value_print_options *options,
428                          const struct
429                              generic_val_print_decorations *decorations)
430 {
431   struct type *unresolved_elttype = TYPE_TARGET_TYPE (type);
432   struct type *elttype = check_typedef (unresolved_elttype);
433
434   if (TYPE_LENGTH (type) > 0 && TYPE_LENGTH (unresolved_elttype) > 0)
435     {
436       LONGEST low_bound, high_bound;
437
438       if (!get_array_bounds (type, &low_bound, &high_bound))
439         error (_("Could not determine the array high bound"));
440
441       if (options->prettyformat_arrays)
442         {
443           print_spaces_filtered (2 + 2 * recurse, stream);
444         }
445
446       fputs_filtered (decorations->array_start, stream);
447       val_print_array_elements (type, valaddr, embedded_offset,
448                                 address, stream,
449                                 recurse, original_value, options, 0);
450       fputs_filtered (decorations->array_end, stream);
451     }
452   else
453     {
454       /* Array of unspecified length: treat like pointer to first elt.  */
455       print_unpacked_pointer (type, elttype, address + embedded_offset, stream,
456                               options);
457     }
458
459 }
460
461 /* generic_val_print helper for TYPE_CODE_PTR.  */
462
463 static void
464 generic_val_print_ptr (struct type *type, const gdb_byte *valaddr,
465                        int embedded_offset, struct ui_file *stream,
466                        const struct value *original_value,
467                        const struct value_print_options *options)
468 {
469   struct gdbarch *gdbarch = get_type_arch (type);
470   int unit_size = gdbarch_addressable_memory_unit_size (gdbarch);
471
472   if (options->format && options->format != 's')
473     {
474       val_print_scalar_formatted (type, valaddr, embedded_offset,
475                                   original_value, options, 0, stream);
476     }
477   else
478     {
479       struct type *unresolved_elttype = TYPE_TARGET_TYPE(type);
480       struct type *elttype = check_typedef (unresolved_elttype);
481       CORE_ADDR addr = unpack_pointer (type,
482                                        valaddr + embedded_offset * unit_size);
483
484       print_unpacked_pointer (type, elttype, addr, stream, options);
485     }
486 }
487
488
489 /* generic_val_print helper for TYPE_CODE_MEMBERPTR.  */
490
491 static void
492 generic_val_print_memberptr (struct type *type, const gdb_byte *valaddr,
493                              int embedded_offset, struct ui_file *stream,
494                              const struct value *original_value,
495                              const struct value_print_options *options)
496 {
497   val_print_scalar_formatted (type, valaddr, embedded_offset,
498                               original_value, options, 0, stream);
499 }
500
501 /* Print '@' followed by the address contained in ADDRESS_BUFFER.  */
502
503 static void
504 print_ref_address (struct type *type, const gdb_byte *address_buffer,
505                   int embedded_offset, struct ui_file *stream)
506 {
507   struct gdbarch *gdbarch = get_type_arch (type);
508
509   if (address_buffer != NULL)
510     {
511       CORE_ADDR address
512         = extract_typed_address (address_buffer + embedded_offset, type);
513
514       fprintf_filtered (stream, "@");
515       fputs_filtered (paddress (gdbarch, address), stream);
516     }
517   /* Else: we have a non-addressable value, such as a DW_AT_const_value.  */
518 }
519
520 /* If VAL is addressable, return the value contents buffer of a value that
521    represents a pointer to VAL.  Otherwise return NULL.  */
522
523 static const gdb_byte *
524 get_value_addr_contents (struct value *deref_val)
525 {
526   gdb_assert (deref_val != NULL);
527
528   if (value_lval_const (deref_val) == lval_memory)
529     return value_contents_for_printing_const (value_addr (deref_val));
530   else
531     {
532       /* We have a non-addressable value, such as a DW_AT_const_value.  */
533       return NULL;
534     }
535 }
536
537 /* generic_val_print helper for TYPE_CODE_REF.  */
538
539 static void
540 generic_val_print_ref (struct type *type, const gdb_byte *valaddr,
541                        int embedded_offset, struct ui_file *stream, int recurse,
542                        const struct value *original_value,
543                        const struct value_print_options *options)
544 {
545   struct type *elttype = check_typedef (TYPE_TARGET_TYPE (type));
546   struct value *deref_val = NULL;
547   const int value_is_synthetic
548     = value_bits_synthetic_pointer (original_value,
549                                     TARGET_CHAR_BIT * embedded_offset,
550                                     TARGET_CHAR_BIT * TYPE_LENGTH (type));
551   const int must_coerce_ref = ((options->addressprint && value_is_synthetic)
552                                || options->deref_ref);
553   const int type_is_defined = TYPE_CODE (elttype) != TYPE_CODE_UNDEF;
554
555   if (must_coerce_ref && type_is_defined)
556     {
557       deref_val = coerce_ref_if_computed (original_value);
558
559       if (deref_val != NULL)
560         {
561           /* More complicated computed references are not supported.  */
562           gdb_assert (embedded_offset == 0);
563         }
564       else
565         deref_val = value_at (TYPE_TARGET_TYPE (type),
566                               unpack_pointer (type, valaddr + embedded_offset));
567     }
568   /* Else, original_value isn't a synthetic reference or we don't have to print
569      the reference's contents.
570
571      Notice that for references to TYPE_CODE_STRUCT, 'set print object on' will
572      cause original_value to be a not_lval instead of an lval_computed,
573      which will make value_bits_synthetic_pointer return false.
574      This happens because if options->objectprint is true, c_value_print will
575      overwrite original_value's contents with the result of coercing
576      the reference through value_addr, and then set its type back to
577      TYPE_CODE_REF.  In that case we don't have to coerce the reference again;
578      we can simply treat it as non-synthetic and move on.  */
579
580   if (options->addressprint)
581     {
582       const gdb_byte *address = (value_is_synthetic && type_is_defined
583                                  ? get_value_addr_contents (deref_val)
584                                  : valaddr);
585
586       print_ref_address (type, address, embedded_offset, stream);
587
588       if (options->deref_ref)
589         fputs_filtered (": ", stream);
590     }
591
592   if (options->deref_ref)
593     {
594       if (type_is_defined)
595         common_val_print (deref_val, stream, recurse, options,
596                           current_language);
597       else
598         fputs_filtered ("???", stream);
599     }
600 }
601
602 /* Helper function for generic_val_print_enum.
603    This is also used to print enums in TYPE_CODE_FLAGS values.  */
604
605 static void
606 generic_val_print_enum_1 (struct type *type, LONGEST val,
607                           struct ui_file *stream)
608 {
609   unsigned int i;
610   unsigned int len;
611
612   len = TYPE_NFIELDS (type);
613   for (i = 0; i < len; i++)
614     {
615       QUIT;
616       if (val == TYPE_FIELD_ENUMVAL (type, i))
617         {
618           break;
619         }
620     }
621   if (i < len)
622     {
623       fputs_filtered (TYPE_FIELD_NAME (type, i), stream);
624     }
625   else if (TYPE_FLAG_ENUM (type))
626     {
627       int first = 1;
628
629       /* We have a "flag" enum, so we try to decompose it into
630          pieces as appropriate.  A flag enum has disjoint
631          constants by definition.  */
632       fputs_filtered ("(", stream);
633       for (i = 0; i < len; ++i)
634         {
635           QUIT;
636
637           if ((val & TYPE_FIELD_ENUMVAL (type, i)) != 0)
638             {
639               if (!first)
640                 fputs_filtered (" | ", stream);
641               first = 0;
642
643               val &= ~TYPE_FIELD_ENUMVAL (type, i);
644               fputs_filtered (TYPE_FIELD_NAME (type, i), stream);
645             }
646         }
647
648       if (first || val != 0)
649         {
650           if (!first)
651             fputs_filtered (" | ", stream);
652           fputs_filtered ("unknown: ", stream);
653           print_longest (stream, 'd', 0, val);
654         }
655
656       fputs_filtered (")", stream);
657     }
658   else
659     print_longest (stream, 'd', 0, val);
660 }
661
662 /* generic_val_print helper for TYPE_CODE_ENUM.  */
663
664 static void
665 generic_val_print_enum (struct type *type, const gdb_byte *valaddr,
666                         int embedded_offset, struct ui_file *stream,
667                         const struct value *original_value,
668                         const struct value_print_options *options)
669 {
670   LONGEST val;
671   struct gdbarch *gdbarch = get_type_arch (type);
672   int unit_size = gdbarch_addressable_memory_unit_size (gdbarch);
673
674   if (options->format)
675     {
676       val_print_scalar_formatted (type, valaddr, embedded_offset,
677                                   original_value, options, 0, stream);
678       return;
679     }
680   val = unpack_long (type, valaddr + embedded_offset * unit_size);
681
682   generic_val_print_enum_1 (type, val, stream);
683 }
684
685 /* generic_val_print helper for TYPE_CODE_FLAGS.  */
686
687 static void
688 generic_val_print_flags (struct type *type, const gdb_byte *valaddr,
689                          int embedded_offset, struct ui_file *stream,
690                          const struct value *original_value,
691                          const struct value_print_options *options)
692
693 {
694   if (options->format)
695     val_print_scalar_formatted (type, valaddr, embedded_offset, original_value,
696                                 options, 0, stream);
697   else
698     val_print_type_code_flags (type, valaddr + embedded_offset, stream);
699 }
700
701 /* generic_val_print helper for TYPE_CODE_FUNC and TYPE_CODE_METHOD.  */
702
703 static void
704 generic_val_print_func (struct type *type, const gdb_byte *valaddr,
705                         int embedded_offset, CORE_ADDR address,
706                         struct ui_file *stream,
707                         const struct value *original_value,
708                         const struct value_print_options *options)
709 {
710   struct gdbarch *gdbarch = get_type_arch (type);
711
712   if (options->format)
713     {
714       val_print_scalar_formatted (type, valaddr, embedded_offset,
715                                   original_value, options, 0, stream);
716     }
717   else
718     {
719       /* FIXME, we should consider, at least for ANSI C language,
720          eliminating the distinction made between FUNCs and POINTERs
721          to FUNCs.  */
722       fprintf_filtered (stream, "{");
723       type_print (type, "", stream, -1);
724       fprintf_filtered (stream, "} ");
725       /* Try to print what function it points to, and its address.  */
726       print_address_demangle (options, gdbarch, address, stream, demangle);
727     }
728 }
729
730 /* generic_val_print helper for TYPE_CODE_BOOL.  */
731
732 static void
733 generic_val_print_bool (struct type *type, const gdb_byte *valaddr,
734                         int embedded_offset, struct ui_file *stream,
735                         const struct value *original_value,
736                         const struct value_print_options *options,
737                         const struct generic_val_print_decorations *decorations)
738 {
739   LONGEST val;
740   struct gdbarch *gdbarch = get_type_arch (type);
741   int unit_size = gdbarch_addressable_memory_unit_size (gdbarch);
742
743   if (options->format || options->output_format)
744     {
745       struct value_print_options opts = *options;
746       opts.format = (options->format ? options->format
747                      : options->output_format);
748       val_print_scalar_formatted (type, valaddr, embedded_offset,
749                                   original_value, &opts, 0, stream);
750     }
751   else
752     {
753       val = unpack_long (type, valaddr + embedded_offset * unit_size);
754       if (val == 0)
755         fputs_filtered (decorations->false_name, stream);
756       else if (val == 1)
757         fputs_filtered (decorations->true_name, stream);
758       else
759         print_longest (stream, 'd', 0, val);
760     }
761 }
762
763 /* generic_val_print helper for TYPE_CODE_INT.  */
764
765 static void
766 generic_val_print_int (struct type *type, const gdb_byte *valaddr,
767                        int embedded_offset, struct ui_file *stream,
768                        const struct value *original_value,
769                        const struct value_print_options *options)
770 {
771   struct gdbarch *gdbarch = get_type_arch (type);
772   int unit_size = gdbarch_addressable_memory_unit_size (gdbarch);
773
774   if (options->format || options->output_format)
775     {
776       struct value_print_options opts = *options;
777
778       opts.format = (options->format ? options->format
779                      : options->output_format);
780       val_print_scalar_formatted (type, valaddr, embedded_offset,
781                                   original_value, &opts, 0, stream);
782     }
783   else
784     val_print_type_code_int (type, valaddr + embedded_offset * unit_size,
785                              stream);
786 }
787
788 /* generic_val_print helper for TYPE_CODE_CHAR.  */
789
790 static void
791 generic_val_print_char (struct type *type, struct type *unresolved_type,
792                         const gdb_byte *valaddr, int embedded_offset,
793                         struct ui_file *stream,
794                         const struct value *original_value,
795                         const struct value_print_options *options)
796 {
797   LONGEST val;
798   struct gdbarch *gdbarch = get_type_arch (type);
799   int unit_size = gdbarch_addressable_memory_unit_size (gdbarch);
800
801   if (options->format || options->output_format)
802     {
803       struct value_print_options opts = *options;
804
805       opts.format = (options->format ? options->format
806                      : options->output_format);
807       val_print_scalar_formatted (type, valaddr, embedded_offset,
808                                   original_value, &opts, 0, stream);
809     }
810   else
811     {
812       val = unpack_long (type, valaddr + embedded_offset * unit_size);
813       if (TYPE_UNSIGNED (type))
814         fprintf_filtered (stream, "%u", (unsigned int) val);
815       else
816         fprintf_filtered (stream, "%d", (int) val);
817       fputs_filtered (" ", stream);
818       LA_PRINT_CHAR (val, unresolved_type, stream);
819     }
820 }
821
822 /* generic_val_print helper for TYPE_CODE_FLT.  */
823
824 static void
825 generic_val_print_float (struct type *type, const gdb_byte *valaddr,
826                          int embedded_offset, struct ui_file *stream,
827                          const struct value *original_value,
828                          const struct value_print_options *options)
829 {
830   struct gdbarch *gdbarch = get_type_arch (type);
831   int unit_size = gdbarch_addressable_memory_unit_size (gdbarch);
832
833   if (options->format)
834     {
835       val_print_scalar_formatted (type, valaddr, embedded_offset,
836                                   original_value, options, 0, stream);
837     }
838   else
839     {
840       print_floating (valaddr + embedded_offset * unit_size, type, stream);
841     }
842 }
843
844 /* generic_val_print helper for TYPE_CODE_DECFLOAT.  */
845
846 static void
847 generic_val_print_decfloat (struct type *type, const gdb_byte *valaddr,
848                             int embedded_offset, struct ui_file *stream,
849                             const struct value *original_value,
850                             const struct value_print_options *options)
851 {
852   struct gdbarch *gdbarch = get_type_arch (type);
853   int unit_size = gdbarch_addressable_memory_unit_size (gdbarch);
854
855   if (options->format)
856     val_print_scalar_formatted (type, valaddr, embedded_offset, original_value,
857                                 options, 0, stream);
858   else
859     print_decimal_floating (valaddr + embedded_offset * unit_size, type,
860                             stream);
861 }
862
863 /* generic_val_print helper for TYPE_CODE_COMPLEX.  */
864
865 static void
866 generic_val_print_complex (struct type *type, const gdb_byte *valaddr,
867                            int embedded_offset, struct ui_file *stream,
868                            const struct value *original_value,
869                            const struct value_print_options *options,
870                            const struct generic_val_print_decorations
871                              *decorations)
872 {
873   struct gdbarch *gdbarch = get_type_arch (type);
874   int unit_size = gdbarch_addressable_memory_unit_size (gdbarch);
875
876   fprintf_filtered (stream, "%s", decorations->complex_prefix);
877   if (options->format)
878     val_print_scalar_formatted (TYPE_TARGET_TYPE (type), valaddr,
879                                 embedded_offset, original_value, options, 0,
880                                 stream);
881   else
882     print_floating (valaddr + embedded_offset * unit_size,
883                     TYPE_TARGET_TYPE (type), stream);
884   fprintf_filtered (stream, "%s", decorations->complex_infix);
885   if (options->format)
886     val_print_scalar_formatted (TYPE_TARGET_TYPE (type), valaddr,
887                                 embedded_offset
888                                 + type_length_units (TYPE_TARGET_TYPE (type)),
889                                 original_value, options, 0, stream);
890   else
891     print_floating (valaddr + embedded_offset * unit_size
892                     + TYPE_LENGTH (TYPE_TARGET_TYPE (type)),
893                     TYPE_TARGET_TYPE (type), stream);
894   fprintf_filtered (stream, "%s", decorations->complex_suffix);
895 }
896
897 /* A generic val_print that is suitable for use by language
898    implementations of the la_val_print method.  This function can
899    handle most type codes, though not all, notably exception
900    TYPE_CODE_UNION and TYPE_CODE_STRUCT, which must be implemented by
901    the caller.
902    
903    Most arguments are as to val_print.
904    
905    The additional DECORATIONS argument can be used to customize the
906    output in some small, language-specific ways.  */
907
908 void
909 generic_val_print (struct type *type, const gdb_byte *valaddr,
910                    int embedded_offset, CORE_ADDR address,
911                    struct ui_file *stream, int recurse,
912                    const struct value *original_value,
913                    const struct value_print_options *options,
914                    const struct generic_val_print_decorations *decorations)
915 {
916   struct type *unresolved_type = type;
917
918   type = check_typedef (type);
919   switch (TYPE_CODE (type))
920     {
921     case TYPE_CODE_ARRAY:
922       generic_val_print_array (type, valaddr, embedded_offset, address, stream,
923                                recurse, original_value, options, decorations);
924       break;
925
926     case TYPE_CODE_MEMBERPTR:
927       generic_val_print_memberptr (type, valaddr, embedded_offset, stream,
928                                    original_value, options);
929       break;
930
931     case TYPE_CODE_PTR:
932       generic_val_print_ptr (type, valaddr, embedded_offset, stream,
933                              original_value, options);
934       break;
935
936     case TYPE_CODE_REF:
937       generic_val_print_ref (type, valaddr, embedded_offset, stream, recurse,
938                              original_value, options);
939       break;
940
941     case TYPE_CODE_ENUM:
942       generic_val_print_enum (type, valaddr, embedded_offset, stream,
943                               original_value, options);
944       break;
945
946     case TYPE_CODE_FLAGS:
947       generic_val_print_flags (type, valaddr, embedded_offset, stream,
948                                original_value, options);
949       break;
950
951     case TYPE_CODE_FUNC:
952     case TYPE_CODE_METHOD:
953       generic_val_print_func (type, valaddr, embedded_offset, address, stream,
954                               original_value, options);
955       break;
956
957     case TYPE_CODE_BOOL:
958       generic_val_print_bool (type, valaddr, embedded_offset, stream,
959                               original_value, options, decorations);
960       break;
961
962     case TYPE_CODE_RANGE:
963       /* FIXME: create_static_range_type does not set the unsigned bit in a
964          range type (I think it probably should copy it from the
965          target type), so we won't print values which are too large to
966          fit in a signed integer correctly.  */
967       /* FIXME: Doesn't handle ranges of enums correctly.  (Can't just
968          print with the target type, though, because the size of our
969          type and the target type might differ).  */
970
971       /* FALLTHROUGH */
972
973     case TYPE_CODE_INT:
974       generic_val_print_int (type, valaddr, embedded_offset, stream,
975                              original_value, options);
976       break;
977
978     case TYPE_CODE_CHAR:
979       generic_val_print_char (type, unresolved_type, valaddr, embedded_offset,
980                               stream, original_value, options);
981       break;
982
983     case TYPE_CODE_FLT:
984       generic_val_print_float (type, valaddr, embedded_offset, stream,
985                                original_value, options);
986       break;
987
988     case TYPE_CODE_DECFLOAT:
989       generic_val_print_decfloat (type, valaddr, embedded_offset, stream,
990                                   original_value, options);
991       break;
992
993     case TYPE_CODE_VOID:
994       fputs_filtered (decorations->void_name, stream);
995       break;
996
997     case TYPE_CODE_ERROR:
998       fprintf_filtered (stream, "%s", TYPE_ERROR_NAME (type));
999       break;
1000
1001     case TYPE_CODE_UNDEF:
1002       /* This happens (without TYPE_STUB set) on systems which don't use
1003          dbx xrefs (NO_DBX_XREFS in gcc) if a file has a "struct foo *bar"
1004          and no complete type for struct foo in that file.  */
1005       fprintf_filtered (stream, _("<incomplete type>"));
1006       break;
1007
1008     case TYPE_CODE_COMPLEX:
1009       generic_val_print_complex (type, valaddr, embedded_offset, stream,
1010                                  original_value, options, decorations);
1011       break;
1012
1013     case TYPE_CODE_UNION:
1014     case TYPE_CODE_STRUCT:
1015     case TYPE_CODE_METHODPTR:
1016     default:
1017       error (_("Unhandled type code %d in symbol table."),
1018              TYPE_CODE (type));
1019     }
1020   gdb_flush (stream);
1021 }
1022
1023 /* Print using the given LANGUAGE the data of type TYPE located at
1024    VALADDR + EMBEDDED_OFFSET (within GDB), which came from the
1025    inferior at address ADDRESS + EMBEDDED_OFFSET, onto stdio stream
1026    STREAM according to OPTIONS.  VAL is the whole object that came
1027    from ADDRESS.  VALADDR must point to the head of VAL's contents
1028    buffer.
1029
1030    The language printers will pass down an adjusted EMBEDDED_OFFSET to
1031    further helper subroutines as subfields of TYPE are printed.  In
1032    such cases, VALADDR is passed down unadjusted, as well as VAL, so
1033    that VAL can be queried for metadata about the contents data being
1034    printed, using EMBEDDED_OFFSET as an offset into VAL's contents
1035    buffer.  For example: "has this field been optimized out", or "I'm
1036    printing an object while inspecting a traceframe; has this
1037    particular piece of data been collected?".
1038
1039    RECURSE indicates the amount of indentation to supply before
1040    continuation lines; this amount is roughly twice the value of
1041    RECURSE.  */
1042
1043 void
1044 val_print (struct type *type, const gdb_byte *valaddr, LONGEST embedded_offset,
1045            CORE_ADDR address, struct ui_file *stream, int recurse,
1046            const struct value *val,
1047            const struct value_print_options *options,
1048            const struct language_defn *language)
1049 {
1050   int ret = 0;
1051   struct value_print_options local_opts = *options;
1052   struct type *real_type = check_typedef (type);
1053
1054   if (local_opts.prettyformat == Val_prettyformat_default)
1055     local_opts.prettyformat = (local_opts.prettyformat_structs
1056                                ? Val_prettyformat : Val_no_prettyformat);
1057
1058   QUIT;
1059
1060   /* Ensure that the type is complete and not just a stub.  If the type is
1061      only a stub and we can't find and substitute its complete type, then
1062      print appropriate string and return.  */
1063
1064   if (TYPE_STUB (real_type))
1065     {
1066       fprintf_filtered (stream, _("<incomplete type>"));
1067       gdb_flush (stream);
1068       return;
1069     }
1070
1071   if (!valprint_check_validity (stream, real_type, embedded_offset, val))
1072     return;
1073
1074   if (!options->raw)
1075     {
1076       ret = apply_ext_lang_val_pretty_printer (type, valaddr, embedded_offset,
1077                                                address, stream, recurse,
1078                                                val, options, language);
1079       if (ret)
1080         return;
1081     }
1082
1083   /* Handle summary mode.  If the value is a scalar, print it;
1084      otherwise, print an ellipsis.  */
1085   if (options->summary && !val_print_scalar_type_p (type))
1086     {
1087       fprintf_filtered (stream, "...");
1088       return;
1089     }
1090
1091   TRY
1092     {
1093       language->la_val_print (type, valaddr, embedded_offset, address,
1094                               stream, recurse, val,
1095                               &local_opts);
1096     }
1097   CATCH (except, RETURN_MASK_ERROR)
1098     {
1099       fprintf_filtered (stream, _("<error reading variable>"));
1100     }
1101   END_CATCH
1102 }
1103
1104 /* Check whether the value VAL is printable.  Return 1 if it is;
1105    return 0 and print an appropriate error message to STREAM according to
1106    OPTIONS if it is not.  */
1107
1108 static int
1109 value_check_printable (struct value *val, struct ui_file *stream,
1110                        const struct value_print_options *options)
1111 {
1112   if (val == 0)
1113     {
1114       fprintf_filtered (stream, _("<address of value unknown>"));
1115       return 0;
1116     }
1117
1118   if (value_entirely_optimized_out (val))
1119     {
1120       if (options->summary && !val_print_scalar_type_p (value_type (val)))
1121         fprintf_filtered (stream, "...");
1122       else
1123         val_print_optimized_out (val, stream);
1124       return 0;
1125     }
1126
1127   if (value_entirely_unavailable (val))
1128     {
1129       if (options->summary && !val_print_scalar_type_p (value_type (val)))
1130         fprintf_filtered (stream, "...");
1131       else
1132         val_print_unavailable (stream);
1133       return 0;
1134     }
1135
1136   if (TYPE_CODE (value_type (val)) == TYPE_CODE_INTERNAL_FUNCTION)
1137     {
1138       fprintf_filtered (stream, _("<internal function %s>"),
1139                         value_internal_function_name (val));
1140       return 0;
1141     }
1142
1143   if (type_not_associated (value_type (val)))
1144     {
1145       val_print_not_associated (stream);
1146       return 0;
1147     }
1148
1149   if (type_not_allocated (value_type (val)))
1150     {
1151       val_print_not_allocated (stream);
1152       return 0;
1153     }
1154
1155   return 1;
1156 }
1157
1158 /* Print using the given LANGUAGE the value VAL onto stream STREAM according
1159    to OPTIONS.
1160
1161    This is a preferable interface to val_print, above, because it uses
1162    GDB's value mechanism.  */
1163
1164 void
1165 common_val_print (struct value *val, struct ui_file *stream, int recurse,
1166                   const struct value_print_options *options,
1167                   const struct language_defn *language)
1168 {
1169   if (!value_check_printable (val, stream, options))
1170     return;
1171
1172   if (language->la_language == language_ada)
1173     /* The value might have a dynamic type, which would cause trouble
1174        below when trying to extract the value contents (since the value
1175        size is determined from the type size which is unknown).  So
1176        get a fixed representation of our value.  */
1177     val = ada_to_fixed_value (val);
1178
1179   val_print (value_type (val), value_contents_for_printing (val),
1180              value_embedded_offset (val), value_address (val),
1181              stream, recurse,
1182              val, options, language);
1183 }
1184
1185 /* Print on stream STREAM the value VAL according to OPTIONS.  The value
1186    is printed using the current_language syntax.  */
1187
1188 void
1189 value_print (struct value *val, struct ui_file *stream,
1190              const struct value_print_options *options)
1191 {
1192   if (!value_check_printable (val, stream, options))
1193     return;
1194
1195   if (!options->raw)
1196     {
1197       int r
1198         = apply_ext_lang_val_pretty_printer (value_type (val),
1199                                              value_contents_for_printing (val),
1200                                              value_embedded_offset (val),
1201                                              value_address (val),
1202                                              stream, 0,
1203                                              val, options, current_language);
1204
1205       if (r)
1206         return;
1207     }
1208
1209   LA_VALUE_PRINT (val, stream, options);
1210 }
1211
1212 /* Called by various <lang>_val_print routines to print
1213    TYPE_CODE_INT's.  TYPE is the type.  VALADDR is the address of the
1214    value.  STREAM is where to print the value.  */
1215
1216 void
1217 val_print_type_code_int (struct type *type, const gdb_byte *valaddr,
1218                          struct ui_file *stream)
1219 {
1220   enum bfd_endian byte_order = gdbarch_byte_order (get_type_arch (type));
1221
1222   if (TYPE_LENGTH (type) > sizeof (LONGEST))
1223     {
1224       LONGEST val;
1225
1226       if (TYPE_UNSIGNED (type)
1227           && extract_long_unsigned_integer (valaddr, TYPE_LENGTH (type),
1228                                             byte_order, &val))
1229         {
1230           print_longest (stream, 'u', 0, val);
1231         }
1232       else
1233         {
1234           /* Signed, or we couldn't turn an unsigned value into a
1235              LONGEST.  For signed values, one could assume two's
1236              complement (a reasonable assumption, I think) and do
1237              better than this.  */
1238           print_hex_chars (stream, (unsigned char *) valaddr,
1239                            TYPE_LENGTH (type), byte_order);
1240         }
1241     }
1242   else
1243     {
1244       print_longest (stream, TYPE_UNSIGNED (type) ? 'u' : 'd', 0,
1245                      unpack_long (type, valaddr));
1246     }
1247 }
1248
1249 static void
1250 val_print_type_code_flags (struct type *type, const gdb_byte *valaddr,
1251                            struct ui_file *stream)
1252 {
1253   ULONGEST val = unpack_long (type, valaddr);
1254   int field, nfields = TYPE_NFIELDS (type);
1255   struct gdbarch *gdbarch = get_type_arch (type);
1256   struct type *bool_type = builtin_type (gdbarch)->builtin_bool;
1257
1258   fputs_filtered ("[", stream);
1259   for (field = 0; field < nfields; field++)
1260     {
1261       if (TYPE_FIELD_NAME (type, field)[0] != '\0')
1262         {
1263           struct type *field_type = TYPE_FIELD_TYPE (type, field);
1264
1265           if (field_type == bool_type
1266               /* We require boolean types here to be one bit wide.  This is a
1267                  problematic place to notify the user of an internal error
1268                  though.  Instead just fall through and print the field as an
1269                  int.  */
1270               && TYPE_FIELD_BITSIZE (type, field) == 1)
1271             {
1272               if (val & ((ULONGEST)1 << TYPE_FIELD_BITPOS (type, field)))
1273                 fprintf_filtered (stream, " %s",
1274                                   TYPE_FIELD_NAME (type, field));
1275             }
1276           else
1277             {
1278               unsigned field_len = TYPE_FIELD_BITSIZE (type, field);
1279               ULONGEST field_val
1280                 = val >> (TYPE_FIELD_BITPOS (type, field) - field_len + 1);
1281
1282               if (field_len < sizeof (ULONGEST) * TARGET_CHAR_BIT)
1283                 field_val &= ((ULONGEST) 1 << field_len) - 1;
1284               fprintf_filtered (stream, " %s=",
1285                                 TYPE_FIELD_NAME (type, field));
1286               if (TYPE_CODE (field_type) == TYPE_CODE_ENUM)
1287                 generic_val_print_enum_1 (field_type, field_val, stream);
1288               else
1289                 print_longest (stream, 'd', 0, field_val);
1290             }
1291         }
1292     }
1293   fputs_filtered (" ]", stream);
1294 }
1295
1296 /* Print a scalar of data of type TYPE, pointed to in GDB by VALADDR,
1297    according to OPTIONS and SIZE on STREAM.  Format i is not supported
1298    at this level.
1299
1300    This is how the elements of an array or structure are printed
1301    with a format.  */
1302
1303 void
1304 val_print_scalar_formatted (struct type *type,
1305                             const gdb_byte *valaddr, LONGEST embedded_offset,
1306                             const struct value *val,
1307                             const struct value_print_options *options,
1308                             int size,
1309                             struct ui_file *stream)
1310 {
1311   struct gdbarch *arch = get_type_arch (type);
1312   int unit_size = gdbarch_addressable_memory_unit_size (arch);
1313
1314   gdb_assert (val != NULL);
1315   gdb_assert (valaddr == value_contents_for_printing_const (val));
1316
1317   /* If we get here with a string format, try again without it.  Go
1318      all the way back to the language printers, which may call us
1319      again.  */
1320   if (options->format == 's')
1321     {
1322       struct value_print_options opts = *options;
1323       opts.format = 0;
1324       opts.deref_ref = 0;
1325       val_print (type, valaddr, embedded_offset, 0, stream, 0, val, &opts,
1326                  current_language);
1327       return;
1328     }
1329
1330   /* A scalar object that does not have all bits available can't be
1331      printed, because all bits contribute to its representation.  */
1332   if (value_bits_any_optimized_out (val,
1333                                     TARGET_CHAR_BIT * embedded_offset,
1334                                     TARGET_CHAR_BIT * TYPE_LENGTH (type)))
1335     val_print_optimized_out (val, stream);
1336   else if (!value_bytes_available (val, embedded_offset, TYPE_LENGTH (type)))
1337     val_print_unavailable (stream);
1338   else
1339     print_scalar_formatted (valaddr + embedded_offset * unit_size, type,
1340                             options, size, stream);
1341 }
1342
1343 /* Print a number according to FORMAT which is one of d,u,x,o,b,h,w,g.
1344    The raison d'etre of this function is to consolidate printing of 
1345    LONG_LONG's into this one function.  The format chars b,h,w,g are 
1346    from print_scalar_formatted().  Numbers are printed using C
1347    format.
1348
1349    USE_C_FORMAT means to use C format in all cases.  Without it, 
1350    'o' and 'x' format do not include the standard C radix prefix
1351    (leading 0 or 0x). 
1352    
1353    Hilfinger/2004-09-09: USE_C_FORMAT was originally called USE_LOCAL
1354    and was intended to request formating according to the current
1355    language and would be used for most integers that GDB prints.  The
1356    exceptional cases were things like protocols where the format of
1357    the integer is a protocol thing, not a user-visible thing).  The
1358    parameter remains to preserve the information of what things might
1359    be printed with language-specific format, should we ever resurrect
1360    that capability.  */
1361
1362 void
1363 print_longest (struct ui_file *stream, int format, int use_c_format,
1364                LONGEST val_long)
1365 {
1366   const char *val;
1367
1368   switch (format)
1369     {
1370     case 'd':
1371       val = int_string (val_long, 10, 1, 0, 1); break;
1372     case 'u':
1373       val = int_string (val_long, 10, 0, 0, 1); break;
1374     case 'x':
1375       val = int_string (val_long, 16, 0, 0, use_c_format); break;
1376     case 'b':
1377       val = int_string (val_long, 16, 0, 2, 1); break;
1378     case 'h':
1379       val = int_string (val_long, 16, 0, 4, 1); break;
1380     case 'w':
1381       val = int_string (val_long, 16, 0, 8, 1); break;
1382     case 'g':
1383       val = int_string (val_long, 16, 0, 16, 1); break;
1384       break;
1385     case 'o':
1386       val = int_string (val_long, 8, 0, 0, use_c_format); break;
1387     default:
1388       internal_error (__FILE__, __LINE__,
1389                       _("failed internal consistency check"));
1390     } 
1391   fputs_filtered (val, stream);
1392 }
1393
1394 /* This used to be a macro, but I don't think it is called often enough
1395    to merit such treatment.  */
1396 /* Convert a LONGEST to an int.  This is used in contexts (e.g. number of
1397    arguments to a function, number in a value history, register number, etc.)
1398    where the value must not be larger than can fit in an int.  */
1399
1400 int
1401 longest_to_int (LONGEST arg)
1402 {
1403   /* Let the compiler do the work.  */
1404   int rtnval = (int) arg;
1405
1406   /* Check for overflows or underflows.  */
1407   if (sizeof (LONGEST) > sizeof (int))
1408     {
1409       if (rtnval != arg)
1410         {
1411           error (_("Value out of range."));
1412         }
1413     }
1414   return (rtnval);
1415 }
1416
1417 /* Print a floating point value of type TYPE (not always a
1418    TYPE_CODE_FLT), pointed to in GDB by VALADDR, on STREAM.  */
1419
1420 void
1421 print_floating (const gdb_byte *valaddr, struct type *type,
1422                 struct ui_file *stream)
1423 {
1424   DOUBLEST doub;
1425   int inv;
1426   const struct floatformat *fmt = NULL;
1427   unsigned len = TYPE_LENGTH (type);
1428   enum float_kind kind;
1429
1430   /* If it is a floating-point, check for obvious problems.  */
1431   if (TYPE_CODE (type) == TYPE_CODE_FLT)
1432     fmt = floatformat_from_type (type);
1433   if (fmt != NULL)
1434     {
1435       kind = floatformat_classify (fmt, valaddr);
1436       if (kind == float_nan)
1437         {
1438           if (floatformat_is_negative (fmt, valaddr))
1439             fprintf_filtered (stream, "-");
1440           fprintf_filtered (stream, "nan(");
1441           fputs_filtered ("0x", stream);
1442           fputs_filtered (floatformat_mantissa (fmt, valaddr), stream);
1443           fprintf_filtered (stream, ")");
1444           return;
1445         }
1446       else if (kind == float_infinite)
1447         {
1448           if (floatformat_is_negative (fmt, valaddr))
1449             fputs_filtered ("-", stream);
1450           fputs_filtered ("inf", stream);
1451           return;
1452         }
1453     }
1454
1455   /* NOTE: cagney/2002-01-15: The TYPE passed into print_floating()
1456      isn't necessarily a TYPE_CODE_FLT.  Consequently, unpack_double
1457      needs to be used as that takes care of any necessary type
1458      conversions.  Such conversions are of course direct to DOUBLEST
1459      and disregard any possible target floating point limitations.
1460      For instance, a u64 would be converted and displayed exactly on a
1461      host with 80 bit DOUBLEST but with loss of information on a host
1462      with 64 bit DOUBLEST.  */
1463
1464   doub = unpack_double (type, valaddr, &inv);
1465   if (inv)
1466     {
1467       fprintf_filtered (stream, "<invalid float value>");
1468       return;
1469     }
1470
1471   /* FIXME: kettenis/2001-01-20: The following code makes too much
1472      assumptions about the host and target floating point format.  */
1473
1474   /* NOTE: cagney/2002-02-03: Since the TYPE of what was passed in may
1475      not necessarily be a TYPE_CODE_FLT, the below ignores that and
1476      instead uses the type's length to determine the precision of the
1477      floating-point value being printed.  */
1478
1479   if (len < sizeof (double))
1480       fprintf_filtered (stream, "%.9g", (double) doub);
1481   else if (len == sizeof (double))
1482       fprintf_filtered (stream, "%.17g", (double) doub);
1483   else
1484 #ifdef PRINTF_HAS_LONG_DOUBLE
1485     fprintf_filtered (stream, "%.35Lg", doub);
1486 #else
1487     /* This at least wins with values that are representable as
1488        doubles.  */
1489     fprintf_filtered (stream, "%.17g", (double) doub);
1490 #endif
1491 }
1492
1493 void
1494 print_decimal_floating (const gdb_byte *valaddr, struct type *type,
1495                         struct ui_file *stream)
1496 {
1497   enum bfd_endian byte_order = gdbarch_byte_order (get_type_arch (type));
1498   char decstr[MAX_DECIMAL_STRING];
1499   unsigned len = TYPE_LENGTH (type);
1500
1501   decimal_to_string (valaddr, len, byte_order, decstr);
1502   fputs_filtered (decstr, stream);
1503   return;
1504 }
1505
1506 void
1507 print_binary_chars (struct ui_file *stream, const gdb_byte *valaddr,
1508                     unsigned len, enum bfd_endian byte_order)
1509 {
1510
1511 #define BITS_IN_BYTES 8
1512
1513   const gdb_byte *p;
1514   unsigned int i;
1515   int b;
1516
1517   /* Declared "int" so it will be signed.
1518      This ensures that right shift will shift in zeros.  */
1519
1520   const int mask = 0x080;
1521
1522   /* FIXME: We should be not printing leading zeroes in most cases.  */
1523
1524   if (byte_order == BFD_ENDIAN_BIG)
1525     {
1526       for (p = valaddr;
1527            p < valaddr + len;
1528            p++)
1529         {
1530           /* Every byte has 8 binary characters; peel off
1531              and print from the MSB end.  */
1532
1533           for (i = 0; i < (BITS_IN_BYTES * sizeof (*p)); i++)
1534             {
1535               if (*p & (mask >> i))
1536                 b = 1;
1537               else
1538                 b = 0;
1539
1540               fprintf_filtered (stream, "%1d", b);
1541             }
1542         }
1543     }
1544   else
1545     {
1546       for (p = valaddr + len - 1;
1547            p >= valaddr;
1548            p--)
1549         {
1550           for (i = 0; i < (BITS_IN_BYTES * sizeof (*p)); i++)
1551             {
1552               if (*p & (mask >> i))
1553                 b = 1;
1554               else
1555                 b = 0;
1556
1557               fprintf_filtered (stream, "%1d", b);
1558             }
1559         }
1560     }
1561 }
1562
1563 /* VALADDR points to an integer of LEN bytes.
1564    Print it in octal on stream or format it in buf.  */
1565
1566 void
1567 print_octal_chars (struct ui_file *stream, const gdb_byte *valaddr,
1568                    unsigned len, enum bfd_endian byte_order)
1569 {
1570   const gdb_byte *p;
1571   unsigned char octa1, octa2, octa3, carry;
1572   int cycle;
1573
1574   /* FIXME: We should be not printing leading zeroes in most cases.  */
1575
1576
1577   /* Octal is 3 bits, which doesn't fit.  Yuk.  So we have to track
1578    * the extra bits, which cycle every three bytes:
1579    *
1580    * Byte side:       0            1             2          3
1581    *                         |             |            |            |
1582    * bit number   123 456 78 | 9 012 345 6 | 78 901 234 | 567 890 12 |
1583    *
1584    * Octal side:   0   1   carry  3   4  carry ...
1585    *
1586    * Cycle number:    0             1            2
1587    *
1588    * But of course we are printing from the high side, so we have to
1589    * figure out where in the cycle we are so that we end up with no
1590    * left over bits at the end.
1591    */
1592 #define BITS_IN_OCTAL 3
1593 #define HIGH_ZERO     0340
1594 #define LOW_ZERO      0016
1595 #define CARRY_ZERO    0003
1596 #define HIGH_ONE      0200
1597 #define MID_ONE       0160
1598 #define LOW_ONE       0016
1599 #define CARRY_ONE     0001
1600 #define HIGH_TWO      0300
1601 #define MID_TWO       0070
1602 #define LOW_TWO       0007
1603
1604   /* For 32 we start in cycle 2, with two bits and one bit carry;
1605      for 64 in cycle in cycle 1, with one bit and a two bit carry.  */
1606
1607   cycle = (len * BITS_IN_BYTES) % BITS_IN_OCTAL;
1608   carry = 0;
1609
1610   fputs_filtered ("0", stream);
1611   if (byte_order == BFD_ENDIAN_BIG)
1612     {
1613       for (p = valaddr;
1614            p < valaddr + len;
1615            p++)
1616         {
1617           switch (cycle)
1618             {
1619             case 0:
1620               /* No carry in, carry out two bits.  */
1621
1622               octa1 = (HIGH_ZERO & *p) >> 5;
1623               octa2 = (LOW_ZERO & *p) >> 2;
1624               carry = (CARRY_ZERO & *p);
1625               fprintf_filtered (stream, "%o", octa1);
1626               fprintf_filtered (stream, "%o", octa2);
1627               break;
1628
1629             case 1:
1630               /* Carry in two bits, carry out one bit.  */
1631
1632               octa1 = (carry << 1) | ((HIGH_ONE & *p) >> 7);
1633               octa2 = (MID_ONE & *p) >> 4;
1634               octa3 = (LOW_ONE & *p) >> 1;
1635               carry = (CARRY_ONE & *p);
1636               fprintf_filtered (stream, "%o", octa1);
1637               fprintf_filtered (stream, "%o", octa2);
1638               fprintf_filtered (stream, "%o", octa3);
1639               break;
1640
1641             case 2:
1642               /* Carry in one bit, no carry out.  */
1643
1644               octa1 = (carry << 2) | ((HIGH_TWO & *p) >> 6);
1645               octa2 = (MID_TWO & *p) >> 3;
1646               octa3 = (LOW_TWO & *p);
1647               carry = 0;
1648               fprintf_filtered (stream, "%o", octa1);
1649               fprintf_filtered (stream, "%o", octa2);
1650               fprintf_filtered (stream, "%o", octa3);
1651               break;
1652
1653             default:
1654               error (_("Internal error in octal conversion;"));
1655             }
1656
1657           cycle++;
1658           cycle = cycle % BITS_IN_OCTAL;
1659         }
1660     }
1661   else
1662     {
1663       for (p = valaddr + len - 1;
1664            p >= valaddr;
1665            p--)
1666         {
1667           switch (cycle)
1668             {
1669             case 0:
1670               /* Carry out, no carry in */
1671
1672               octa1 = (HIGH_ZERO & *p) >> 5;
1673               octa2 = (LOW_ZERO & *p) >> 2;
1674               carry = (CARRY_ZERO & *p);
1675               fprintf_filtered (stream, "%o", octa1);
1676               fprintf_filtered (stream, "%o", octa2);
1677               break;
1678
1679             case 1:
1680               /* Carry in, carry out */
1681
1682               octa1 = (carry << 1) | ((HIGH_ONE & *p) >> 7);
1683               octa2 = (MID_ONE & *p) >> 4;
1684               octa3 = (LOW_ONE & *p) >> 1;
1685               carry = (CARRY_ONE & *p);
1686               fprintf_filtered (stream, "%o", octa1);
1687               fprintf_filtered (stream, "%o", octa2);
1688               fprintf_filtered (stream, "%o", octa3);
1689               break;
1690
1691             case 2:
1692               /* Carry in, no carry out */
1693
1694               octa1 = (carry << 2) | ((HIGH_TWO & *p) >> 6);
1695               octa2 = (MID_TWO & *p) >> 3;
1696               octa3 = (LOW_TWO & *p);
1697               carry = 0;
1698               fprintf_filtered (stream, "%o", octa1);
1699               fprintf_filtered (stream, "%o", octa2);
1700               fprintf_filtered (stream, "%o", octa3);
1701               break;
1702
1703             default:
1704               error (_("Internal error in octal conversion;"));
1705             }
1706
1707           cycle++;
1708           cycle = cycle % BITS_IN_OCTAL;
1709         }
1710     }
1711
1712 }
1713
1714 /* VALADDR points to an integer of LEN bytes.
1715    Print it in decimal on stream or format it in buf.  */
1716
1717 void
1718 print_decimal_chars (struct ui_file *stream, const gdb_byte *valaddr,
1719                      unsigned len, enum bfd_endian byte_order)
1720 {
1721 #define TEN             10
1722 #define CARRY_OUT(  x ) ((x) / TEN)     /* extend char to int */
1723 #define CARRY_LEFT( x ) ((x) % TEN)
1724 #define SHIFT( x )      ((x) << 4)
1725 #define LOW_NIBBLE(  x ) ( (x) & 0x00F)
1726 #define HIGH_NIBBLE( x ) (((x) & 0x0F0) >> 4)
1727
1728   const gdb_byte *p;
1729   unsigned char *digits;
1730   int carry;
1731   int decimal_len;
1732   int i, j, decimal_digits;
1733   int dummy;
1734   int flip;
1735
1736   /* Base-ten number is less than twice as many digits
1737      as the base 16 number, which is 2 digits per byte.  */
1738
1739   decimal_len = len * 2 * 2;
1740   digits = (unsigned char *) xmalloc (decimal_len);
1741
1742   for (i = 0; i < decimal_len; i++)
1743     {
1744       digits[i] = 0;
1745     }
1746
1747   /* Ok, we have an unknown number of bytes of data to be printed in
1748    * decimal.
1749    *
1750    * Given a hex number (in nibbles) as XYZ, we start by taking X and
1751    * decemalizing it as "x1 x2" in two decimal nibbles.  Then we multiply
1752    * the nibbles by 16, add Y and re-decimalize.  Repeat with Z.
1753    *
1754    * The trick is that "digits" holds a base-10 number, but sometimes
1755    * the individual digits are > 10.
1756    *
1757    * Outer loop is per nibble (hex digit) of input, from MSD end to
1758    * LSD end.
1759    */
1760   decimal_digits = 0;           /* Number of decimal digits so far */
1761   p = (byte_order == BFD_ENDIAN_BIG) ? valaddr : valaddr + len - 1;
1762   flip = 0;
1763   while ((byte_order == BFD_ENDIAN_BIG) ? (p < valaddr + len) : (p >= valaddr))
1764     {
1765       /*
1766        * Multiply current base-ten number by 16 in place.
1767        * Each digit was between 0 and 9, now is between
1768        * 0 and 144.
1769        */
1770       for (j = 0; j < decimal_digits; j++)
1771         {
1772           digits[j] = SHIFT (digits[j]);
1773         }
1774
1775       /* Take the next nibble off the input and add it to what
1776        * we've got in the LSB position.  Bottom 'digit' is now
1777        * between 0 and 159.
1778        *
1779        * "flip" is used to run this loop twice for each byte.
1780        */
1781       if (flip == 0)
1782         {
1783           /* Take top nibble.  */
1784
1785           digits[0] += HIGH_NIBBLE (*p);
1786           flip = 1;
1787         }
1788       else
1789         {
1790           /* Take low nibble and bump our pointer "p".  */
1791
1792           digits[0] += LOW_NIBBLE (*p);
1793           if (byte_order == BFD_ENDIAN_BIG)
1794             p++;
1795           else
1796             p--;
1797           flip = 0;
1798         }
1799
1800       /* Re-decimalize.  We have to do this often enough
1801        * that we don't overflow, but once per nibble is
1802        * overkill.  Easier this way, though.  Note that the
1803        * carry is often larger than 10 (e.g. max initial
1804        * carry out of lowest nibble is 15, could bubble all
1805        * the way up greater than 10).  So we have to do
1806        * the carrying beyond the last current digit.
1807        */
1808       carry = 0;
1809       for (j = 0; j < decimal_len - 1; j++)
1810         {
1811           digits[j] += carry;
1812
1813           /* "/" won't handle an unsigned char with
1814            * a value that if signed would be negative.
1815            * So extend to longword int via "dummy".
1816            */
1817           dummy = digits[j];
1818           carry = CARRY_OUT (dummy);
1819           digits[j] = CARRY_LEFT (dummy);
1820
1821           if (j >= decimal_digits && carry == 0)
1822             {
1823               /*
1824                * All higher digits are 0 and we
1825                * no longer have a carry.
1826                *
1827                * Note: "j" is 0-based, "decimal_digits" is
1828                *       1-based.
1829                */
1830               decimal_digits = j + 1;
1831               break;
1832             }
1833         }
1834     }
1835
1836   /* Ok, now "digits" is the decimal representation, with
1837      the "decimal_digits" actual digits.  Print!  */
1838
1839   for (i = decimal_digits - 1; i >= 0; i--)
1840     {
1841       fprintf_filtered (stream, "%1d", digits[i]);
1842     }
1843   xfree (digits);
1844 }
1845
1846 /* VALADDR points to an integer of LEN bytes.  Print it in hex on stream.  */
1847
1848 void
1849 print_hex_chars (struct ui_file *stream, const gdb_byte *valaddr,
1850                  unsigned len, enum bfd_endian byte_order)
1851 {
1852   const gdb_byte *p;
1853
1854   /* FIXME: We should be not printing leading zeroes in most cases.  */
1855
1856   fputs_filtered ("0x", stream);
1857   if (byte_order == BFD_ENDIAN_BIG)
1858     {
1859       for (p = valaddr;
1860            p < valaddr + len;
1861            p++)
1862         {
1863           fprintf_filtered (stream, "%02x", *p);
1864         }
1865     }
1866   else
1867     {
1868       for (p = valaddr + len - 1;
1869            p >= valaddr;
1870            p--)
1871         {
1872           fprintf_filtered (stream, "%02x", *p);
1873         }
1874     }
1875 }
1876
1877 /* VALADDR points to a char integer of LEN bytes.
1878    Print it out in appropriate language form on stream.
1879    Omit any leading zero chars.  */
1880
1881 void
1882 print_char_chars (struct ui_file *stream, struct type *type,
1883                   const gdb_byte *valaddr,
1884                   unsigned len, enum bfd_endian byte_order)
1885 {
1886   const gdb_byte *p;
1887
1888   if (byte_order == BFD_ENDIAN_BIG)
1889     {
1890       p = valaddr;
1891       while (p < valaddr + len - 1 && *p == 0)
1892         ++p;
1893
1894       while (p < valaddr + len)
1895         {
1896           LA_EMIT_CHAR (*p, type, stream, '\'');
1897           ++p;
1898         }
1899     }
1900   else
1901     {
1902       p = valaddr + len - 1;
1903       while (p > valaddr && *p == 0)
1904         --p;
1905
1906       while (p >= valaddr)
1907         {
1908           LA_EMIT_CHAR (*p, type, stream, '\'');
1909           --p;
1910         }
1911     }
1912 }
1913
1914 /* Print function pointer with inferior address ADDRESS onto stdio
1915    stream STREAM.  */
1916
1917 void
1918 print_function_pointer_address (const struct value_print_options *options,
1919                                 struct gdbarch *gdbarch,
1920                                 CORE_ADDR address,
1921                                 struct ui_file *stream)
1922 {
1923   CORE_ADDR func_addr
1924     = gdbarch_convert_from_func_ptr_addr (gdbarch, address,
1925                                           &current_target);
1926
1927   /* If the function pointer is represented by a description, print
1928      the address of the description.  */
1929   if (options->addressprint && func_addr != address)
1930     {
1931       fputs_filtered ("@", stream);
1932       fputs_filtered (paddress (gdbarch, address), stream);
1933       fputs_filtered (": ", stream);
1934     }
1935   print_address_demangle (options, gdbarch, func_addr, stream, demangle);
1936 }
1937
1938
1939 /* Print on STREAM using the given OPTIONS the index for the element
1940    at INDEX of an array whose index type is INDEX_TYPE.  */
1941     
1942 void  
1943 maybe_print_array_index (struct type *index_type, LONGEST index,
1944                          struct ui_file *stream,
1945                          const struct value_print_options *options)
1946 {
1947   struct value *index_value;
1948
1949   if (!options->print_array_indexes)
1950     return; 
1951     
1952   index_value = value_from_longest (index_type, index);
1953
1954   LA_PRINT_ARRAY_INDEX (index_value, stream, options);
1955 }
1956
1957 /*  Called by various <lang>_val_print routines to print elements of an
1958    array in the form "<elem1>, <elem2>, <elem3>, ...".
1959
1960    (FIXME?)  Assumes array element separator is a comma, which is correct
1961    for all languages currently handled.
1962    (FIXME?)  Some languages have a notation for repeated array elements,
1963    perhaps we should try to use that notation when appropriate.  */
1964
1965 void
1966 val_print_array_elements (struct type *type,
1967                           const gdb_byte *valaddr, LONGEST embedded_offset,
1968                           CORE_ADDR address, struct ui_file *stream,
1969                           int recurse,
1970                           const struct value *val,
1971                           const struct value_print_options *options,
1972                           unsigned int i)
1973 {
1974   unsigned int things_printed = 0;
1975   unsigned len;
1976   struct type *elttype, *index_type, *base_index_type;
1977   unsigned eltlen;
1978   /* Position of the array element we are examining to see
1979      whether it is repeated.  */
1980   unsigned int rep1;
1981   /* Number of repetitions we have detected so far.  */
1982   unsigned int reps;
1983   LONGEST low_bound, high_bound;
1984   LONGEST low_pos, high_pos;
1985
1986   elttype = TYPE_TARGET_TYPE (type);
1987   eltlen = type_length_units (check_typedef (elttype));
1988   index_type = TYPE_INDEX_TYPE (type);
1989
1990   if (get_array_bounds (type, &low_bound, &high_bound))
1991     {
1992       if (TYPE_CODE (index_type) == TYPE_CODE_RANGE)
1993         base_index_type = TYPE_TARGET_TYPE (index_type);
1994       else
1995         base_index_type = index_type;
1996
1997       /* Non-contiguous enumerations types can by used as index types
1998          in some languages (e.g. Ada).  In this case, the array length
1999          shall be computed from the positions of the first and last
2000          literal in the enumeration type, and not from the values
2001          of these literals.  */
2002       if (!discrete_position (base_index_type, low_bound, &low_pos)
2003           || !discrete_position (base_index_type, high_bound, &high_pos))
2004         {
2005           warning (_("unable to get positions in array, use bounds instead"));
2006           low_pos = low_bound;
2007           high_pos = high_bound;
2008         }
2009
2010       /* The array length should normally be HIGH_POS - LOW_POS + 1.
2011          But we have to be a little extra careful, because some languages
2012          such as Ada allow LOW_POS to be greater than HIGH_POS for
2013          empty arrays.  In that situation, the array length is just zero,
2014          not negative!  */
2015       if (low_pos > high_pos)
2016         len = 0;
2017       else
2018         len = high_pos - low_pos + 1;
2019     }
2020   else
2021     {
2022       warning (_("unable to get bounds of array, assuming null array"));
2023       low_bound = 0;
2024       len = 0;
2025     }
2026
2027   annotate_array_section_begin (i, elttype);
2028
2029   for (; i < len && things_printed < options->print_max; i++)
2030     {
2031       if (i != 0)
2032         {
2033           if (options->prettyformat_arrays)
2034             {
2035               fprintf_filtered (stream, ",\n");
2036               print_spaces_filtered (2 + 2 * recurse, stream);
2037             }
2038           else
2039             {
2040               fprintf_filtered (stream, ", ");
2041             }
2042         }
2043       wrap_here (n_spaces (2 + 2 * recurse));
2044       maybe_print_array_index (index_type, i + low_bound,
2045                                stream, options);
2046
2047       rep1 = i + 1;
2048       reps = 1;
2049       /* Only check for reps if repeat_count_threshold is not set to
2050          UINT_MAX (unlimited).  */
2051       if (options->repeat_count_threshold < UINT_MAX)
2052         {
2053           while (rep1 < len
2054                  && value_contents_eq (val,
2055                                        embedded_offset + i * eltlen,
2056                                        val,
2057                                        (embedded_offset
2058                                         + rep1 * eltlen),
2059                                        eltlen))
2060             {
2061               ++reps;
2062               ++rep1;
2063             }
2064         }
2065
2066       if (reps > options->repeat_count_threshold)
2067         {
2068           val_print (elttype, valaddr, embedded_offset + i * eltlen,
2069                      address, stream, recurse + 1, val, options,
2070                      current_language);
2071           annotate_elt_rep (reps);
2072           fprintf_filtered (stream, " <repeats %u times>", reps);
2073           annotate_elt_rep_end ();
2074
2075           i = rep1 - 1;
2076           things_printed += options->repeat_count_threshold;
2077         }
2078       else
2079         {
2080           val_print (elttype, valaddr, embedded_offset + i * eltlen,
2081                      address,
2082                      stream, recurse + 1, val, options, current_language);
2083           annotate_elt ();
2084           things_printed++;
2085         }
2086     }
2087   annotate_array_section_end ();
2088   if (i < len)
2089     {
2090       fprintf_filtered (stream, "...");
2091     }
2092 }
2093
2094 /* Read LEN bytes of target memory at address MEMADDR, placing the
2095    results in GDB's memory at MYADDR.  Returns a count of the bytes
2096    actually read, and optionally a target_xfer_status value in the
2097    location pointed to by ERRPTR if ERRPTR is non-null.  */
2098
2099 /* FIXME: cagney/1999-10-14: Only used by val_print_string.  Can this
2100    function be eliminated.  */
2101
2102 static int
2103 partial_memory_read (CORE_ADDR memaddr, gdb_byte *myaddr,
2104                      int len, int *errptr)
2105 {
2106   int nread;                    /* Number of bytes actually read.  */
2107   int errcode;                  /* Error from last read.  */
2108
2109   /* First try a complete read.  */
2110   errcode = target_read_memory (memaddr, myaddr, len);
2111   if (errcode == 0)
2112     {
2113       /* Got it all.  */
2114       nread = len;
2115     }
2116   else
2117     {
2118       /* Loop, reading one byte at a time until we get as much as we can.  */
2119       for (errcode = 0, nread = 0; len > 0 && errcode == 0; nread++, len--)
2120         {
2121           errcode = target_read_memory (memaddr++, myaddr++, 1);
2122         }
2123       /* If an error, the last read was unsuccessful, so adjust count.  */
2124       if (errcode != 0)
2125         {
2126           nread--;
2127         }
2128     }
2129   if (errptr != NULL)
2130     {
2131       *errptr = errcode;
2132     }
2133   return (nread);
2134 }
2135
2136 /* Read a string from the inferior, at ADDR, with LEN characters of WIDTH bytes
2137    each.  Fetch at most FETCHLIMIT characters.  BUFFER will be set to a newly
2138    allocated buffer containing the string, which the caller is responsible to
2139    free, and BYTES_READ will be set to the number of bytes read.  Returns 0 on
2140    success, or a target_xfer_status on failure.
2141
2142    If LEN > 0, reads the lesser of LEN or FETCHLIMIT characters
2143    (including eventual NULs in the middle or end of the string).
2144
2145    If LEN is -1, stops at the first null character (not necessarily
2146    the first null byte) up to a maximum of FETCHLIMIT characters.  Set
2147    FETCHLIMIT to UINT_MAX to read as many characters as possible from
2148    the string.
2149
2150    Unless an exception is thrown, BUFFER will always be allocated, even on
2151    failure.  In this case, some characters might have been read before the
2152    failure happened.  Check BYTES_READ to recognize this situation.
2153
2154    Note: There was a FIXME asking to make this code use target_read_string,
2155    but this function is more general (can read past null characters, up to
2156    given LEN).  Besides, it is used much more often than target_read_string
2157    so it is more tested.  Perhaps callers of target_read_string should use
2158    this function instead?  */
2159
2160 int
2161 read_string (CORE_ADDR addr, int len, int width, unsigned int fetchlimit,
2162              enum bfd_endian byte_order, gdb_byte **buffer, int *bytes_read)
2163 {
2164   int errcode;                  /* Errno returned from bad reads.  */
2165   unsigned int nfetch;          /* Chars to fetch / chars fetched.  */
2166   gdb_byte *bufptr;             /* Pointer to next available byte in
2167                                    buffer.  */
2168   struct cleanup *old_chain = NULL;     /* Top of the old cleanup chain.  */
2169
2170   /* Loop until we either have all the characters, or we encounter
2171      some error, such as bumping into the end of the address space.  */
2172
2173   *buffer = NULL;
2174
2175   old_chain = make_cleanup (free_current_contents, buffer);
2176
2177   if (len > 0)
2178     {
2179       /* We want fetchlimit chars, so we might as well read them all in
2180          one operation.  */
2181       unsigned int fetchlen = min (len, fetchlimit);
2182
2183       *buffer = (gdb_byte *) xmalloc (fetchlen * width);
2184       bufptr = *buffer;
2185
2186       nfetch = partial_memory_read (addr, bufptr, fetchlen * width, &errcode)
2187         / width;
2188       addr += nfetch * width;
2189       bufptr += nfetch * width;
2190     }
2191   else if (len == -1)
2192     {
2193       unsigned long bufsize = 0;
2194       unsigned int chunksize;   /* Size of each fetch, in chars.  */
2195       int found_nul;            /* Non-zero if we found the nul char.  */
2196       gdb_byte *limit;          /* First location past end of fetch buffer.  */
2197
2198       found_nul = 0;
2199       /* We are looking for a NUL terminator to end the fetching, so we
2200          might as well read in blocks that are large enough to be efficient,
2201          but not so large as to be slow if fetchlimit happens to be large.
2202          So we choose the minimum of 8 and fetchlimit.  We used to use 200
2203          instead of 8 but 200 is way too big for remote debugging over a
2204           serial line.  */
2205       chunksize = min (8, fetchlimit);
2206
2207       do
2208         {
2209           QUIT;
2210           nfetch = min (chunksize, fetchlimit - bufsize);
2211
2212           if (*buffer == NULL)
2213             *buffer = (gdb_byte *) xmalloc (nfetch * width);
2214           else
2215             *buffer = (gdb_byte *) xrealloc (*buffer,
2216                                              (nfetch + bufsize) * width);
2217
2218           bufptr = *buffer + bufsize * width;
2219           bufsize += nfetch;
2220
2221           /* Read as much as we can.  */
2222           nfetch = partial_memory_read (addr, bufptr, nfetch * width, &errcode)
2223                     / width;
2224
2225           /* Scan this chunk for the null character that terminates the string
2226              to print.  If found, we don't need to fetch any more.  Note
2227              that bufptr is explicitly left pointing at the next character
2228              after the null character, or at the next character after the end
2229              of the buffer.  */
2230
2231           limit = bufptr + nfetch * width;
2232           while (bufptr < limit)
2233             {
2234               unsigned long c;
2235
2236               c = extract_unsigned_integer (bufptr, width, byte_order);
2237               addr += width;
2238               bufptr += width;
2239               if (c == 0)
2240                 {
2241                   /* We don't care about any error which happened after
2242                      the NUL terminator.  */
2243                   errcode = 0;
2244                   found_nul = 1;
2245                   break;
2246                 }
2247             }
2248         }
2249       while (errcode == 0       /* no error */
2250              && bufptr - *buffer < fetchlimit * width   /* no overrun */
2251              && !found_nul);    /* haven't found NUL yet */
2252     }
2253   else
2254     {                           /* Length of string is really 0!  */
2255       /* We always allocate *buffer.  */
2256       *buffer = bufptr = (gdb_byte *) xmalloc (1);
2257       errcode = 0;
2258     }
2259
2260   /* bufptr and addr now point immediately beyond the last byte which we
2261      consider part of the string (including a '\0' which ends the string).  */
2262   *bytes_read = bufptr - *buffer;
2263
2264   QUIT;
2265
2266   discard_cleanups (old_chain);
2267
2268   return errcode;
2269 }
2270
2271 /* Return true if print_wchar can display W without resorting to a
2272    numeric escape, false otherwise.  */
2273
2274 static int
2275 wchar_printable (gdb_wchar_t w)
2276 {
2277   return (gdb_iswprint (w)
2278           || w == LCST ('\a') || w == LCST ('\b')
2279           || w == LCST ('\f') || w == LCST ('\n')
2280           || w == LCST ('\r') || w == LCST ('\t')
2281           || w == LCST ('\v'));
2282 }
2283
2284 /* A helper function that converts the contents of STRING to wide
2285    characters and then appends them to OUTPUT.  */
2286
2287 static void
2288 append_string_as_wide (const char *string,
2289                        struct obstack *output)
2290 {
2291   for (; *string; ++string)
2292     {
2293       gdb_wchar_t w = gdb_btowc (*string);
2294       obstack_grow (output, &w, sizeof (gdb_wchar_t));
2295     }
2296 }
2297
2298 /* Print a wide character W to OUTPUT.  ORIG is a pointer to the
2299    original (target) bytes representing the character, ORIG_LEN is the
2300    number of valid bytes.  WIDTH is the number of bytes in a base
2301    characters of the type.  OUTPUT is an obstack to which wide
2302    characters are emitted.  QUOTER is a (narrow) character indicating
2303    the style of quotes surrounding the character to be printed.
2304    NEED_ESCAPE is an in/out flag which is used to track numeric
2305    escapes across calls.  */
2306
2307 static void
2308 print_wchar (gdb_wint_t w, const gdb_byte *orig,
2309              int orig_len, int width,
2310              enum bfd_endian byte_order,
2311              struct obstack *output,
2312              int quoter, int *need_escapep)
2313 {
2314   int need_escape = *need_escapep;
2315
2316   *need_escapep = 0;
2317
2318   /* iswprint implementation on Windows returns 1 for tab character.
2319      In order to avoid different printout on this host, we explicitly
2320      use wchar_printable function.  */
2321   switch (w)
2322     {
2323       case LCST ('\a'):
2324         obstack_grow_wstr (output, LCST ("\\a"));
2325         break;
2326       case LCST ('\b'):
2327         obstack_grow_wstr (output, LCST ("\\b"));
2328         break;
2329       case LCST ('\f'):
2330         obstack_grow_wstr (output, LCST ("\\f"));
2331         break;
2332       case LCST ('\n'):
2333         obstack_grow_wstr (output, LCST ("\\n"));
2334         break;
2335       case LCST ('\r'):
2336         obstack_grow_wstr (output, LCST ("\\r"));
2337         break;
2338       case LCST ('\t'):
2339         obstack_grow_wstr (output, LCST ("\\t"));
2340         break;
2341       case LCST ('\v'):
2342         obstack_grow_wstr (output, LCST ("\\v"));
2343         break;
2344       default:
2345         {
2346           if (wchar_printable (w) && (!need_escape || (!gdb_iswdigit (w)
2347                                                        && w != LCST ('8')
2348                                                        && w != LCST ('9'))))
2349             {
2350               gdb_wchar_t wchar = w;
2351
2352               if (w == gdb_btowc (quoter) || w == LCST ('\\'))
2353                 obstack_grow_wstr (output, LCST ("\\"));
2354               obstack_grow (output, &wchar, sizeof (gdb_wchar_t));
2355             }
2356           else
2357             {
2358               int i;
2359
2360               for (i = 0; i + width <= orig_len; i += width)
2361                 {
2362                   char octal[30];
2363                   ULONGEST value;
2364
2365                   value = extract_unsigned_integer (&orig[i], width,
2366                                                   byte_order);
2367                   /* If the value fits in 3 octal digits, print it that
2368                      way.  Otherwise, print it as a hex escape.  */
2369                   if (value <= 0777)
2370                     xsnprintf (octal, sizeof (octal), "\\%.3o",
2371                                (int) (value & 0777));
2372                   else
2373                     xsnprintf (octal, sizeof (octal), "\\x%lx", (long) value);
2374                   append_string_as_wide (octal, output);
2375                 }
2376               /* If we somehow have extra bytes, print them now.  */
2377               while (i < orig_len)
2378                 {
2379                   char octal[5];
2380
2381                   xsnprintf (octal, sizeof (octal), "\\%.3o", orig[i] & 0xff);
2382                   append_string_as_wide (octal, output);
2383                   ++i;
2384                 }
2385
2386               *need_escapep = 1;
2387             }
2388           break;
2389         }
2390     }
2391 }
2392
2393 /* Print the character C on STREAM as part of the contents of a
2394    literal string whose delimiter is QUOTER.  ENCODING names the
2395    encoding of C.  */
2396
2397 void
2398 generic_emit_char (int c, struct type *type, struct ui_file *stream,
2399                    int quoter, const char *encoding)
2400 {
2401   enum bfd_endian byte_order
2402     = gdbarch_byte_order (get_type_arch (type));
2403   struct obstack wchar_buf, output;
2404   struct cleanup *cleanups;
2405   gdb_byte *buf;
2406   struct wchar_iterator *iter;
2407   int need_escape = 0;
2408
2409   buf = (gdb_byte *) alloca (TYPE_LENGTH (type));
2410   pack_long (buf, type, c);
2411
2412   iter = make_wchar_iterator (buf, TYPE_LENGTH (type),
2413                               encoding, TYPE_LENGTH (type));
2414   cleanups = make_cleanup_wchar_iterator (iter);
2415
2416   /* This holds the printable form of the wchar_t data.  */
2417   obstack_init (&wchar_buf);
2418   make_cleanup_obstack_free (&wchar_buf);
2419
2420   while (1)
2421     {
2422       int num_chars;
2423       gdb_wchar_t *chars;
2424       const gdb_byte *buf;
2425       size_t buflen;
2426       int print_escape = 1;
2427       enum wchar_iterate_result result;
2428
2429       num_chars = wchar_iterate (iter, &result, &chars, &buf, &buflen);
2430       if (num_chars < 0)
2431         break;
2432       if (num_chars > 0)
2433         {
2434           /* If all characters are printable, print them.  Otherwise,
2435              we're going to have to print an escape sequence.  We
2436              check all characters because we want to print the target
2437              bytes in the escape sequence, and we don't know character
2438              boundaries there.  */
2439           int i;
2440
2441           print_escape = 0;
2442           for (i = 0; i < num_chars; ++i)
2443             if (!wchar_printable (chars[i]))
2444               {
2445                 print_escape = 1;
2446                 break;
2447               }
2448
2449           if (!print_escape)
2450             {
2451               for (i = 0; i < num_chars; ++i)
2452                 print_wchar (chars[i], buf, buflen,
2453                              TYPE_LENGTH (type), byte_order,
2454                              &wchar_buf, quoter, &need_escape);
2455             }
2456         }
2457
2458       /* This handles the NUM_CHARS == 0 case as well.  */
2459       if (print_escape)
2460         print_wchar (gdb_WEOF, buf, buflen, TYPE_LENGTH (type),
2461                      byte_order, &wchar_buf, quoter, &need_escape);
2462     }
2463
2464   /* The output in the host encoding.  */
2465   obstack_init (&output);
2466   make_cleanup_obstack_free (&output);
2467
2468   convert_between_encodings (INTERMEDIATE_ENCODING, host_charset (),
2469                              (gdb_byte *) obstack_base (&wchar_buf),
2470                              obstack_object_size (&wchar_buf),
2471                              sizeof (gdb_wchar_t), &output, translit_char);
2472   obstack_1grow (&output, '\0');
2473
2474   fputs_filtered ((const char *) obstack_base (&output), stream);
2475
2476   do_cleanups (cleanups);
2477 }
2478
2479 /* Return the repeat count of the next character/byte in ITER,
2480    storing the result in VEC.  */
2481
2482 static int
2483 count_next_character (struct wchar_iterator *iter,
2484                       VEC (converted_character_d) **vec)
2485 {
2486   struct converted_character *current;
2487
2488   if (VEC_empty (converted_character_d, *vec))
2489     {
2490       struct converted_character tmp;
2491       gdb_wchar_t *chars;
2492
2493       tmp.num_chars
2494         = wchar_iterate (iter, &tmp.result, &chars, &tmp.buf, &tmp.buflen);
2495       if (tmp.num_chars > 0)
2496         {
2497           gdb_assert (tmp.num_chars < MAX_WCHARS);
2498           memcpy (tmp.chars, chars, tmp.num_chars * sizeof (gdb_wchar_t));
2499         }
2500       VEC_safe_push (converted_character_d, *vec, &tmp);
2501     }
2502
2503   current = VEC_last (converted_character_d, *vec);
2504
2505   /* Count repeated characters or bytes.  */
2506   current->repeat_count = 1;
2507   if (current->num_chars == -1)
2508     {
2509       /* EOF  */
2510       return -1;
2511     }
2512   else
2513     {
2514       gdb_wchar_t *chars;
2515       struct converted_character d;
2516       int repeat;
2517
2518       d.repeat_count = 0;
2519
2520       while (1)
2521         {
2522           /* Get the next character.  */
2523           d.num_chars
2524             = wchar_iterate (iter, &d.result, &chars, &d.buf, &d.buflen);
2525
2526           /* If a character was successfully converted, save the character
2527              into the converted character.  */
2528           if (d.num_chars > 0)
2529             {
2530               gdb_assert (d.num_chars < MAX_WCHARS);
2531               memcpy (d.chars, chars, WCHAR_BUFLEN (d.num_chars));
2532             }
2533
2534           /* Determine if the current character is the same as this
2535              new character.  */
2536           if (d.num_chars == current->num_chars && d.result == current->result)
2537             {
2538               /* There are two cases to consider:
2539
2540                  1) Equality of converted character (num_chars > 0)
2541                  2) Equality of non-converted character (num_chars == 0)  */
2542               if ((current->num_chars > 0
2543                    && memcmp (current->chars, d.chars,
2544                               WCHAR_BUFLEN (current->num_chars)) == 0)
2545                   || (current->num_chars == 0
2546                       && current->buflen == d.buflen
2547                       && memcmp (current->buf, d.buf, current->buflen) == 0))
2548                 ++current->repeat_count;
2549               else
2550                 break;
2551             }
2552           else
2553             break;
2554         }
2555
2556       /* Push this next converted character onto the result vector.  */
2557       repeat = current->repeat_count;
2558       VEC_safe_push (converted_character_d, *vec, &d);
2559       return repeat;
2560     }
2561 }
2562
2563 /* Print the characters in CHARS to the OBSTACK.  QUOTE_CHAR is the quote
2564    character to use with string output.  WIDTH is the size of the output
2565    character type.  BYTE_ORDER is the the target byte order.  OPTIONS
2566    is the user's print options.  */
2567
2568 static void
2569 print_converted_chars_to_obstack (struct obstack *obstack,
2570                                   VEC (converted_character_d) *chars,
2571                                   int quote_char, int width,
2572                                   enum bfd_endian byte_order,
2573                                   const struct value_print_options *options)
2574 {
2575   unsigned int idx;
2576   struct converted_character *elem;
2577   enum {START, SINGLE, REPEAT, INCOMPLETE, FINISH} state, last;
2578   gdb_wchar_t wide_quote_char = gdb_btowc (quote_char);
2579   int need_escape = 0;
2580
2581   /* Set the start state.  */
2582   idx = 0;
2583   last = state = START;
2584   elem = NULL;
2585
2586   while (1)
2587     {
2588       switch (state)
2589         {
2590         case START:
2591           /* Nothing to do.  */
2592           break;
2593
2594         case SINGLE:
2595           {
2596             int j;
2597
2598             /* We are outputting a single character
2599                (< options->repeat_count_threshold).  */
2600
2601             if (last != SINGLE)
2602               {
2603                 /* We were outputting some other type of content, so we
2604                    must output and a comma and a quote.  */
2605                 if (last != START)
2606                   obstack_grow_wstr (obstack, LCST (", "));
2607                 obstack_grow (obstack, &wide_quote_char, sizeof (gdb_wchar_t));
2608               }
2609             /* Output the character.  */
2610             for (j = 0; j < elem->repeat_count; ++j)
2611               {
2612                 if (elem->result == wchar_iterate_ok)
2613                   print_wchar (elem->chars[0], elem->buf, elem->buflen, width,
2614                                byte_order, obstack, quote_char, &need_escape);
2615                 else
2616                   print_wchar (gdb_WEOF, elem->buf, elem->buflen, width,
2617                                byte_order, obstack, quote_char, &need_escape);
2618               }
2619           }
2620           break;
2621
2622         case REPEAT:
2623           {
2624             int j;
2625             char *s;
2626
2627             /* We are outputting a character with a repeat count
2628                greater than options->repeat_count_threshold.  */
2629
2630             if (last == SINGLE)
2631               {
2632                 /* We were outputting a single string.  Terminate the
2633                    string.  */
2634                 obstack_grow (obstack, &wide_quote_char, sizeof (gdb_wchar_t));
2635               }
2636             if (last != START)
2637               obstack_grow_wstr (obstack, LCST (", "));
2638
2639             /* Output the character and repeat string.  */
2640             obstack_grow_wstr (obstack, LCST ("'"));
2641             if (elem->result == wchar_iterate_ok)
2642               print_wchar (elem->chars[0], elem->buf, elem->buflen, width,
2643                            byte_order, obstack, quote_char, &need_escape);
2644             else
2645               print_wchar (gdb_WEOF, elem->buf, elem->buflen, width,
2646                            byte_order, obstack, quote_char, &need_escape);
2647             obstack_grow_wstr (obstack, LCST ("'"));
2648             s = xstrprintf (_(" <repeats %u times>"), elem->repeat_count);
2649             for (j = 0; s[j]; ++j)
2650               {
2651                 gdb_wchar_t w = gdb_btowc (s[j]);
2652                 obstack_grow (obstack, &w, sizeof (gdb_wchar_t));
2653               }
2654             xfree (s);
2655           }
2656           break;
2657
2658         case INCOMPLETE:
2659           /* We are outputting an incomplete sequence.  */
2660           if (last == SINGLE)
2661             {
2662               /* If we were outputting a string of SINGLE characters,
2663                  terminate the quote.  */
2664               obstack_grow (obstack, &wide_quote_char, sizeof (gdb_wchar_t));
2665             }
2666           if (last != START)
2667             obstack_grow_wstr (obstack, LCST (", "));
2668
2669           /* Output the incomplete sequence string.  */
2670           obstack_grow_wstr (obstack, LCST ("<incomplete sequence "));
2671           print_wchar (gdb_WEOF, elem->buf, elem->buflen, width, byte_order,
2672                        obstack, 0, &need_escape);
2673           obstack_grow_wstr (obstack, LCST (">"));
2674
2675           /* We do not attempt to outupt anything after this.  */
2676           state = FINISH;
2677           break;
2678
2679         case FINISH:
2680           /* All done.  If we were outputting a string of SINGLE
2681              characters, the string must be terminated.  Otherwise,
2682              REPEAT and INCOMPLETE are always left properly terminated.  */
2683           if (last == SINGLE)
2684             obstack_grow (obstack, &wide_quote_char, sizeof (gdb_wchar_t));
2685
2686           return;
2687         }
2688
2689       /* Get the next element and state.  */
2690       last = state;
2691       if (state != FINISH)
2692         {
2693           elem = VEC_index (converted_character_d, chars, idx++);
2694           switch (elem->result)
2695             {
2696             case wchar_iterate_ok:
2697             case wchar_iterate_invalid:
2698               if (elem->repeat_count > options->repeat_count_threshold)
2699                 state = REPEAT;
2700               else
2701                 state = SINGLE;
2702               break;
2703
2704             case wchar_iterate_incomplete:
2705               state = INCOMPLETE;
2706               break;
2707
2708             case wchar_iterate_eof:
2709               state = FINISH;
2710               break;
2711             }
2712         }
2713     }
2714 }
2715
2716 /* Print the character string STRING, printing at most LENGTH
2717    characters.  LENGTH is -1 if the string is nul terminated.  TYPE is
2718    the type of each character.  OPTIONS holds the printing options;
2719    printing stops early if the number hits print_max; repeat counts
2720    are printed as appropriate.  Print ellipses at the end if we had to
2721    stop before printing LENGTH characters, or if FORCE_ELLIPSES.
2722    QUOTE_CHAR is the character to print at each end of the string.  If
2723    C_STYLE_TERMINATOR is true, and the last character is 0, then it is
2724    omitted.  */
2725
2726 void
2727 generic_printstr (struct ui_file *stream, struct type *type, 
2728                   const gdb_byte *string, unsigned int length, 
2729                   const char *encoding, int force_ellipses,
2730                   int quote_char, int c_style_terminator,
2731                   const struct value_print_options *options)
2732 {
2733   enum bfd_endian byte_order = gdbarch_byte_order (get_type_arch (type));
2734   unsigned int i;
2735   int width = TYPE_LENGTH (type);
2736   struct obstack wchar_buf, output;
2737   struct cleanup *cleanup;
2738   struct wchar_iterator *iter;
2739   int finished = 0;
2740   struct converted_character *last;
2741   VEC (converted_character_d) *converted_chars;
2742
2743   if (length == -1)
2744     {
2745       unsigned long current_char = 1;
2746
2747       for (i = 0; current_char; ++i)
2748         {
2749           QUIT;
2750           current_char = extract_unsigned_integer (string + i * width,
2751                                                    width, byte_order);
2752         }
2753       length = i;
2754     }
2755
2756   /* If the string was not truncated due to `set print elements', and
2757      the last byte of it is a null, we don't print that, in
2758      traditional C style.  */
2759   if (c_style_terminator
2760       && !force_ellipses
2761       && length > 0
2762       && (extract_unsigned_integer (string + (length - 1) * width,
2763                                     width, byte_order) == 0))
2764     length--;
2765
2766   if (length == 0)
2767     {
2768       fputs_filtered ("\"\"", stream);
2769       return;
2770     }
2771
2772   /* Arrange to iterate over the characters, in wchar_t form.  */
2773   iter = make_wchar_iterator (string, length * width, encoding, width);
2774   cleanup = make_cleanup_wchar_iterator (iter);
2775   converted_chars = NULL;
2776   make_cleanup (VEC_cleanup (converted_character_d), &converted_chars);
2777
2778   /* Convert characters until the string is over or the maximum
2779      number of printed characters has been reached.  */
2780   i = 0;
2781   while (i < options->print_max)
2782     {
2783       int r;
2784
2785       QUIT;
2786
2787       /* Grab the next character and repeat count.  */
2788       r = count_next_character (iter, &converted_chars);
2789
2790       /* If less than zero, the end of the input string was reached.  */
2791       if (r < 0)
2792         break;
2793
2794       /* Otherwise, add the count to the total print count and get
2795          the next character.  */
2796       i += r;
2797     }
2798
2799   /* Get the last element and determine if the entire string was
2800      processed.  */
2801   last = VEC_last (converted_character_d, converted_chars);
2802   finished = (last->result == wchar_iterate_eof);
2803
2804   /* Ensure that CONVERTED_CHARS is terminated.  */
2805   last->result = wchar_iterate_eof;
2806
2807   /* WCHAR_BUF is the obstack we use to represent the string in
2808      wchar_t form.  */
2809   obstack_init (&wchar_buf);
2810   make_cleanup_obstack_free (&wchar_buf);
2811
2812   /* Print the output string to the obstack.  */
2813   print_converted_chars_to_obstack (&wchar_buf, converted_chars, quote_char,
2814                                     width, byte_order, options);
2815
2816   if (force_ellipses || !finished)
2817     obstack_grow_wstr (&wchar_buf, LCST ("..."));
2818
2819   /* OUTPUT is where we collect `char's for printing.  */
2820   obstack_init (&output);
2821   make_cleanup_obstack_free (&output);
2822
2823   convert_between_encodings (INTERMEDIATE_ENCODING, host_charset (),
2824                              (gdb_byte *) obstack_base (&wchar_buf),
2825                              obstack_object_size (&wchar_buf),
2826                              sizeof (gdb_wchar_t), &output, translit_char);
2827   obstack_1grow (&output, '\0');
2828
2829   fputs_filtered ((const char *) obstack_base (&output), stream);
2830
2831   do_cleanups (cleanup);
2832 }
2833
2834 /* Print a string from the inferior, starting at ADDR and printing up to LEN
2835    characters, of WIDTH bytes a piece, to STREAM.  If LEN is -1, printing
2836    stops at the first null byte, otherwise printing proceeds (including null
2837    bytes) until either print_max or LEN characters have been printed,
2838    whichever is smaller.  ENCODING is the name of the string's
2839    encoding.  It can be NULL, in which case the target encoding is
2840    assumed.  */
2841
2842 int
2843 val_print_string (struct type *elttype, const char *encoding,
2844                   CORE_ADDR addr, int len,
2845                   struct ui_file *stream,
2846                   const struct value_print_options *options)
2847 {
2848   int force_ellipsis = 0;       /* Force ellipsis to be printed if nonzero.  */
2849   int err;                      /* Non-zero if we got a bad read.  */
2850   int found_nul;                /* Non-zero if we found the nul char.  */
2851   unsigned int fetchlimit;      /* Maximum number of chars to print.  */
2852   int bytes_read;
2853   gdb_byte *buffer = NULL;      /* Dynamically growable fetch buffer.  */
2854   struct cleanup *old_chain = NULL;     /* Top of the old cleanup chain.  */
2855   struct gdbarch *gdbarch = get_type_arch (elttype);
2856   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
2857   int width = TYPE_LENGTH (elttype);
2858
2859   /* First we need to figure out the limit on the number of characters we are
2860      going to attempt to fetch and print.  This is actually pretty simple.  If
2861      LEN >= zero, then the limit is the minimum of LEN and print_max.  If
2862      LEN is -1, then the limit is print_max.  This is true regardless of
2863      whether print_max is zero, UINT_MAX (unlimited), or something in between,
2864      because finding the null byte (or available memory) is what actually
2865      limits the fetch.  */
2866
2867   fetchlimit = (len == -1 ? options->print_max : min (len,
2868                                                       options->print_max));
2869
2870   err = read_string (addr, len, width, fetchlimit, byte_order,
2871                      &buffer, &bytes_read);
2872   old_chain = make_cleanup (xfree, buffer);
2873
2874   addr += bytes_read;
2875
2876   /* We now have either successfully filled the buffer to fetchlimit,
2877      or terminated early due to an error or finding a null char when
2878      LEN is -1.  */
2879
2880   /* Determine found_nul by looking at the last character read.  */
2881   found_nul = 0;
2882   if (bytes_read >= width)
2883     found_nul = extract_unsigned_integer (buffer + bytes_read - width, width,
2884                                           byte_order) == 0;
2885   if (len == -1 && !found_nul)
2886     {
2887       gdb_byte *peekbuf;
2888
2889       /* We didn't find a NUL terminator we were looking for.  Attempt
2890          to peek at the next character.  If not successful, or it is not
2891          a null byte, then force ellipsis to be printed.  */
2892
2893       peekbuf = (gdb_byte *) alloca (width);
2894
2895       if (target_read_memory (addr, peekbuf, width) == 0
2896           && extract_unsigned_integer (peekbuf, width, byte_order) != 0)
2897         force_ellipsis = 1;
2898     }
2899   else if ((len >= 0 && err != 0) || (len > bytes_read / width))
2900     {
2901       /* Getting an error when we have a requested length, or fetching less
2902          than the number of characters actually requested, always make us
2903          print ellipsis.  */
2904       force_ellipsis = 1;
2905     }
2906
2907   /* If we get an error before fetching anything, don't print a string.
2908      But if we fetch something and then get an error, print the string
2909      and then the error message.  */
2910   if (err == 0 || bytes_read > 0)
2911     {
2912       LA_PRINT_STRING (stream, elttype, buffer, bytes_read / width,
2913                        encoding, force_ellipsis, options);
2914     }
2915
2916   if (err != 0)
2917     {
2918       char *str;
2919
2920       str = memory_error_message (TARGET_XFER_E_IO, gdbarch, addr);
2921       make_cleanup (xfree, str);
2922
2923       fprintf_filtered (stream, "<error: ");
2924       fputs_filtered (str, stream);
2925       fprintf_filtered (stream, ">");
2926     }
2927
2928   gdb_flush (stream);
2929   do_cleanups (old_chain);
2930
2931   return (bytes_read / width);
2932 }
2933 \f
2934
2935 /* The 'set input-radix' command writes to this auxiliary variable.
2936    If the requested radix is valid, INPUT_RADIX is updated; otherwise,
2937    it is left unchanged.  */
2938
2939 static unsigned input_radix_1 = 10;
2940
2941 /* Validate an input or output radix setting, and make sure the user
2942    knows what they really did here.  Radix setting is confusing, e.g.
2943    setting the input radix to "10" never changes it!  */
2944
2945 static void
2946 set_input_radix (char *args, int from_tty, struct cmd_list_element *c)
2947 {
2948   set_input_radix_1 (from_tty, input_radix_1);
2949 }
2950
2951 static void
2952 set_input_radix_1 (int from_tty, unsigned radix)
2953 {
2954   /* We don't currently disallow any input radix except 0 or 1, which don't
2955      make any mathematical sense.  In theory, we can deal with any input
2956      radix greater than 1, even if we don't have unique digits for every
2957      value from 0 to radix-1, but in practice we lose on large radix values.
2958      We should either fix the lossage or restrict the radix range more.
2959      (FIXME).  */
2960
2961   if (radix < 2)
2962     {
2963       input_radix_1 = input_radix;
2964       error (_("Nonsense input radix ``decimal %u''; input radix unchanged."),
2965              radix);
2966     }
2967   input_radix_1 = input_radix = radix;
2968   if (from_tty)
2969     {
2970       printf_filtered (_("Input radix now set to "
2971                          "decimal %u, hex %x, octal %o.\n"),
2972                        radix, radix, radix);
2973     }
2974 }
2975
2976 /* The 'set output-radix' command writes to this auxiliary variable.
2977    If the requested radix is valid, OUTPUT_RADIX is updated,
2978    otherwise, it is left unchanged.  */
2979
2980 static unsigned output_radix_1 = 10;
2981
2982 static void
2983 set_output_radix (char *args, int from_tty, struct cmd_list_element *c)
2984 {
2985   set_output_radix_1 (from_tty, output_radix_1);
2986 }
2987
2988 static void
2989 set_output_radix_1 (int from_tty, unsigned radix)
2990 {
2991   /* Validate the radix and disallow ones that we aren't prepared to
2992      handle correctly, leaving the radix unchanged.  */
2993   switch (radix)
2994     {
2995     case 16:
2996       user_print_options.output_format = 'x';   /* hex */
2997       break;
2998     case 10:
2999       user_print_options.output_format = 0;     /* decimal */
3000       break;
3001     case 8:
3002       user_print_options.output_format = 'o';   /* octal */
3003       break;
3004     default:
3005       output_radix_1 = output_radix;
3006       error (_("Unsupported output radix ``decimal %u''; "
3007                "output radix unchanged."),
3008              radix);
3009     }
3010   output_radix_1 = output_radix = radix;
3011   if (from_tty)
3012     {
3013       printf_filtered (_("Output radix now set to "
3014                          "decimal %u, hex %x, octal %o.\n"),
3015                        radix, radix, radix);
3016     }
3017 }
3018
3019 /* Set both the input and output radix at once.  Try to set the output radix
3020    first, since it has the most restrictive range.  An radix that is valid as
3021    an output radix is also valid as an input radix.
3022
3023    It may be useful to have an unusual input radix.  If the user wishes to
3024    set an input radix that is not valid as an output radix, he needs to use
3025    the 'set input-radix' command.  */
3026
3027 static void
3028 set_radix (char *arg, int from_tty)
3029 {
3030   unsigned radix;
3031
3032   radix = (arg == NULL) ? 10 : parse_and_eval_long (arg);
3033   set_output_radix_1 (0, radix);
3034   set_input_radix_1 (0, radix);
3035   if (from_tty)
3036     {
3037       printf_filtered (_("Input and output radices now set to "
3038                          "decimal %u, hex %x, octal %o.\n"),
3039                        radix, radix, radix);
3040     }
3041 }
3042
3043 /* Show both the input and output radices.  */
3044
3045 static void
3046 show_radix (char *arg, int from_tty)
3047 {
3048   if (from_tty)
3049     {
3050       if (input_radix == output_radix)
3051         {
3052           printf_filtered (_("Input and output radices set to "
3053                              "decimal %u, hex %x, octal %o.\n"),
3054                            input_radix, input_radix, input_radix);
3055         }
3056       else
3057         {
3058           printf_filtered (_("Input radix set to decimal "
3059                              "%u, hex %x, octal %o.\n"),
3060                            input_radix, input_radix, input_radix);
3061           printf_filtered (_("Output radix set to decimal "
3062                              "%u, hex %x, octal %o.\n"),
3063                            output_radix, output_radix, output_radix);
3064         }
3065     }
3066 }
3067 \f
3068
3069 static void
3070 set_print (char *arg, int from_tty)
3071 {
3072   printf_unfiltered (
3073      "\"set print\" must be followed by the name of a print subcommand.\n");
3074   help_list (setprintlist, "set print ", all_commands, gdb_stdout);
3075 }
3076
3077 static void
3078 show_print (char *args, int from_tty)
3079 {
3080   cmd_show_list (showprintlist, from_tty, "");
3081 }
3082
3083 static void
3084 set_print_raw (char *arg, int from_tty)
3085 {
3086   printf_unfiltered (
3087      "\"set print raw\" must be followed by the name of a \"print raw\" subcommand.\n");
3088   help_list (setprintrawlist, "set print raw ", all_commands, gdb_stdout);
3089 }
3090
3091 static void
3092 show_print_raw (char *args, int from_tty)
3093 {
3094   cmd_show_list (showprintrawlist, from_tty, "");
3095 }
3096
3097 \f
3098 void
3099 _initialize_valprint (void)
3100 {
3101   add_prefix_cmd ("print", no_class, set_print,
3102                   _("Generic command for setting how things print."),
3103                   &setprintlist, "set print ", 0, &setlist);
3104   add_alias_cmd ("p", "print", no_class, 1, &setlist);
3105   /* Prefer set print to set prompt.  */
3106   add_alias_cmd ("pr", "print", no_class, 1, &setlist);
3107
3108   add_prefix_cmd ("print", no_class, show_print,
3109                   _("Generic command for showing print settings."),
3110                   &showprintlist, "show print ", 0, &showlist);
3111   add_alias_cmd ("p", "print", no_class, 1, &showlist);
3112   add_alias_cmd ("pr", "print", no_class, 1, &showlist);
3113
3114   add_prefix_cmd ("raw", no_class, set_print_raw,
3115                   _("\
3116 Generic command for setting what things to print in \"raw\" mode."),
3117                   &setprintrawlist, "set print raw ", 0, &setprintlist);
3118   add_prefix_cmd ("raw", no_class, show_print_raw,
3119                   _("Generic command for showing \"print raw\" settings."),
3120                   &showprintrawlist, "show print raw ", 0, &showprintlist);
3121
3122   add_setshow_uinteger_cmd ("elements", no_class,
3123                             &user_print_options.print_max, _("\
3124 Set limit on string chars or array elements to print."), _("\
3125 Show limit on string chars or array elements to print."), _("\
3126 \"set print elements unlimited\" causes there to be no limit."),
3127                             NULL,
3128                             show_print_max,
3129                             &setprintlist, &showprintlist);
3130
3131   add_setshow_boolean_cmd ("null-stop", no_class,
3132                            &user_print_options.stop_print_at_null, _("\
3133 Set printing of char arrays to stop at first null char."), _("\
3134 Show printing of char arrays to stop at first null char."), NULL,
3135                            NULL,
3136                            show_stop_print_at_null,
3137                            &setprintlist, &showprintlist);
3138
3139   add_setshow_uinteger_cmd ("repeats", no_class,
3140                             &user_print_options.repeat_count_threshold, _("\
3141 Set threshold for repeated print elements."), _("\
3142 Show threshold for repeated print elements."), _("\
3143 \"set print repeats unlimited\" causes all elements to be individually printed."),
3144                             NULL,
3145                             show_repeat_count_threshold,
3146                             &setprintlist, &showprintlist);
3147
3148   add_setshow_boolean_cmd ("pretty", class_support,
3149                            &user_print_options.prettyformat_structs, _("\
3150 Set pretty formatting of structures."), _("\
3151 Show pretty formatting of structures."), NULL,
3152                            NULL,
3153                            show_prettyformat_structs,
3154                            &setprintlist, &showprintlist);
3155
3156   add_setshow_boolean_cmd ("union", class_support,
3157                            &user_print_options.unionprint, _("\
3158 Set printing of unions interior to structures."), _("\
3159 Show printing of unions interior to structures."), NULL,
3160                            NULL,
3161                            show_unionprint,
3162                            &setprintlist, &showprintlist);
3163
3164   add_setshow_boolean_cmd ("array", class_support,
3165                            &user_print_options.prettyformat_arrays, _("\
3166 Set pretty formatting of arrays."), _("\
3167 Show pretty formatting of arrays."), NULL,
3168                            NULL,
3169                            show_prettyformat_arrays,
3170                            &setprintlist, &showprintlist);
3171
3172   add_setshow_boolean_cmd ("address", class_support,
3173                            &user_print_options.addressprint, _("\
3174 Set printing of addresses."), _("\
3175 Show printing of addresses."), NULL,
3176                            NULL,
3177                            show_addressprint,
3178                            &setprintlist, &showprintlist);
3179
3180   add_setshow_boolean_cmd ("symbol", class_support,
3181                            &user_print_options.symbol_print, _("\
3182 Set printing of symbol names when printing pointers."), _("\
3183 Show printing of symbol names when printing pointers."),
3184                            NULL, NULL,
3185                            show_symbol_print,
3186                            &setprintlist, &showprintlist);
3187
3188   add_setshow_zuinteger_cmd ("input-radix", class_support, &input_radix_1,
3189                              _("\
3190 Set default input radix for entering numbers."), _("\
3191 Show default input radix for entering numbers."), NULL,
3192                              set_input_radix,
3193                              show_input_radix,
3194                              &setlist, &showlist);
3195
3196   add_setshow_zuinteger_cmd ("output-radix", class_support, &output_radix_1,
3197                              _("\
3198 Set default output radix for printing of values."), _("\
3199 Show default output radix for printing of values."), NULL,
3200                              set_output_radix,
3201                              show_output_radix,
3202                              &setlist, &showlist);
3203
3204   /* The "set radix" and "show radix" commands are special in that
3205      they are like normal set and show commands but allow two normally
3206      independent variables to be either set or shown with a single
3207      command.  So the usual deprecated_add_set_cmd() and [deleted]
3208      add_show_from_set() commands aren't really appropriate.  */
3209   /* FIXME: i18n: With the new add_setshow_integer command, that is no
3210      longer true - show can display anything.  */
3211   add_cmd ("radix", class_support, set_radix, _("\
3212 Set default input and output number radices.\n\
3213 Use 'set input-radix' or 'set output-radix' to independently set each.\n\
3214 Without an argument, sets both radices back to the default value of 10."),
3215            &setlist);
3216   add_cmd ("radix", class_support, show_radix, _("\
3217 Show the default input and output number radices.\n\
3218 Use 'show input-radix' or 'show output-radix' to independently show each."),
3219            &showlist);
3220
3221   add_setshow_boolean_cmd ("array-indexes", class_support,
3222                            &user_print_options.print_array_indexes, _("\
3223 Set printing of array indexes."), _("\
3224 Show printing of array indexes"), NULL, NULL, show_print_array_indexes,
3225                            &setprintlist, &showprintlist);
3226 }