2004-09-12 Andrew Cagney <cagney@gnu.org>
[platform/upstream/binutils.git] / gdb / valprint.c
1 /* Print values for GDB, the GNU debugger.
2
3    Copyright 1986, 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995,
4    1996, 1997, 1998, 1999, 2000, 2001, 2002 Free Software Foundation,
5    Inc.
6
7    This file is part of GDB.
8
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 2 of the License, or
12    (at your option) any later version.
13
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18
19    You should have received a copy of the GNU General Public License
20    along with this program; if not, write to the Free Software
21    Foundation, Inc., 59 Temple Place - Suite 330,
22    Boston, MA 02111-1307, USA.  */
23
24 #include "defs.h"
25 #include "gdb_string.h"
26 #include "symtab.h"
27 #include "gdbtypes.h"
28 #include "value.h"
29 #include "gdbcore.h"
30 #include "gdbcmd.h"
31 #include "target.h"
32 #include "language.h"
33 #include "annotate.h"
34 #include "valprint.h"
35 #include "floatformat.h"
36 #include "doublest.h"
37
38 #include <errno.h>
39
40 /* Prototypes for local functions */
41
42 static int partial_memory_read (CORE_ADDR memaddr, char *myaddr,
43                                 int len, int *errnoptr);
44
45 static void show_print (char *, int);
46
47 static void set_print (char *, int);
48
49 static void set_radix (char *, int);
50
51 static void show_radix (char *, int);
52
53 static void set_input_radix (char *, int, struct cmd_list_element *);
54
55 static void set_input_radix_1 (int, unsigned);
56
57 static void set_output_radix (char *, int, struct cmd_list_element *);
58
59 static void set_output_radix_1 (int, unsigned);
60
61 void _initialize_valprint (void);
62
63 /* Maximum number of chars to print for a string pointer value or vector
64    contents, or UINT_MAX for no limit.  Note that "set print elements 0"
65    stores UINT_MAX in print_max, which displays in a show command as
66    "unlimited". */
67
68 unsigned int print_max;
69 #define PRINT_MAX_DEFAULT 200   /* Start print_max off at this value. */
70
71 /* Default input and output radixes, and output format letter.  */
72
73 unsigned input_radix = 10;
74 unsigned output_radix = 10;
75 int output_format = 0;
76
77 /* Print repeat counts if there are more than this many repetitions of an
78    element in an array.  Referenced by the low level language dependent
79    print routines. */
80
81 unsigned int repeat_count_threshold = 10;
82
83 /* If nonzero, stops printing of char arrays at first null. */
84
85 int stop_print_at_null;
86
87 /* Controls pretty printing of structures. */
88
89 int prettyprint_structs;
90
91 /* Controls pretty printing of arrays.  */
92
93 int prettyprint_arrays;
94
95 /* If nonzero, causes unions inside structures or other unions to be
96    printed. */
97
98 int unionprint;                 /* Controls printing of nested unions.  */
99
100 /* If nonzero, causes machine addresses to be printed in certain contexts. */
101
102 int addressprint;               /* Controls printing of machine addresses */
103 \f
104
105 /* Print data of type TYPE located at VALADDR (within GDB), which came from
106    the inferior at address ADDRESS, onto stdio stream STREAM according to
107    FORMAT (a letter, or 0 for natural format using TYPE).
108
109    If DEREF_REF is nonzero, then dereference references, otherwise just print
110    them like pointers.
111
112    The PRETTY parameter controls prettyprinting.
113
114    If the data are a string pointer, returns the number of string characters
115    printed.
116
117    FIXME:  The data at VALADDR is in target byte order.  If gdb is ever
118    enhanced to be able to debug more than the single target it was compiled
119    for (specific CPU type and thus specific target byte ordering), then
120    either the print routines are going to have to take this into account,
121    or the data is going to have to be passed into here already converted
122    to the host byte ordering, whichever is more convenient. */
123
124
125 int
126 val_print (struct type *type, char *valaddr, int embedded_offset,
127            CORE_ADDR address, struct ui_file *stream, int format, int deref_ref,
128            int recurse, enum val_prettyprint pretty)
129 {
130   struct type *real_type = check_typedef (type);
131   if (pretty == Val_pretty_default)
132     {
133       pretty = prettyprint_structs ? Val_prettyprint : Val_no_prettyprint;
134     }
135
136   QUIT;
137
138   /* Ensure that the type is complete and not just a stub.  If the type is
139      only a stub and we can't find and substitute its complete type, then
140      print appropriate string and return.  */
141
142   if (TYPE_STUB (real_type))
143     {
144       fprintf_filtered (stream, "<incomplete type>");
145       gdb_flush (stream);
146       return (0);
147     }
148
149   return (LA_VAL_PRINT (type, valaddr, embedded_offset, address,
150                         stream, format, deref_ref, recurse, pretty));
151 }
152
153 /* Print the value VAL in C-ish syntax on stream STREAM.
154    FORMAT is a format-letter, or 0 for print in natural format of data type.
155    If the object printed is a string pointer, returns
156    the number of string bytes printed.  */
157
158 int
159 value_print (struct value *val, struct ui_file *stream, int format,
160              enum val_prettyprint pretty)
161 {
162   if (val == 0)
163     {
164       printf_filtered ("<address of value unknown>");
165       return 0;
166     }
167   if (VALUE_OPTIMIZED_OUT (val))
168     {
169       printf_filtered ("<value optimized out>");
170       return 0;
171     }
172   return LA_VALUE_PRINT (val, stream, format, pretty);
173 }
174
175 /* Called by various <lang>_val_print routines to print
176    TYPE_CODE_INT's.  TYPE is the type.  VALADDR is the address of the
177    value.  STREAM is where to print the value.  */
178
179 void
180 val_print_type_code_int (struct type *type, char *valaddr,
181                          struct ui_file *stream)
182 {
183   if (TYPE_LENGTH (type) > sizeof (LONGEST))
184     {
185       LONGEST val;
186
187       if (TYPE_UNSIGNED (type)
188           && extract_long_unsigned_integer (valaddr, TYPE_LENGTH (type),
189                                             &val))
190         {
191           print_longest (stream, 'u', 0, val);
192         }
193       else
194         {
195           /* Signed, or we couldn't turn an unsigned value into a
196              LONGEST.  For signed values, one could assume two's
197              complement (a reasonable assumption, I think) and do
198              better than this.  */
199           print_hex_chars (stream, (unsigned char *) valaddr,
200                            TYPE_LENGTH (type));
201         }
202     }
203   else
204     {
205       print_longest (stream, TYPE_UNSIGNED (type) ? 'u' : 'd', 0,
206                      unpack_long (type, valaddr));
207     }
208 }
209
210 /* Print a number according to FORMAT which is one of d,u,x,o,b,h,w,g.
211    The raison d'etre of this function is to consolidate printing of 
212    LONG_LONG's into this one function. The format chars b,h,w,g are 
213    from print_scalar_formatted().  Numbers are printed using C
214    format. 
215
216    USE_C_FORMAT means to use C format in all cases.  Without it, 
217    'o' and 'x' format do not include the standard C radix prefix
218    (leading 0 or 0x). 
219    
220    Hilfinger/2004-09-09: USE_C_FORMAT was originally called USE_LOCAL
221    and was intended to request formating according to the current
222    language and would be used for most integers that GDB prints.  The
223    exceptional cases were things like protocols where the format of
224    the integer is a protocol thing, not a user-visible thing).  The
225    parameter remains to preserve the information of what things might
226    be printed with language-specific format, should we ever resurrect
227    that capability. */
228
229 void
230 print_longest (struct ui_file *stream, int format, int use_c_format,
231                LONGEST val_long)
232 {
233   const char *val;
234
235   switch (format)
236     {
237     case 'd':
238       val = int_string (val_long, 10, 1, 0, 1); break;
239     case 'u':
240       val = int_string (val_long, 10, 0, 0, 1); break;
241     case 'x':
242       val = int_string (val_long, 16, 0, 0, use_c_format); break;
243     case 'b':
244       val = int_string (val_long, 16, 0, 2, 1); break;
245     case 'h':
246       val = int_string (val_long, 16, 0, 4, 1); break;
247     case 'w':
248       val = int_string (val_long, 16, 0, 8, 1); break;
249     case 'g':
250       val = int_string (val_long, 16, 0, 16, 1); break;
251       break;
252     case 'o':
253       val = int_string (val_long, 8, 0, 0, use_c_format); break;
254     default:
255       internal_error (__FILE__, __LINE__, "failed internal consistency check");
256     } 
257   fputs_filtered (val, stream);
258 }
259
260 /* This used to be a macro, but I don't think it is called often enough
261    to merit such treatment.  */
262 /* Convert a LONGEST to an int.  This is used in contexts (e.g. number of
263    arguments to a function, number in a value history, register number, etc.)
264    where the value must not be larger than can fit in an int.  */
265
266 int
267 longest_to_int (LONGEST arg)
268 {
269   /* Let the compiler do the work */
270   int rtnval = (int) arg;
271
272   /* Check for overflows or underflows */
273   if (sizeof (LONGEST) > sizeof (int))
274     {
275       if (rtnval != arg)
276         {
277           error ("Value out of range.");
278         }
279     }
280   return (rtnval);
281 }
282
283 /* Print a floating point value of type TYPE (not always a
284    TYPE_CODE_FLT), pointed to in GDB by VALADDR, on STREAM.  */
285
286 void
287 print_floating (char *valaddr, struct type *type, struct ui_file *stream)
288 {
289   DOUBLEST doub;
290   int inv;
291   const struct floatformat *fmt = NULL;
292   unsigned len = TYPE_LENGTH (type);
293
294   /* If it is a floating-point, check for obvious problems.  */
295   if (TYPE_CODE (type) == TYPE_CODE_FLT)
296     fmt = floatformat_from_type (type);
297   if (fmt != NULL && floatformat_is_nan (fmt, valaddr))
298     {
299       if (floatformat_is_negative (fmt, valaddr))
300         fprintf_filtered (stream, "-");
301       fprintf_filtered (stream, "nan(");
302       fputs_filtered ("0x", stream);
303       fputs_filtered (floatformat_mantissa (fmt, valaddr), stream);
304       fprintf_filtered (stream, ")");
305       return;
306     }
307
308   /* NOTE: cagney/2002-01-15: The TYPE passed into print_floating()
309      isn't necessarily a TYPE_CODE_FLT.  Consequently, unpack_double
310      needs to be used as that takes care of any necessary type
311      conversions.  Such conversions are of course direct to DOUBLEST
312      and disregard any possible target floating point limitations.
313      For instance, a u64 would be converted and displayed exactly on a
314      host with 80 bit DOUBLEST but with loss of information on a host
315      with 64 bit DOUBLEST.  */
316
317   doub = unpack_double (type, valaddr, &inv);
318   if (inv)
319     {
320       fprintf_filtered (stream, "<invalid float value>");
321       return;
322     }
323
324   /* FIXME: kettenis/2001-01-20: The following code makes too much
325      assumptions about the host and target floating point format.  */
326
327   /* NOTE: cagney/2002-02-03: Since the TYPE of what was passed in may
328      not necessarially be a TYPE_CODE_FLT, the below ignores that and
329      instead uses the type's length to determine the precision of the
330      floating-point value being printed.  */
331
332   if (len < sizeof (double))
333       fprintf_filtered (stream, "%.9g", (double) doub);
334   else if (len == sizeof (double))
335       fprintf_filtered (stream, "%.17g", (double) doub);
336   else
337 #ifdef PRINTF_HAS_LONG_DOUBLE
338     fprintf_filtered (stream, "%.35Lg", doub);
339 #else
340     /* This at least wins with values that are representable as
341        doubles.  */
342     fprintf_filtered (stream, "%.17g", (double) doub);
343 #endif
344 }
345
346 void
347 print_binary_chars (struct ui_file *stream, unsigned char *valaddr,
348                     unsigned len)
349 {
350
351 #define BITS_IN_BYTES 8
352
353   unsigned char *p;
354   unsigned int i;
355   int b;
356
357   /* Declared "int" so it will be signed.
358    * This ensures that right shift will shift in zeros.
359    */
360   const int mask = 0x080;
361
362   /* FIXME: We should be not printing leading zeroes in most cases.  */
363
364   if (TARGET_BYTE_ORDER == BFD_ENDIAN_BIG)
365     {
366       for (p = valaddr;
367            p < valaddr + len;
368            p++)
369         {
370           /* Every byte has 8 binary characters; peel off
371            * and print from the MSB end.
372            */
373           for (i = 0; i < (BITS_IN_BYTES * sizeof (*p)); i++)
374             {
375               if (*p & (mask >> i))
376                 b = 1;
377               else
378                 b = 0;
379
380               fprintf_filtered (stream, "%1d", b);
381             }
382         }
383     }
384   else
385     {
386       for (p = valaddr + len - 1;
387            p >= valaddr;
388            p--)
389         {
390           for (i = 0; i < (BITS_IN_BYTES * sizeof (*p)); i++)
391             {
392               if (*p & (mask >> i))
393                 b = 1;
394               else
395                 b = 0;
396
397               fprintf_filtered (stream, "%1d", b);
398             }
399         }
400     }
401 }
402
403 /* VALADDR points to an integer of LEN bytes.
404  * Print it in octal on stream or format it in buf.
405  */
406 void
407 print_octal_chars (struct ui_file *stream, unsigned char *valaddr, unsigned len)
408 {
409   unsigned char *p;
410   unsigned char octa1, octa2, octa3, carry;
411   int cycle;
412
413   /* FIXME: We should be not printing leading zeroes in most cases.  */
414
415
416   /* Octal is 3 bits, which doesn't fit.  Yuk.  So we have to track
417    * the extra bits, which cycle every three bytes:
418    *
419    * Byte side:       0            1             2          3
420    *                         |             |            |            |
421    * bit number   123 456 78 | 9 012 345 6 | 78 901 234 | 567 890 12 |
422    *
423    * Octal side:   0   1   carry  3   4  carry ...
424    *
425    * Cycle number:    0             1            2
426    *
427    * But of course we are printing from the high side, so we have to
428    * figure out where in the cycle we are so that we end up with no
429    * left over bits at the end.
430    */
431 #define BITS_IN_OCTAL 3
432 #define HIGH_ZERO     0340
433 #define LOW_ZERO      0016
434 #define CARRY_ZERO    0003
435 #define HIGH_ONE      0200
436 #define MID_ONE       0160
437 #define LOW_ONE       0016
438 #define CARRY_ONE     0001
439 #define HIGH_TWO      0300
440 #define MID_TWO       0070
441 #define LOW_TWO       0007
442
443   /* For 32 we start in cycle 2, with two bits and one bit carry;
444    * for 64 in cycle in cycle 1, with one bit and a two bit carry.
445    */
446   cycle = (len * BITS_IN_BYTES) % BITS_IN_OCTAL;
447   carry = 0;
448
449   fputs_filtered ("0", stream);
450   if (TARGET_BYTE_ORDER == BFD_ENDIAN_BIG)
451     {
452       for (p = valaddr;
453            p < valaddr + len;
454            p++)
455         {
456           switch (cycle)
457             {
458             case 0:
459               /* No carry in, carry out two bits.
460                */
461               octa1 = (HIGH_ZERO & *p) >> 5;
462               octa2 = (LOW_ZERO & *p) >> 2;
463               carry = (CARRY_ZERO & *p);
464               fprintf_filtered (stream, "%o", octa1);
465               fprintf_filtered (stream, "%o", octa2);
466               break;
467
468             case 1:
469               /* Carry in two bits, carry out one bit.
470                */
471               octa1 = (carry << 1) | ((HIGH_ONE & *p) >> 7);
472               octa2 = (MID_ONE & *p) >> 4;
473               octa3 = (LOW_ONE & *p) >> 1;
474               carry = (CARRY_ONE & *p);
475               fprintf_filtered (stream, "%o", octa1);
476               fprintf_filtered (stream, "%o", octa2);
477               fprintf_filtered (stream, "%o", octa3);
478               break;
479
480             case 2:
481               /* Carry in one bit, no carry out.
482                */
483               octa1 = (carry << 2) | ((HIGH_TWO & *p) >> 6);
484               octa2 = (MID_TWO & *p) >> 3;
485               octa3 = (LOW_TWO & *p);
486               carry = 0;
487               fprintf_filtered (stream, "%o", octa1);
488               fprintf_filtered (stream, "%o", octa2);
489               fprintf_filtered (stream, "%o", octa3);
490               break;
491
492             default:
493               error ("Internal error in octal conversion;");
494             }
495
496           cycle++;
497           cycle = cycle % BITS_IN_OCTAL;
498         }
499     }
500   else
501     {
502       for (p = valaddr + len - 1;
503            p >= valaddr;
504            p--)
505         {
506           switch (cycle)
507             {
508             case 0:
509               /* Carry out, no carry in */
510               octa1 = (HIGH_ZERO & *p) >> 5;
511               octa2 = (LOW_ZERO & *p) >> 2;
512               carry = (CARRY_ZERO & *p);
513               fprintf_filtered (stream, "%o", octa1);
514               fprintf_filtered (stream, "%o", octa2);
515               break;
516
517             case 1:
518               /* Carry in, carry out */
519               octa1 = (carry << 1) | ((HIGH_ONE & *p) >> 7);
520               octa2 = (MID_ONE & *p) >> 4;
521               octa3 = (LOW_ONE & *p) >> 1;
522               carry = (CARRY_ONE & *p);
523               fprintf_filtered (stream, "%o", octa1);
524               fprintf_filtered (stream, "%o", octa2);
525               fprintf_filtered (stream, "%o", octa3);
526               break;
527
528             case 2:
529               /* Carry in, no carry out */
530               octa1 = (carry << 2) | ((HIGH_TWO & *p) >> 6);
531               octa2 = (MID_TWO & *p) >> 3;
532               octa3 = (LOW_TWO & *p);
533               carry = 0;
534               fprintf_filtered (stream, "%o", octa1);
535               fprintf_filtered (stream, "%o", octa2);
536               fprintf_filtered (stream, "%o", octa3);
537               break;
538
539             default:
540               error ("Internal error in octal conversion;");
541             }
542
543           cycle++;
544           cycle = cycle % BITS_IN_OCTAL;
545         }
546     }
547
548 }
549
550 /* VALADDR points to an integer of LEN bytes.
551  * Print it in decimal on stream or format it in buf.
552  */
553 void
554 print_decimal_chars (struct ui_file *stream, unsigned char *valaddr,
555                      unsigned len)
556 {
557 #define TEN             10
558 #define TWO_TO_FOURTH   16
559 #define CARRY_OUT(  x ) ((x) / TEN)     /* extend char to int */
560 #define CARRY_LEFT( x ) ((x) % TEN)
561 #define SHIFT( x )      ((x) << 4)
562 #define START_P \
563         ((TARGET_BYTE_ORDER == BFD_ENDIAN_BIG) ? valaddr : valaddr + len - 1)
564 #define NOT_END_P \
565         ((TARGET_BYTE_ORDER == BFD_ENDIAN_BIG) ? (p < valaddr + len) : (p >= valaddr))
566 #define NEXT_P \
567         ((TARGET_BYTE_ORDER == BFD_ENDIAN_BIG) ? p++ : p-- )
568 #define LOW_NIBBLE(  x ) ( (x) & 0x00F)
569 #define HIGH_NIBBLE( x ) (((x) & 0x0F0) >> 4)
570
571   unsigned char *p;
572   unsigned char *digits;
573   int carry;
574   int decimal_len;
575   int i, j, decimal_digits;
576   int dummy;
577   int flip;
578
579   /* Base-ten number is less than twice as many digits
580    * as the base 16 number, which is 2 digits per byte.
581    */
582   decimal_len = len * 2 * 2;
583   digits = xmalloc (decimal_len);
584
585   for (i = 0; i < decimal_len; i++)
586     {
587       digits[i] = 0;
588     }
589
590   /* Ok, we have an unknown number of bytes of data to be printed in
591    * decimal.
592    *
593    * Given a hex number (in nibbles) as XYZ, we start by taking X and
594    * decemalizing it as "x1 x2" in two decimal nibbles.  Then we multiply
595    * the nibbles by 16, add Y and re-decimalize.  Repeat with Z.
596    *
597    * The trick is that "digits" holds a base-10 number, but sometimes
598    * the individual digits are > 10. 
599    *
600    * Outer loop is per nibble (hex digit) of input, from MSD end to
601    * LSD end.
602    */
603   decimal_digits = 0;           /* Number of decimal digits so far */
604   p = START_P;
605   flip = 0;
606   while (NOT_END_P)
607     {
608       /*
609        * Multiply current base-ten number by 16 in place.
610        * Each digit was between 0 and 9, now is between
611        * 0 and 144.
612        */
613       for (j = 0; j < decimal_digits; j++)
614         {
615           digits[j] = SHIFT (digits[j]);
616         }
617
618       /* Take the next nibble off the input and add it to what
619        * we've got in the LSB position.  Bottom 'digit' is now
620        * between 0 and 159.
621        *
622        * "flip" is used to run this loop twice for each byte.
623        */
624       if (flip == 0)
625         {
626           /* Take top nibble.
627            */
628           digits[0] += HIGH_NIBBLE (*p);
629           flip = 1;
630         }
631       else
632         {
633           /* Take low nibble and bump our pointer "p".
634            */
635           digits[0] += LOW_NIBBLE (*p);
636           NEXT_P;
637           flip = 0;
638         }
639
640       /* Re-decimalize.  We have to do this often enough
641        * that we don't overflow, but once per nibble is
642        * overkill.  Easier this way, though.  Note that the
643        * carry is often larger than 10 (e.g. max initial
644        * carry out of lowest nibble is 15, could bubble all
645        * the way up greater than 10).  So we have to do
646        * the carrying beyond the last current digit.
647        */
648       carry = 0;
649       for (j = 0; j < decimal_len - 1; j++)
650         {
651           digits[j] += carry;
652
653           /* "/" won't handle an unsigned char with
654            * a value that if signed would be negative.
655            * So extend to longword int via "dummy".
656            */
657           dummy = digits[j];
658           carry = CARRY_OUT (dummy);
659           digits[j] = CARRY_LEFT (dummy);
660
661           if (j >= decimal_digits && carry == 0)
662             {
663               /*
664                * All higher digits are 0 and we
665                * no longer have a carry.
666                *
667                * Note: "j" is 0-based, "decimal_digits" is
668                *       1-based.
669                */
670               decimal_digits = j + 1;
671               break;
672             }
673         }
674     }
675
676   /* Ok, now "digits" is the decimal representation, with
677    * the "decimal_digits" actual digits.  Print!
678    */
679   for (i = decimal_digits - 1; i >= 0; i--)
680     {
681       fprintf_filtered (stream, "%1d", digits[i]);
682     }
683   xfree (digits);
684 }
685
686 /* VALADDR points to an integer of LEN bytes.  Print it in hex on stream.  */
687
688 void
689 print_hex_chars (struct ui_file *stream, unsigned char *valaddr, unsigned len)
690 {
691   unsigned char *p;
692
693   /* FIXME: We should be not printing leading zeroes in most cases.  */
694
695   fputs_filtered ("0x", stream);
696   if (TARGET_BYTE_ORDER == BFD_ENDIAN_BIG)
697     {
698       for (p = valaddr;
699            p < valaddr + len;
700            p++)
701         {
702           fprintf_filtered (stream, "%02x", *p);
703         }
704     }
705   else
706     {
707       for (p = valaddr + len - 1;
708            p >= valaddr;
709            p--)
710         {
711           fprintf_filtered (stream, "%02x", *p);
712         }
713     }
714 }
715
716 /* VALADDR points to a char integer of LEN bytes.  Print it out in appropriate language form on stream.  
717    Omit any leading zero chars.  */
718
719 void
720 print_char_chars (struct ui_file *stream, unsigned char *valaddr, unsigned len)
721 {
722   unsigned char *p;
723
724   if (TARGET_BYTE_ORDER == BFD_ENDIAN_BIG)
725     {
726       p = valaddr;
727       while (p < valaddr + len - 1 && *p == 0)
728         ++p;
729
730       while (p < valaddr + len)
731         {
732           LA_EMIT_CHAR (*p, stream, '\'');
733           ++p;
734         }
735     }
736   else
737     {
738       p = valaddr + len - 1;
739       while (p > valaddr && *p == 0)
740         --p;
741
742       while (p >= valaddr)
743         {
744           LA_EMIT_CHAR (*p, stream, '\'');
745           --p;
746         }
747     }
748 }
749
750 /*  Called by various <lang>_val_print routines to print elements of an
751    array in the form "<elem1>, <elem2>, <elem3>, ...".
752
753    (FIXME?)  Assumes array element separator is a comma, which is correct
754    for all languages currently handled.
755    (FIXME?)  Some languages have a notation for repeated array elements,
756    perhaps we should try to use that notation when appropriate.
757  */
758
759 void
760 val_print_array_elements (struct type *type, char *valaddr, CORE_ADDR address,
761                           struct ui_file *stream, int format, int deref_ref,
762                           int recurse, enum val_prettyprint pretty,
763                           unsigned int i)
764 {
765   unsigned int things_printed = 0;
766   unsigned len;
767   struct type *elttype;
768   unsigned eltlen;
769   /* Position of the array element we are examining to see
770      whether it is repeated.  */
771   unsigned int rep1;
772   /* Number of repetitions we have detected so far.  */
773   unsigned int reps;
774
775   elttype = TYPE_TARGET_TYPE (type);
776   eltlen = TYPE_LENGTH (check_typedef (elttype));
777   len = TYPE_LENGTH (type) / eltlen;
778
779   annotate_array_section_begin (i, elttype);
780
781   for (; i < len && things_printed < print_max; i++)
782     {
783       if (i != 0)
784         {
785           if (prettyprint_arrays)
786             {
787               fprintf_filtered (stream, ",\n");
788               print_spaces_filtered (2 + 2 * recurse, stream);
789             }
790           else
791             {
792               fprintf_filtered (stream, ", ");
793             }
794         }
795       wrap_here (n_spaces (2 + 2 * recurse));
796
797       rep1 = i + 1;
798       reps = 1;
799       while ((rep1 < len) &&
800              !memcmp (valaddr + i * eltlen, valaddr + rep1 * eltlen, eltlen))
801         {
802           ++reps;
803           ++rep1;
804         }
805
806       if (reps > repeat_count_threshold)
807         {
808           val_print (elttype, valaddr + i * eltlen, 0, 0, stream, format,
809                      deref_ref, recurse + 1, pretty);
810           annotate_elt_rep (reps);
811           fprintf_filtered (stream, " <repeats %u times>", reps);
812           annotate_elt_rep_end ();
813
814           i = rep1 - 1;
815           things_printed += repeat_count_threshold;
816         }
817       else
818         {
819           val_print (elttype, valaddr + i * eltlen, 0, 0, stream, format,
820                      deref_ref, recurse + 1, pretty);
821           annotate_elt ();
822           things_printed++;
823         }
824     }
825   annotate_array_section_end ();
826   if (i < len)
827     {
828       fprintf_filtered (stream, "...");
829     }
830 }
831
832 /* Read LEN bytes of target memory at address MEMADDR, placing the
833    results in GDB's memory at MYADDR.  Returns a count of the bytes
834    actually read, and optionally an errno value in the location
835    pointed to by ERRNOPTR if ERRNOPTR is non-null. */
836
837 /* FIXME: cagney/1999-10-14: Only used by val_print_string.  Can this
838    function be eliminated.  */
839
840 static int
841 partial_memory_read (CORE_ADDR memaddr, char *myaddr, int len, int *errnoptr)
842 {
843   int nread;                    /* Number of bytes actually read. */
844   int errcode;                  /* Error from last read. */
845
846   /* First try a complete read. */
847   errcode = target_read_memory (memaddr, myaddr, len);
848   if (errcode == 0)
849     {
850       /* Got it all. */
851       nread = len;
852     }
853   else
854     {
855       /* Loop, reading one byte at a time until we get as much as we can. */
856       for (errcode = 0, nread = 0; len > 0 && errcode == 0; nread++, len--)
857         {
858           errcode = target_read_memory (memaddr++, myaddr++, 1);
859         }
860       /* If an error, the last read was unsuccessful, so adjust count. */
861       if (errcode != 0)
862         {
863           nread--;
864         }
865     }
866   if (errnoptr != NULL)
867     {
868       *errnoptr = errcode;
869     }
870   return (nread);
871 }
872
873 /*  Print a string from the inferior, starting at ADDR and printing up to LEN
874    characters, of WIDTH bytes a piece, to STREAM.  If LEN is -1, printing
875    stops at the first null byte, otherwise printing proceeds (including null
876    bytes) until either print_max or LEN characters have been printed,
877    whichever is smaller. */
878
879 /* FIXME: Use target_read_string.  */
880
881 int
882 val_print_string (CORE_ADDR addr, int len, int width, struct ui_file *stream)
883 {
884   int force_ellipsis = 0;       /* Force ellipsis to be printed if nonzero. */
885   int errcode;                  /* Errno returned from bad reads. */
886   unsigned int fetchlimit;      /* Maximum number of chars to print. */
887   unsigned int nfetch;          /* Chars to fetch / chars fetched. */
888   unsigned int chunksize;       /* Size of each fetch, in chars. */
889   char *buffer = NULL;          /* Dynamically growable fetch buffer. */
890   char *bufptr;                 /* Pointer to next available byte in buffer. */
891   char *limit;                  /* First location past end of fetch buffer. */
892   struct cleanup *old_chain = NULL;     /* Top of the old cleanup chain. */
893   int found_nul;                /* Non-zero if we found the nul char */
894
895   /* First we need to figure out the limit on the number of characters we are
896      going to attempt to fetch and print.  This is actually pretty simple.  If
897      LEN >= zero, then the limit is the minimum of LEN and print_max.  If
898      LEN is -1, then the limit is print_max.  This is true regardless of
899      whether print_max is zero, UINT_MAX (unlimited), or something in between,
900      because finding the null byte (or available memory) is what actually
901      limits the fetch. */
902
903   fetchlimit = (len == -1 ? print_max : min (len, print_max));
904
905   /* Now decide how large of chunks to try to read in one operation.  This
906      is also pretty simple.  If LEN >= zero, then we want fetchlimit chars,
907      so we might as well read them all in one operation.  If LEN is -1, we
908      are looking for a null terminator to end the fetching, so we might as
909      well read in blocks that are large enough to be efficient, but not so
910      large as to be slow if fetchlimit happens to be large.  So we choose the
911      minimum of 8 and fetchlimit.  We used to use 200 instead of 8 but
912      200 is way too big for remote debugging over a serial line.  */
913
914   chunksize = (len == -1 ? min (8, fetchlimit) : fetchlimit);
915
916   /* Loop until we either have all the characters to print, or we encounter
917      some error, such as bumping into the end of the address space. */
918
919   found_nul = 0;
920   old_chain = make_cleanup (null_cleanup, 0);
921
922   if (len > 0)
923     {
924       buffer = (char *) xmalloc (len * width);
925       bufptr = buffer;
926       old_chain = make_cleanup (xfree, buffer);
927
928       nfetch = partial_memory_read (addr, bufptr, len * width, &errcode)
929         / width;
930       addr += nfetch * width;
931       bufptr += nfetch * width;
932     }
933   else if (len == -1)
934     {
935       unsigned long bufsize = 0;
936       do
937         {
938           QUIT;
939           nfetch = min (chunksize, fetchlimit - bufsize);
940
941           if (buffer == NULL)
942             buffer = (char *) xmalloc (nfetch * width);
943           else
944             {
945               discard_cleanups (old_chain);
946               buffer = (char *) xrealloc (buffer, (nfetch + bufsize) * width);
947             }
948
949           old_chain = make_cleanup (xfree, buffer);
950           bufptr = buffer + bufsize * width;
951           bufsize += nfetch;
952
953           /* Read as much as we can. */
954           nfetch = partial_memory_read (addr, bufptr, nfetch * width, &errcode)
955             / width;
956
957           /* Scan this chunk for the null byte that terminates the string
958              to print.  If found, we don't need to fetch any more.  Note
959              that bufptr is explicitly left pointing at the next character
960              after the null byte, or at the next character after the end of
961              the buffer. */
962
963           limit = bufptr + nfetch * width;
964           while (bufptr < limit)
965             {
966               unsigned long c;
967
968               c = extract_unsigned_integer (bufptr, width);
969               addr += width;
970               bufptr += width;
971               if (c == 0)
972                 {
973                   /* We don't care about any error which happened after
974                      the NULL terminator.  */
975                   errcode = 0;
976                   found_nul = 1;
977                   break;
978                 }
979             }
980         }
981       while (errcode == 0       /* no error */
982              && bufptr - buffer < fetchlimit * width    /* no overrun */
983              && !found_nul);    /* haven't found nul yet */
984     }
985   else
986     {                           /* length of string is really 0! */
987       buffer = bufptr = NULL;
988       errcode = 0;
989     }
990
991   /* bufptr and addr now point immediately beyond the last byte which we
992      consider part of the string (including a '\0' which ends the string).  */
993
994   /* We now have either successfully filled the buffer to fetchlimit, or
995      terminated early due to an error or finding a null char when LEN is -1. */
996
997   if (len == -1 && !found_nul)
998     {
999       char *peekbuf;
1000
1001       /* We didn't find a null terminator we were looking for.  Attempt
1002          to peek at the next character.  If not successful, or it is not
1003          a null byte, then force ellipsis to be printed.  */
1004
1005       peekbuf = (char *) alloca (width);
1006
1007       if (target_read_memory (addr, peekbuf, width) == 0
1008           && extract_unsigned_integer (peekbuf, width) != 0)
1009         force_ellipsis = 1;
1010     }
1011   else if ((len >= 0 && errcode != 0) || (len > (bufptr - buffer) / width))
1012     {
1013       /* Getting an error when we have a requested length, or fetching less
1014          than the number of characters actually requested, always make us
1015          print ellipsis. */
1016       force_ellipsis = 1;
1017     }
1018
1019   QUIT;
1020
1021   /* If we get an error before fetching anything, don't print a string.
1022      But if we fetch something and then get an error, print the string
1023      and then the error message.  */
1024   if (errcode == 0 || bufptr > buffer)
1025     {
1026       if (addressprint)
1027         {
1028           fputs_filtered (" ", stream);
1029         }
1030       LA_PRINT_STRING (stream, buffer, (bufptr - buffer) / width, width, force_ellipsis);
1031     }
1032
1033   if (errcode != 0)
1034     {
1035       if (errcode == EIO)
1036         {
1037           fprintf_filtered (stream, " <Address ");
1038           print_address_numeric (addr, 1, stream);
1039           fprintf_filtered (stream, " out of bounds>");
1040         }
1041       else
1042         {
1043           fprintf_filtered (stream, " <Error reading address ");
1044           print_address_numeric (addr, 1, stream);
1045           fprintf_filtered (stream, ": %s>", safe_strerror (errcode));
1046         }
1047     }
1048   gdb_flush (stream);
1049   do_cleanups (old_chain);
1050   return ((bufptr - buffer) / width);
1051 }
1052 \f
1053
1054 /* Validate an input or output radix setting, and make sure the user
1055    knows what they really did here.  Radix setting is confusing, e.g.
1056    setting the input radix to "10" never changes it!  */
1057
1058 static void
1059 set_input_radix (char *args, int from_tty, struct cmd_list_element *c)
1060 {
1061   set_input_radix_1 (from_tty, input_radix);
1062 }
1063
1064 static void
1065 set_input_radix_1 (int from_tty, unsigned radix)
1066 {
1067   /* We don't currently disallow any input radix except 0 or 1, which don't
1068      make any mathematical sense.  In theory, we can deal with any input
1069      radix greater than 1, even if we don't have unique digits for every
1070      value from 0 to radix-1, but in practice we lose on large radix values.
1071      We should either fix the lossage or restrict the radix range more.
1072      (FIXME). */
1073
1074   if (radix < 2)
1075     {
1076       /* FIXME: cagney/2002-03-17: This needs to revert the bad radix
1077          value.  */
1078       error ("Nonsense input radix ``decimal %u''; input radix unchanged.",
1079              radix);
1080     }
1081   input_radix = radix;
1082   if (from_tty)
1083     {
1084       printf_filtered ("Input radix now set to decimal %u, hex %x, octal %o.\n",
1085                        radix, radix, radix);
1086     }
1087 }
1088
1089 static void
1090 set_output_radix (char *args, int from_tty, struct cmd_list_element *c)
1091 {
1092   set_output_radix_1 (from_tty, output_radix);
1093 }
1094
1095 static void
1096 set_output_radix_1 (int from_tty, unsigned radix)
1097 {
1098   /* Validate the radix and disallow ones that we aren't prepared to
1099      handle correctly, leaving the radix unchanged. */
1100   switch (radix)
1101     {
1102     case 16:
1103       output_format = 'x';      /* hex */
1104       break;
1105     case 10:
1106       output_format = 0;        /* decimal */
1107       break;
1108     case 8:
1109       output_format = 'o';      /* octal */
1110       break;
1111     default:
1112       /* FIXME: cagney/2002-03-17: This needs to revert the bad radix
1113          value.  */
1114       error ("Unsupported output radix ``decimal %u''; output radix unchanged.",
1115              radix);
1116     }
1117   output_radix = radix;
1118   if (from_tty)
1119     {
1120       printf_filtered ("Output radix now set to decimal %u, hex %x, octal %o.\n",
1121                        radix, radix, radix);
1122     }
1123 }
1124
1125 /* Set both the input and output radix at once.  Try to set the output radix
1126    first, since it has the most restrictive range.  An radix that is valid as
1127    an output radix is also valid as an input radix.
1128
1129    It may be useful to have an unusual input radix.  If the user wishes to
1130    set an input radix that is not valid as an output radix, he needs to use
1131    the 'set input-radix' command. */
1132
1133 static void
1134 set_radix (char *arg, int from_tty)
1135 {
1136   unsigned radix;
1137
1138   radix = (arg == NULL) ? 10 : parse_and_eval_long (arg);
1139   set_output_radix_1 (0, radix);
1140   set_input_radix_1 (0, radix);
1141   if (from_tty)
1142     {
1143       printf_filtered ("Input and output radices now set to decimal %u, hex %x, octal %o.\n",
1144                        radix, radix, radix);
1145     }
1146 }
1147
1148 /* Show both the input and output radices. */
1149
1150 static void
1151 show_radix (char *arg, int from_tty)
1152 {
1153   if (from_tty)
1154     {
1155       if (input_radix == output_radix)
1156         {
1157           printf_filtered ("Input and output radices set to decimal %u, hex %x, octal %o.\n",
1158                            input_radix, input_radix, input_radix);
1159         }
1160       else
1161         {
1162           printf_filtered ("Input radix set to decimal %u, hex %x, octal %o.\n",
1163                            input_radix, input_radix, input_radix);
1164           printf_filtered ("Output radix set to decimal %u, hex %x, octal %o.\n",
1165                            output_radix, output_radix, output_radix);
1166         }
1167     }
1168 }
1169 \f
1170
1171 static void
1172 set_print (char *arg, int from_tty)
1173 {
1174   printf_unfiltered (
1175      "\"set print\" must be followed by the name of a print subcommand.\n");
1176   help_list (setprintlist, "set print ", -1, gdb_stdout);
1177 }
1178
1179 static void
1180 show_print (char *args, int from_tty)
1181 {
1182   cmd_show_list (showprintlist, from_tty, "");
1183 }
1184 \f
1185 void
1186 _initialize_valprint (void)
1187 {
1188   struct cmd_list_element *c;
1189
1190   add_prefix_cmd ("print", no_class, set_print,
1191                   "Generic command for setting how things print.",
1192                   &setprintlist, "set print ", 0, &setlist);
1193   add_alias_cmd ("p", "print", no_class, 1, &setlist);
1194   /* prefer set print to set prompt */
1195   add_alias_cmd ("pr", "print", no_class, 1, &setlist);
1196
1197   add_prefix_cmd ("print", no_class, show_print,
1198                   "Generic command for showing print settings.",
1199                   &showprintlist, "show print ", 0, &showlist);
1200   add_alias_cmd ("p", "print", no_class, 1, &showlist);
1201   add_alias_cmd ("pr", "print", no_class, 1, &showlist);
1202
1203   deprecated_add_show_from_set
1204     (add_set_cmd ("elements", no_class, var_uinteger, (char *) &print_max,
1205                   "Set limit on string chars or array elements to print.\n\
1206 \"set print elements 0\" causes there to be no limit.",
1207                   &setprintlist),
1208      &showprintlist);
1209
1210   deprecated_add_show_from_set
1211     (add_set_cmd ("null-stop", no_class, var_boolean,
1212                   (char *) &stop_print_at_null,
1213                   "Set printing of char arrays to stop at first null char.",
1214                   &setprintlist),
1215      &showprintlist);
1216
1217   deprecated_add_show_from_set
1218     (add_set_cmd ("repeats", no_class, var_uinteger,
1219                   (char *) &repeat_count_threshold,
1220                   "Set threshold for repeated print elements.\n\
1221 \"set print repeats 0\" causes all elements to be individually printed.",
1222                   &setprintlist),
1223      &showprintlist);
1224
1225   deprecated_add_show_from_set
1226     (add_set_cmd ("pretty", class_support, var_boolean,
1227                   (char *) &prettyprint_structs,
1228                   "Set prettyprinting of structures.",
1229                   &setprintlist),
1230      &showprintlist);
1231
1232   deprecated_add_show_from_set
1233     (add_set_cmd ("union", class_support, var_boolean, (char *) &unionprint,
1234                   "Set printing of unions interior to structures.",
1235                   &setprintlist),
1236      &showprintlist);
1237
1238   deprecated_add_show_from_set
1239     (add_set_cmd ("array", class_support, var_boolean,
1240                   (char *) &prettyprint_arrays,
1241                   "Set prettyprinting of arrays.",
1242                   &setprintlist),
1243      &showprintlist);
1244
1245   deprecated_add_show_from_set
1246     (add_set_cmd ("address", class_support, var_boolean, (char *) &addressprint,
1247                   "Set printing of addresses.",
1248                   &setprintlist),
1249      &showprintlist);
1250
1251   c = add_set_cmd ("input-radix", class_support, var_uinteger,
1252                    (char *) &input_radix,
1253                    "Set default input radix for entering numbers.",
1254                    &setlist);
1255   deprecated_add_show_from_set (c, &showlist);
1256   set_cmd_sfunc (c, set_input_radix);
1257
1258   c = add_set_cmd ("output-radix", class_support, var_uinteger,
1259                    (char *) &output_radix,
1260                    "Set default output radix for printing of values.",
1261                    &setlist);
1262   deprecated_add_show_from_set (c, &showlist);
1263   set_cmd_sfunc (c, set_output_radix);
1264
1265   /* The "set radix" and "show radix" commands are special in that
1266      they are like normal set and show commands but allow two normally
1267      independent variables to be either set or shown with a single
1268      command.  So the usual deprecated_add_set_cmd() and
1269      add_show_from_set() commands aren't really appropriate. */
1270   add_cmd ("radix", class_support, set_radix,
1271            "Set default input and output number radices.\n\
1272 Use 'set input-radix' or 'set output-radix' to independently set each.\n\
1273 Without an argument, sets both radices back to the default value of 10.",
1274            &setlist);
1275   add_cmd ("radix", class_support, show_radix,
1276            "Show the default input and output number radices.\n\
1277 Use 'show input-radix' or 'show output-radix' to independently show each.",
1278            &showlist);
1279
1280   /* Give people the defaults which they are used to.  */
1281   prettyprint_structs = 0;
1282   prettyprint_arrays = 0;
1283   unionprint = 1;
1284   addressprint = 1;
1285   print_max = PRINT_MAX_DEFAULT;
1286 }