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