(OFF_T_MAX): Remove definition.
[platform/upstream/coreutils.git] / src / od.c
1 /* od -- dump files in octal and other formats
2    Copyright (C) 92, 95, 1996 Free Software Foundation, Inc.
3
4    This program is free software; you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation; either version 2, or (at your option)
7    any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program; if not, write to the Free Software Foundation,
16    Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
17
18 /* Written by Jim Meyering.  */
19
20 /* AIX requires this to be the first thing in the file.  */
21 #include <config.h>
22
23 #ifdef __GNUC__
24 #define alloca __builtin_alloca
25 #else /* not __GNUC__ */
26 #if HAVE_ALLOCA_H
27 #include <alloca.h>
28 #else /* not HAVE_ALLOCA_H */
29 #ifdef _AIX
30  #pragma alloca
31 #else /* not _AIX */
32 #ifdef _WIN32
33 #include <malloc.h>
34 #include <io.h>
35 #else
36 char *alloca ();
37 #endif /* not _WIN32 */
38 #endif /* not _AIX */
39 #endif /* not HAVE_ALLOCA_H */
40 #endif /* not __GNUC__ */
41
42 #include <stdio.h>
43 #include <assert.h>
44 #include <getopt.h>
45 #include <sys/types.h>
46 #include "system.h"
47 #include "xstrtoul.h"
48 #include "error.h"
49
50 #if defined(__GNUC__) || defined(STDC_HEADERS)
51 #include <float.h>
52 #endif
53
54 #ifdef HAVE_LONG_DOUBLE
55 typedef long double LONG_DOUBLE;
56 #else
57 typedef double LONG_DOUBLE;
58 #endif
59
60 #if HAVE_LIMITS_H
61 # include <limits.h>
62 #endif
63 #ifndef SCHAR_MAX
64 # define SCHAR_MAX 127
65 #endif
66 #ifndef SCHAR_MIN
67 # define SCHAR_MIN (-128)
68 #endif
69 #ifndef SHRT_MAX
70 # define SHRT_MAX 32767
71 #endif
72 #ifndef SHRT_MIN
73 # define SHRT_MIN (-32768)
74 #endif
75 #ifndef ULONG_MAX
76 # define ULONG_MAX ((unsigned long) ~(unsigned long) 0)
77 #endif
78
79 #if HAVE_VALUES_H
80 # include <values.h>
81 #endif
82
83 #ifndef BITSPERBYTE
84 # define BITSPERBYTE 8
85 #endif
86
87 #define STREQ(a,b) (strcmp((a), (b)) == 0)
88
89 #ifndef MAX
90 # define MAX(a, b) ((a) > (b) ? (a) : (b))
91 #endif
92
93 #ifndef MIN
94 # define MIN(a,b) (((a) < (b)) ? (a) : (b))
95 #endif
96
97 #if defined (_WIN32) && defined (_O_BINARY)
98 # define WINDOWS_SETFILEMODE_BINARY(IN_STREAM, FILENAME)                \
99     do                                                                  \
100       { /* Turn off DOS text file modes, "rb" doesn't work on stdin.  */\
101         if (_setmode (_fileno ((IN_STREAM)), _O_BINARY) == -1)          \
102           {                                                             \
103             error (0, errno, "%s", (FILENAME));                         \
104             err = 1;                                                    \
105             continue;                                                   \
106           }                                                             \
107       }                                                                 \
108     while (0)
109 #else
110 # define WINDOWS_SETFILEMODE_BINARY(IN_STREAM, FILENAME) /* empty */
111 #endif
112
113 /* The default number of input bytes per output line.  */
114 #define DEFAULT_BYTES_PER_BLOCK 16
115
116 /* The number of decimal digits of precision in a float.  */
117 #ifndef FLT_DIG
118 # define FLT_DIG 7
119 #endif
120
121 /* The number of decimal digits of precision in a double.  */
122 #ifndef DBL_DIG
123 # define DBL_DIG 15
124 #endif
125
126 /* The number of decimal digits of precision in a long double.  */
127 #ifndef LDBL_DIG
128 # define LDBL_DIG DBL_DIG
129 #endif
130
131 char *xmalloc ();
132 char *xrealloc ();
133
134 enum size_spec
135   {
136     NO_SIZE,
137     CHAR,
138     SHORT,
139     INT,
140     LONG,
141     FLOAT_SINGLE,
142     FLOAT_DOUBLE,
143     FLOAT_LONG_DOUBLE
144   };
145
146 enum output_format
147   {
148     SIGNED_DECIMAL,
149     UNSIGNED_DECIMAL,
150     OCTAL,
151     HEXADECIMAL,
152     FLOATING_POINT,
153     NAMED_CHARACTER,
154     CHARACTER
155   };
156
157 /* Each output format specification (from POSIX `-t spec' or from
158    old-style options) is represented by one of these structures.  */
159 struct tspec
160   {
161     enum output_format fmt;
162     enum size_spec size;
163     void (*print_function) ();
164     char *fmt_string;
165   };
166
167 /* The name this program was run with.  */
168 char *program_name;
169
170 /* Convert the number of 8-bit bytes of a binary representation to
171    the number of characters (digits + sign if the type is signed)
172    required to represent the same quantity in the specified base/type.
173    For example, a 32-bit (4-byte) quantity may require a field width
174    as wide as the following for these types:
175    11   unsigned octal
176    11   signed decimal
177    10   unsigned decimal
178    8    unsigned hexadecimal  */
179
180 static const unsigned int bytes_to_oct_digits[] =
181 {0, 3, 6, 8, 11, 14, 16, 19, 22, 25, 27, 30, 32, 35, 38, 41, 43};
182
183 static const unsigned int bytes_to_signed_dec_digits[] =
184 {1, 4, 6, 8, 11, 13, 16, 18, 20, 23, 25, 28, 30, 33, 35, 37, 40};
185
186 static const unsigned int bytes_to_unsigned_dec_digits[] =
187 {0, 3, 5, 8, 10, 13, 15, 17, 20, 22, 25, 27, 29, 32, 34, 37, 39};
188
189 static const unsigned int bytes_to_hex_digits[] =
190 {0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32};
191
192 /* Convert enum size_spec to the size of the named type.  */
193 static const int width_bytes[] =
194 {
195   -1,
196   sizeof (char),
197   sizeof (short int),
198   sizeof (int),
199   sizeof (long int),
200   sizeof (float),
201   sizeof (double),
202   sizeof (LONG_DOUBLE)
203 };
204
205 /* Names for some non-printing characters.  */
206 static const char *const charname[33] =
207 {
208   "nul", "soh", "stx", "etx", "eot", "enq", "ack", "bel",
209   "bs", "ht", "nl", "vt", "ff", "cr", "so", "si",
210   "dle", "dc1", "dc2", "dc3", "dc4", "nak", "syn", "etb",
211   "can", "em", "sub", "esc", "fs", "gs", "rs", "us",
212   "sp"
213 };
214
215 /* A printf control string for printing a file offset.  */
216 static const char *output_address_fmt_string;
217
218 /* FIXME: make this the number of octal digits in an unsigned long.  */
219 #define MAX_ADDRESS_LENGTH 13
220
221 /* Space for a normal address, a space, a pseudo address, parentheses
222    around the pseudo address, and a trailing zero byte. */
223 static char address_fmt_buffer[2 * MAX_ADDRESS_LENGTH + 4];
224 static char address_pad[MAX_ADDRESS_LENGTH + 1];
225
226 static unsigned long int string_min;
227 static unsigned long int flag_dump_strings;
228
229 /* Non-zero if we should recognize the pre-POSIX non-option arguments
230    that specified at most one file and optional arguments specifying
231    offset and pseudo-start address.  */
232 static int traditional;
233
234 /* Non-zero if an old-style `pseudo-address' was specified.  */
235 static long int flag_pseudo_start;
236
237 /* The difference between the old-style pseudo starting address and
238    the number of bytes to skip.  */
239 static long int pseudo_offset;
240
241 /* Function to format an address and optionally an additional parenthesized
242    pseudo-address; it returns the formatted string.  */
243 static const char *(*format_address) __P ((long unsigned int));
244
245 /* The number of input bytes to skip before formatting and writing.  */
246 static off_t n_bytes_to_skip = 0;
247
248 /* When nonzero, MAX_BYTES_TO_FORMAT is the maximum number of bytes
249    to be read and formatted.  Otherwise all input is formatted.  */
250 static int limit_bytes_to_format = 0;
251
252 /* The maximum number of bytes that will be formatted.  This
253    value is used only when LIMIT_BYTES_TO_FORMAT is nonzero.  */
254 static off_t max_bytes_to_format;
255
256 /* When nonzero and two or more consecutive blocks are equal, format
257    only the first block and output an asterisk alone on the following
258    line to indicate that identical blocks have been elided.  */
259 static int abbreviate_duplicate_blocks = 1;
260
261 /* An array of specs describing how to format each input block.  */
262 static struct tspec *spec;
263
264 /* The number of format specs.  */
265 static unsigned int n_specs;
266
267 /* The allocated length of SPEC.  */
268 static unsigned int n_specs_allocated;
269
270 /* The number of input bytes formatted per output line.  It must be
271    a multiple of the least common multiple of the sizes associated with
272    the specified output types.  It should be as large as possible, but
273    no larger than 16 -- unless specified with the -w option.  */
274 static unsigned int bytes_per_block;
275
276 /* Human-readable representation of *file_list (for error messages).
277    It differs from *file_list only when *file_list is "-".  */
278 static char const *input_filename;
279
280 /* A NULL-terminated list of the file-arguments from the command line.
281    If no file-arguments were specified, this variable is initialized
282    to { "-", NULL }.  */
283 static char const *const *file_list;
284
285 /* The input stream associated with the current file.  */
286 static FILE *in_stream;
287
288 /* If nonzero, at least one of the files we read was standard input.  */
289 static int have_read_stdin;
290
291 #define LONGEST_INTEGRAL_TYPE long int
292
293 #define MAX_INTEGRAL_TYPE_SIZE sizeof(LONGEST_INTEGRAL_TYPE)
294 static enum size_spec integral_type_size[MAX_INTEGRAL_TYPE_SIZE + 1];
295
296 #define MAX_FP_TYPE_SIZE sizeof(LONG_DOUBLE)
297 static enum size_spec fp_type_size[MAX_FP_TYPE_SIZE + 1];
298
299 /* If nonzero, display usage information and exit.  */
300 static int show_help;
301
302 /* If nonzero, print the version on standard output then exit.  */
303 static int show_version;
304
305 static struct option const long_options[] =
306 {
307   /* POSIX options.  */
308   {"skip-bytes", required_argument, NULL, 'j'},
309   {"address-radix", required_argument, NULL, 'A'},
310   {"read-bytes", required_argument, NULL, 'N'},
311   {"format", required_argument, NULL, 't'},
312   {"output-duplicates", no_argument, NULL, 'v'},
313
314   /* non-POSIX options.  */
315   {"strings", optional_argument, NULL, 's'},
316   {"traditional", no_argument, NULL, 'B'},
317   {"width", optional_argument, NULL, 'w'},
318   {"help", no_argument, &show_help, 1},
319   {"version", no_argument, &show_version, 1},
320   {NULL, 0, NULL, 0}
321 };
322
323 static void
324 usage (int status)
325 {
326   if (status != 0)
327     fprintf (stderr, _("Try `%s --help' for more information.\n"),
328              program_name);
329   else
330     {
331       printf (_("\
332 Usage: %s [OPTION]... [FILE]...\n\
333   or:  %s --traditional [FILE] [[+]OFFSET [[+]LABEL]]\n\
334 "),
335               program_name, program_name);
336       printf (_("\
337 Write an unambiguous representation, octal bytes by default, of FILE\n\
338 to standard output.  With no FILE, or when FILE is -, read standard input.\n\
339 \n\
340   -A, --address-radix=RADIX   decide how file offsets are printed\n\
341   -N, --read-bytes=BYTES      limit dump to BYTES input bytes per file\n\
342   -j, --skip-bytes=BYTES      skip BYTES input bytes first on each file\n\
343   -s, --strings[=BYTES]       output strings of at least BYTES graphic chars\n\
344   -t, --format=TYPE           select output format or formats\n\
345   -v, --output-duplicates     do not use * to mark line suppression\n\
346   -w, --width[=BYTES]         output BYTES bytes per output line\n\
347       --traditional           accept arguments in pre-POSIX form\n\
348       --help                  display this help and exit\n\
349       --version               output version information and exit\n\
350 \n\
351 Pre-POSIX format specifications may be intermixed, they accumulate:\n\
352   -a   same as -t a,  select named characters\n\
353   -b   same as -t oC, select octal bytes\n\
354   -c   same as -t c,  select ASCII characters or backslash escapes\n\
355   -d   same as -t u2, select unsigned decimal shorts\n\
356   -f   same as -t fF, select floats\n\
357   -h   same as -t x2, select hexadecimal shorts\n\
358   -i   same as -t d2, select decimal shorts\n\
359   -l   same as -t d4, select decimal longs\n\
360   -o   same as -t o2, select octal shorts\n\
361   -x   same as -t x2, select hexadecimal shorts\n\
362 "));
363       printf (_("\
364 \n\
365 For older syntax (second call format), OFFSET means -j OFFSET.  LABEL\n\
366 is the pseudo-address at first byte printed, incremented when dump is\n\
367 progressing.  For OFFSET and LABEL, a 0x or 0X prefix indicates\n\
368 hexadecimal, suffixes maybe . for octal and b multiply by 512.\n\
369 \n\
370 TYPE is made up of one or more of these specifications:\n\
371 \n\
372   a          named character\n\
373   c          ASCII character or backslash escape\n\
374   d[SIZE]    signed decimal, SIZE bytes per integer\n\
375   f[SIZE]    floating point, SIZE bytes per integer\n\
376   o[SIZE]    octal, SIZE bytes per integer\n\
377   u[SIZE]    unsigned decimal, SIZE bytes per integer\n\
378   x[SIZE]    hexadecimal, SIZE bytes per integer\n\
379 \n\
380 SIZE is a number.  For TYPE in doux, SIZE may also be C for\n\
381 sizeof(char), S for sizeof(short), I for sizeof(int) or L for\n\
382 sizeof(long).  If TYPE is f, SIZE may also be F for sizeof(float), D\n\
383 for sizeof(double) or L for sizeof(long double).\n\
384 \n\
385 RADIX is d for decimal, o for octal, x for hexadecimal or n for none.\n\
386 BYTES is hexadecimal with 0x or 0X prefix, it is multiplied by 512\n\
387 with b suffix, by 1024 with k and by 1048576 with m.  -s without a\n\
388 number implies 3.  -w without a number implies 32.  By default, od\n\
389 uses -A o -t d2 -w 16.\n\
390 "));
391     }
392   exit (status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
393 }
394
395 /* Compute the greatest common denominator of U and V
396    using Euclid's algorithm.  */
397
398 static unsigned int
399 gcd (unsigned int u, unsigned int v)
400 {
401   unsigned int t;
402   while (v != 0)
403     {
404       t = u % v;
405       u = v;
406       v = t;
407     }
408   return u;
409 }
410
411 /* Compute the least common multiple of U and V.  */
412
413 static unsigned int
414 lcm (unsigned int u, unsigned int v)
415 {
416   unsigned int t = gcd (u, v);
417   if (t == 0)
418     return 0;
419   return u * v / t;
420 }
421
422 static void
423 print_s_char (long unsigned int n_bytes, const char *block,
424               const char *fmt_string)
425 {
426   int i;
427   for (i = n_bytes; i > 0; i--)
428     {
429       int tmp = (unsigned) *(const unsigned char *) block;
430       if (tmp > SCHAR_MAX)
431         tmp -= SCHAR_MAX - SCHAR_MIN + 1;
432       assert (tmp <= SCHAR_MAX);
433       printf (fmt_string, tmp, (i == 1 ? '\n' : ' '));
434       block += sizeof (unsigned char);
435     }
436 }
437
438 static void
439 print_char (long unsigned int n_bytes, const char *block,
440             const char *fmt_string)
441 {
442   int i;
443   for (i = n_bytes; i > 0; i--)
444     {
445       unsigned int tmp = *(const unsigned char *) block;
446       printf (fmt_string, tmp, (i == 1 ? '\n' : ' '));
447       block += sizeof (unsigned char);
448     }
449 }
450
451 static void
452 print_s_short (long unsigned int n_bytes, const char *block,
453                const char *fmt_string)
454 {
455   int i;
456   for (i = n_bytes / sizeof (unsigned short); i > 0; i--)
457     {
458       int tmp = (unsigned) *(const unsigned short *) block;
459       if (tmp > SHRT_MAX)
460         tmp -= SHRT_MAX - SHRT_MIN + 1;
461       assert (tmp <= SHRT_MAX);
462       printf (fmt_string, tmp, (i == 1 ? '\n' : ' '));
463       block += sizeof (unsigned short);
464     }
465 }
466 static void
467 print_short (long unsigned int n_bytes, const char *block,
468              const char *fmt_string)
469 {
470   int i;
471   for (i = n_bytes / sizeof (unsigned short); i > 0; i--)
472     {
473       unsigned int tmp = *(const unsigned short *) block;
474       printf (fmt_string, tmp, (i == 1 ? '\n' : ' '));
475       block += sizeof (unsigned short);
476     }
477 }
478
479 static void
480 print_int (long unsigned int n_bytes, const char *block,
481            const char *fmt_string)
482 {
483   int i;
484   for (i = n_bytes / sizeof (unsigned int); i > 0; i--)
485     {
486       unsigned int tmp = *(const unsigned int *) block;
487       printf (fmt_string, tmp, (i == 1 ? '\n' : ' '));
488       block += sizeof (unsigned int);
489     }
490 }
491
492 static void
493 print_long (long unsigned int n_bytes, const char *block,
494             const char *fmt_string)
495 {
496   int i;
497   for (i = n_bytes / sizeof (unsigned long); i > 0; i--)
498     {
499       unsigned long tmp = *(const unsigned long *) block;
500       printf (fmt_string, tmp, (i == 1 ? '\n' : ' '));
501       block += sizeof (unsigned long);
502     }
503 }
504
505 static void
506 print_float (long unsigned int n_bytes, const char *block,
507              const char *fmt_string)
508 {
509   int i;
510   for (i = n_bytes / sizeof (float); i > 0; i--)
511     {
512       float tmp = *(const float *) block;
513       printf (fmt_string, tmp, (i == 1 ? '\n' : ' '));
514       block += sizeof (float);
515     }
516 }
517
518 static void
519 print_double (long unsigned int n_bytes, const char *block,
520               const char *fmt_string)
521 {
522   int i;
523   for (i = n_bytes / sizeof (double); i > 0; i--)
524     {
525       double tmp = *(const double *) block;
526       printf (fmt_string, tmp, (i == 1 ? '\n' : ' '));
527       block += sizeof (double);
528     }
529 }
530
531 #ifdef HAVE_LONG_DOUBLE
532 static void
533 print_long_double (long unsigned int n_bytes, const char *block,
534                    const char *fmt_string)
535 {
536   int i;
537   for (i = n_bytes / sizeof (LONG_DOUBLE); i > 0; i--)
538     {
539       LONG_DOUBLE tmp = *(const LONG_DOUBLE *) block;
540       printf (fmt_string, tmp, (i == 1 ? '\n' : ' '));
541       block += sizeof (LONG_DOUBLE);
542     }
543 }
544
545 #endif
546
547 static void
548 print_named_ascii (long unsigned int n_bytes, const char *block,
549                    const char *unused_fmt_string)
550 {
551   int i;
552   for (i = n_bytes; i > 0; i--)
553     {
554       unsigned int c = *(const unsigned char *) block;
555       unsigned int masked_c = (0x7f & c);
556       const char *s;
557       char buf[5];
558
559       if (masked_c == 127)
560         s = "del";
561       else if (masked_c <= 040)
562         s = charname[masked_c];
563       else
564         {
565           sprintf (buf, "  %c", masked_c);
566           s = buf;
567         }
568
569       printf ("%3s%c", s, (i == 1 ? '\n' : ' '));
570       block += sizeof (unsigned char);
571     }
572 }
573
574 static void
575 print_ascii (long unsigned int n_bytes, const char *block,
576              const char *unused_fmt_string)
577 {
578   int i;
579   for (i = n_bytes; i > 0; i--)
580     {
581       unsigned int c = *(const unsigned char *) block;
582       const char *s;
583       char buf[5];
584
585       switch (c)
586         {
587         case '\0':
588           s = " \\0";
589           break;
590
591         case '\007':
592           s = " \\a";
593           break;
594
595         case '\b':
596           s = " \\b";
597           break;
598
599         case '\f':
600           s = " \\f";
601           break;
602
603         case '\n':
604           s = " \\n";
605           break;
606
607         case '\r':
608           s = " \\r";
609           break;
610
611         case '\t':
612           s = " \\t";
613           break;
614
615         case '\v':
616           s = " \\v";
617           break;
618
619         default:
620           sprintf (buf, (ISPRINT (c) ? "  %c" : "%03o"), c);
621           s = (const char *) buf;
622         }
623
624       printf ("%3s%c", s, (i == 1 ? '\n' : ' '));
625       block += sizeof (unsigned char);
626     }
627 }
628
629 /* Convert a null-terminated (possibly zero-length) string S to an
630    unsigned long integer value.  If S points to a non-digit set *P to S,
631    *VAL to 0, and return 0.  Otherwise, accumulate the integer value of
632    the string of digits.  If the string of digits represents a value
633    larger than ULONG_MAX, don't modify *VAL or *P and return nonzero.
634    Otherwise, advance *P to the first non-digit after S, set *VAL to
635    the result of the conversion and return zero.  */
636
637 static int
638 simple_strtoul (const char *s, const char **p, long unsigned int *val)
639 {
640   unsigned long int sum;
641
642   sum = 0;
643   while (ISDIGIT (*s))
644     {
645       unsigned int c = *s++ - '0';
646       if (sum > (ULONG_MAX - c) / 10)
647         return 1;
648       sum = sum * 10 + c;
649     }
650   *p = s;
651   *val = sum;
652   return 0;
653 }
654
655 /* If S points to a single valid POSIX-style od format string, put
656    a description of that format in *TSPEC, make *NEXT point at the
657    character following the just-decoded format (if *NEXT is non-NULL),
658    and return zero.  If S is not valid, don't modify *NEXT or *TSPEC,
659    give a diagnostic, and return nonzero.  For example, if S were
660    "d4afL" *NEXT would be set to "afL" and *TSPEC would be
661      {
662        fmt = SIGNED_DECIMAL;
663        size = INT or LONG; (whichever integral_type_size[4] resolves to)
664        print_function = print_int; (assuming size == INT)
665        fmt_string = "%011d%c";
666       }
667    S_ORIG is solely for reporting errors.  It should be the full format
668    string argument.
669    */
670
671 static int
672 decode_one_format (const char *s_orig, const char *s, const char **next,
673                    struct tspec *tspec)
674 {
675   enum size_spec size_spec;
676   unsigned long int size;
677   enum output_format fmt;
678   const char *pre_fmt_string;
679   char *fmt_string;
680   void (*print_function) ();
681   const char *p;
682   unsigned int c;
683
684   assert (tspec != NULL);
685
686   switch (*s)
687     {
688     case 'd':
689     case 'o':
690     case 'u':
691     case 'x':
692       c = *s;
693       ++s;
694       switch (*s)
695         {
696         case 'C':
697           ++s;
698           size = sizeof (char);
699           break;
700
701         case 'S':
702           ++s;
703           size = sizeof (short);
704           break;
705
706         case 'I':
707           ++s;
708           size = sizeof (int);
709           break;
710
711         case 'L':
712           ++s;
713           size = sizeof (long int);
714           break;
715
716         default:
717           if (simple_strtoul (s, &p, &size) != 0)
718             {
719               /* The integer at P in S would overflow an unsigned long.
720                  A digit string that long is sufficiently odd looking
721                  that the following diagnostic is sufficient.  */
722               error (0, 0, _("invalid type string `%s'"), s_orig);
723               return 1;
724             }
725           if (p == s)
726             size = sizeof (int);
727           else
728             {
729               if (size > MAX_INTEGRAL_TYPE_SIZE
730                   || integral_type_size[size] == NO_SIZE)
731                 {
732                   error (0, 0, _("invalid type string `%s';\n\
733 this system doesn't provide a %lu-byte integral type"), s_orig, size);
734                   return 1;
735                 }
736               s = p;
737             }
738           break;
739         }
740
741 #define FMT_BYTES_ALLOCATED 9
742       fmt_string = xmalloc (FMT_BYTES_ALLOCATED);
743
744       size_spec = integral_type_size[size];
745
746       switch (c)
747         {
748         case 'd':
749           fmt = SIGNED_DECIMAL;
750           sprintf (fmt_string, "%%%u%sd%%c",
751                    bytes_to_signed_dec_digits[size],
752                    (size_spec == LONG ? "l" : ""));
753           break;
754
755         case 'o':
756           fmt = OCTAL;
757           sprintf (fmt_string, "%%0%u%so%%c",
758                    bytes_to_oct_digits[size],
759                    (size_spec == LONG ? "l" : ""));
760           break;
761
762         case 'u':
763           fmt = UNSIGNED_DECIMAL;
764           sprintf (fmt_string, "%%%u%su%%c",
765                    bytes_to_unsigned_dec_digits[size],
766                    (size_spec == LONG ? "l" : ""));
767           break;
768
769         case 'x':
770           fmt = HEXADECIMAL;
771           sprintf (fmt_string, "%%0%u%sx%%c",
772                    bytes_to_hex_digits[size],
773                    (size_spec == LONG ? "l" : ""));
774           break;
775
776         default:
777           abort ();
778         }
779
780       assert (strlen (fmt_string) < FMT_BYTES_ALLOCATED);
781
782       switch (size_spec)
783         {
784         case CHAR:
785           print_function = (fmt == SIGNED_DECIMAL
786                             ? print_s_char
787                             : print_char);
788           break;
789
790         case SHORT:
791           print_function = (fmt == SIGNED_DECIMAL
792                             ? print_s_short
793                             : print_short);
794           break;
795
796         case INT:
797           print_function = print_int;
798           break;
799
800         case LONG:
801           print_function = print_long;
802           break;
803
804         default:
805           abort ();
806         }
807       break;
808
809     case 'f':
810       fmt = FLOATING_POINT;
811       ++s;
812       switch (*s)
813         {
814         case 'F':
815           ++s;
816           size = sizeof (float);
817           break;
818
819         case 'D':
820           ++s;
821           size = sizeof (double);
822           break;
823
824         case 'L':
825           ++s;
826           size = sizeof (LONG_DOUBLE);
827           break;
828
829         default:
830           if (simple_strtoul (s, &p, &size) != 0)
831             {
832               /* The integer at P in S would overflow an unsigned long.
833                  A digit string that long is sufficiently odd looking
834                  that the following diagnostic is sufficient.  */
835               error (0, 0, _("invalid type string `%s'"), s_orig);
836               return 1;
837             }
838           if (p == s)
839             size = sizeof (double);
840           else
841             {
842               if (size > MAX_FP_TYPE_SIZE
843                   || fp_type_size[size] == NO_SIZE)
844                 {
845                   error (0, 0, _("invalid type string `%s';\n\
846 this system doesn't provide a %lu-byte floating point type"), s_orig, size);
847                   return 1;
848                 }
849               s = p;
850             }
851           break;
852         }
853       size_spec = fp_type_size[size];
854
855       switch (size_spec)
856         {
857         case FLOAT_SINGLE:
858           print_function = print_float;
859           /* Don't use %#e; not all systems support it.  */
860           pre_fmt_string = "%%%d.%de%%c";
861           fmt_string = xmalloc (strlen (pre_fmt_string));
862           sprintf (fmt_string, pre_fmt_string,
863                    FLT_DIG + 8, FLT_DIG);
864           break;
865
866         case FLOAT_DOUBLE:
867           print_function = print_double;
868           pre_fmt_string = "%%%d.%de%%c";
869           fmt_string = xmalloc (strlen (pre_fmt_string));
870           sprintf (fmt_string, pre_fmt_string,
871                    DBL_DIG + 8, DBL_DIG);
872           break;
873
874 #ifdef HAVE_LONG_DOUBLE
875         case FLOAT_LONG_DOUBLE:
876           print_function = print_long_double;
877           pre_fmt_string = "%%%d.%dLe%%c";
878           fmt_string = xmalloc (strlen (pre_fmt_string));
879           sprintf (fmt_string, pre_fmt_string,
880                    LDBL_DIG + 8, LDBL_DIG);
881           break;
882 #endif
883
884         default:
885           abort ();
886         }
887       break;
888
889     case 'a':
890       ++s;
891       fmt = NAMED_CHARACTER;
892       size_spec = CHAR;
893       fmt_string = NULL;
894       print_function = print_named_ascii;
895       break;
896
897     case 'c':
898       ++s;
899       fmt = CHARACTER;
900       size_spec = CHAR;
901       fmt_string = NULL;
902       print_function = print_ascii;
903       break;
904
905     default:
906       error (0, 0, _("invalid character `%c' in type string `%s'"),
907              *s, s_orig);
908       return 1;
909     }
910
911   tspec->size = size_spec;
912   tspec->fmt = fmt;
913   tspec->print_function = print_function;
914   tspec->fmt_string = fmt_string;
915
916   if (next != NULL)
917     *next = s;
918
919   return 0;
920 }
921
922 /* Decode the POSIX-style od format string S.  Append the decoded
923    representation to the global array SPEC, reallocating SPEC if
924    necessary.  Return zero if S is valid, nonzero otherwise.  */
925
926 static int
927 decode_format_string (const char *s)
928 {
929   const char *s_orig = s;
930   assert (s != NULL);
931
932   while (*s != '\0')
933     {
934       struct tspec tspec;
935       const char *next;
936
937       if (decode_one_format (s_orig, s, &next, &tspec))
938         return 1;
939
940       assert (s != next);
941       s = next;
942
943       if (n_specs >= n_specs_allocated)
944         {
945           n_specs_allocated = 1 + (3 * n_specs_allocated) / 2;
946           spec = (struct tspec *) xrealloc (spec, (n_specs_allocated
947                                                    * sizeof (struct tspec)));
948         }
949
950       memcpy ((char *) &spec[n_specs], (char *) &tspec,
951               sizeof (struct tspec));
952       ++n_specs;
953     }
954
955   return 0;
956 }
957
958 /* Given a list of one or more input filenames FILE_LIST, set the global
959    file pointer IN_STREAM to position N_SKIP in the concatenation of
960    those files.  If any file operation fails or if there are fewer than
961    N_SKIP bytes in the combined input, give an error message and return
962    nonzero.  When possible, use seek- rather than read operations to
963    advance IN_STREAM.  A file name of "-" is interpreted as standard
964    input.  */
965
966 static int
967 skip (off_t n_skip)
968 {
969   int err;
970
971   err = 0;
972   for ( /* empty */ ; *file_list != NULL; ++file_list)
973     {
974       struct stat file_stats;
975       int j;
976
977       if (STREQ (*file_list, "-"))
978         {
979           input_filename = _("standard input");
980           in_stream = stdin;
981           have_read_stdin = 1;
982         }
983       else
984         {
985           input_filename = *file_list;
986           in_stream = fopen (input_filename, "r");
987           if (in_stream == NULL)
988             {
989               error (0, errno, "%s", input_filename);
990               err = 1;
991               continue;
992             }
993         }
994       WINDOWS_SETFILEMODE_BINARY (in_stream, input_filename);
995
996       if (n_skip == 0)
997         break;
998
999       /* First try using fseek.  For large offsets, this extra work is
1000          worthwhile.  If the offset is below some threshold it may be
1001          more efficient to move the pointer by reading.  There are two
1002          issues when trying to use fseek:
1003            - the file must be seekable.
1004            - before seeking to the specified position, make sure
1005              that the new position is in the current file.
1006              Try to do that by getting file's size using fstat().
1007              But that will work only for regular files and dirs.  */
1008
1009       if (fstat (fileno (in_stream), &file_stats))
1010         {
1011           error (0, errno, "%s", input_filename);
1012           err = 1;
1013           continue;
1014         }
1015
1016       /* The st_size field is valid only for regular files and
1017          directories.  FIXME: is the preceding true?
1018          If the number of bytes left to skip is at least as large as
1019          the size of the current file, we can decrement
1020          n_skip and go on to the next file.  */
1021       if (S_ISREG (file_stats.st_mode) || S_ISDIR (file_stats.st_mode))
1022         {
1023           if (n_skip >= file_stats.st_size)
1024             {
1025               n_skip -= file_stats.st_size;
1026               if (in_stream != stdin && fclose (in_stream) == EOF)
1027                 {
1028                   error (0, errno, "%s", input_filename);
1029                   err = 1;
1030                 }
1031               continue;
1032             }
1033           else
1034             {
1035               /* fseek may work on some streams for which lseek doesn't.
1036                  But fseek's offset argument is restricted to the range
1037                  of type `long'.  So if N_SKIP is too large or if fseek
1038                  fails, try lseek.  */
1039               if ((n_skip <= LONG_MAX
1040                    && fseek (in_stream, (long) n_skip, SEEK_SET) == 0)
1041                   || lseek (fileno (in_stream), n_skip, SEEK_SET) >= 0)
1042                 {
1043                   n_skip = 0;
1044                   break;
1045                 }
1046             }
1047         }
1048
1049       /* Seek didn't work or wasn't attempted;  position the file pointer
1050          by reading.  */
1051
1052       for (j = n_skip / BUFSIZ; j >= 0; j--)
1053         {
1054           char buf[BUFSIZ];
1055           size_t n_bytes_to_read = (j > 0
1056                                     ? BUFSIZ
1057                                     : n_skip % BUFSIZ);
1058           size_t n_bytes_read;
1059           n_bytes_read = fread (buf, 1, n_bytes_to_read, in_stream);
1060           n_skip -= n_bytes_read;
1061           if (n_bytes_read != n_bytes_to_read)
1062             break;
1063         }
1064
1065       if (n_skip == 0)
1066         break;
1067     }
1068
1069   if (n_skip != 0)
1070     error (EXIT_FAILURE, 0, _("cannot skip past end of combined input"));
1071
1072   return err;
1073 }
1074
1075 static const char *
1076 format_address_none (long unsigned int address)
1077 {
1078   return "";
1079 }
1080
1081 static const char *
1082 format_address_std (long unsigned int address)
1083 {
1084   const char *address_string;
1085
1086   sprintf (address_fmt_buffer, output_address_fmt_string, address);
1087   address_string = address_fmt_buffer;
1088   return address_string;
1089 }
1090
1091 static const char *
1092 format_address_label (long unsigned int address)
1093 {
1094   const char *address_string;
1095   assert (output_address_fmt_string != NULL);
1096
1097   sprintf (address_fmt_buffer, output_address_fmt_string,
1098            address, address + pseudo_offset);
1099   address_string = address_fmt_buffer;
1100   return address_string;
1101 }
1102
1103 /* Write N_BYTES bytes from CURR_BLOCK to standard output once for each
1104    of the N_SPEC format specs.  CURRENT_OFFSET is the byte address of
1105    CURR_BLOCK in the concatenation of input files, and it is printed
1106    (optionally) only before the output line associated with the first
1107    format spec.  When duplicate blocks are being abbreviated, the output
1108    for a sequence of identical input blocks is the output for the first
1109    block followed by an asterisk alone on a line.  It is valid to compare
1110    the blocks PREV_BLOCK and CURR_BLOCK only when N_BYTES == BYTES_PER_BLOCK.
1111    That condition may be false only for the last input block -- and then
1112    only when it has not been padded to length BYTES_PER_BLOCK.  */
1113
1114 static void
1115 write_block (long unsigned int current_offset, long unsigned int n_bytes,
1116              const char *prev_block, const char *curr_block)
1117 {
1118   static int first = 1;
1119   static int prev_pair_equal = 0;
1120
1121 #define EQUAL_BLOCKS(b1, b2) (memcmp ((b1), (b2), bytes_per_block) == 0)
1122
1123   if (abbreviate_duplicate_blocks
1124       && !first && n_bytes == bytes_per_block
1125       && EQUAL_BLOCKS (prev_block, curr_block))
1126     {
1127       if (prev_pair_equal)
1128         {
1129           /* The two preceding blocks were equal, and the current
1130              block is the same as the last one, so print nothing.  */
1131         }
1132       else
1133         {
1134           printf ("*\n");
1135           prev_pair_equal = 1;
1136         }
1137     }
1138   else
1139     {
1140       unsigned int i;
1141
1142       prev_pair_equal = 0;
1143       for (i = 0; i < n_specs; i++)
1144         {
1145           printf ("%s ", (i == 0
1146                           ? format_address (current_offset)
1147                           : address_pad));
1148           (*spec[i].print_function) (n_bytes, curr_block, spec[i].fmt_string);
1149         }
1150     }
1151   first = 0;
1152 }
1153
1154 /* Test whether there have been errors on in_stream, and close it if
1155    it is not standard input.  Return nonzero if there has been an error
1156    on in_stream or stdout; return zero otherwise.  This function will
1157    report more than one error only if both a read and a write error
1158    have occurred.  */
1159
1160 static int
1161 check_and_close (void)
1162 {
1163   int err;
1164
1165   err = 0;
1166   if (ferror (in_stream))
1167     {
1168       error (0, errno, "%s", input_filename);
1169       if (in_stream != stdin)
1170         fclose (in_stream);
1171       err = 1;
1172     }
1173   else if (in_stream != stdin && fclose (in_stream) == EOF)
1174     {
1175       error (0, errno, "%s", input_filename);
1176       err = 1;
1177     }
1178
1179   if (ferror (stdout))
1180     {
1181       error (0, errno, _("standard output"));
1182       err = 1;
1183     }
1184
1185   return err;
1186 }
1187
1188 /* Read a single byte into *C from the concatenation of the input files
1189    named in the global array FILE_LIST.  On the first call to this
1190    function, the global variable IN_STREAM is expected to be an open
1191    stream associated with the input file *FILE_LIST.  If IN_STREAM is
1192    at end-of-file, close it and update the global variables IN_STREAM,
1193    FILE_LIST, and INPUT_FILENAME so they correspond to the next file in
1194    the list.  Then try to read a byte from the newly opened file.
1195    Repeat if necessary until *FILE_LIST is NULL.  When EOF is reached
1196    for the last file in FILE_LIST, set *C to EOF and return.  Subsequent
1197    calls do likewise.  The return value is nonzero if any errors
1198    occured, zero otherwise.  */
1199
1200 static int
1201 read_char (int *c)
1202 {
1203   int err;
1204
1205   if (*file_list == NULL)
1206     {
1207       *c = EOF;
1208       return 0;
1209     }
1210
1211   err = 0;
1212   while (1)
1213     {
1214       *c = fgetc (in_stream);
1215
1216       if (*c != EOF)
1217         return err;
1218
1219       err |= check_and_close ();
1220
1221       do
1222         {
1223           ++file_list;
1224           if (*file_list == NULL)
1225             return err;
1226
1227           if (STREQ (*file_list, "-"))
1228             {
1229               input_filename = _("standard input");
1230               in_stream = stdin;
1231               have_read_stdin = 1;
1232             }
1233           else
1234             {
1235               input_filename = *file_list;
1236               in_stream = fopen (input_filename, "r");
1237               if (in_stream == NULL)
1238                 {
1239                   error (0, errno, "%s", input_filename);
1240                   err = 1;
1241                 }
1242             }
1243           WINDOWS_SETFILEMODE_BINARY (in_stream, input_filename);
1244         }
1245       while (in_stream == NULL);
1246     }
1247 }
1248
1249 /* Read N bytes into BLOCK from the concatenation of the input files
1250    named in the global array FILE_LIST.  On the first call to this
1251    function, the global variable IN_STREAM is expected to be an open
1252    stream associated with the input file *FILE_LIST.  On subsequent
1253    calls, if *FILE_LIST is NULL, don't modify BLOCK and return zero.
1254    If all N bytes cannot be read from IN_STREAM, close IN_STREAM and
1255    update the global variables IN_STREAM, FILE_LIST, and INPUT_FILENAME.
1256    Then try to read the remaining bytes from the newly opened file.
1257    Repeat if necessary until *FILE_LIST is NULL.  Set *N_BYTES_IN_BUFFER
1258    to the number of bytes read.  If an error occurs, it will be detected
1259    through ferror when the stream is about to be closed.  If there is an
1260    error, give a message but continue reading as usual and return nonzero.
1261    Otherwise return zero.  */
1262
1263 static int
1264 read_block (size_t n, char *block, size_t *n_bytes_in_buffer)
1265 {
1266   int err;
1267
1268   assert (n > 0 && n <= bytes_per_block);
1269
1270   *n_bytes_in_buffer = 0;
1271
1272   if (n == 0)
1273     return 0;
1274
1275   if (*file_list == NULL)
1276     return 0;                   /* EOF.  */
1277
1278   err = 0;
1279   while (1)
1280     {
1281       size_t n_needed;
1282       size_t n_read;
1283
1284       n_needed = n - *n_bytes_in_buffer;
1285       n_read = fread (block + *n_bytes_in_buffer, 1, n_needed, in_stream);
1286
1287       *n_bytes_in_buffer += n_read;
1288
1289       if (n_read == n_needed)
1290         return err;
1291
1292       err |= check_and_close ();
1293
1294       do
1295         {
1296           ++file_list;
1297           if (*file_list == NULL)
1298             return err;
1299
1300           if (STREQ (*file_list, "-"))
1301             {
1302               input_filename = _("standard input");
1303               in_stream = stdin;
1304               have_read_stdin = 1;
1305             }
1306           else
1307             {
1308               input_filename = *file_list;
1309               in_stream = fopen (input_filename, "r");
1310               if (in_stream == NULL)
1311                 {
1312                   error (0, errno, "%s", input_filename);
1313                   err = 1;
1314                 }
1315             }
1316           WINDOWS_SETFILEMODE_BINARY (in_stream, input_filename);
1317         }
1318       while (in_stream == NULL);
1319     }
1320 }
1321
1322 /* Return the least common multiple of the sizes associated
1323    with the format specs.  */
1324
1325 static int
1326 get_lcm (void)
1327 {
1328   unsigned int i;
1329   int l_c_m = 1;
1330
1331   for (i = 0; i < n_specs; i++)
1332     l_c_m = lcm (l_c_m, width_bytes[(int) spec[i].size]);
1333   return l_c_m;
1334 }
1335
1336 /* If S is a valid pre-POSIX offset specification with an optional leading '+'
1337    return the offset it denotes.  Otherwise, return -1.  */
1338
1339 off_t
1340 parse_old_offset (const char *s)
1341 {
1342   int radix;
1343   off_t offset;
1344   enum strtol_error s_err;
1345   long unsigned int tmp;
1346
1347   if (*s == '\0')
1348     return -1;
1349
1350   /* Skip over any leading '+'. */
1351   if (s[0] == '+')
1352     ++s;
1353
1354   /* Determine the radix we'll use to interpret S.  If there is a `.',
1355      it's decimal, otherwise, if the string begins with `0X'or `0x',
1356      it's hexadecimal, else octal.  */
1357   if (strchr (s, '.') != NULL)
1358     radix = 10;
1359   else
1360     {
1361       if (s[0] == '0' && (s[1] == 'x' || s[1] == 'X'))
1362         radix = 16;
1363       else
1364         radix = 8;
1365     }
1366
1367   s_err = xstrtoul (s, NULL, radix, &tmp, "Bb");
1368   if (s_err != LONGINT_OK)
1369     {
1370       STRTOL_FAIL_WARN (s, _("old-style offset"), s_err);
1371       return -1;
1372     }
1373   offset = tmp;
1374   return offset;
1375 }
1376
1377 /* Read a chunk of size BYTES_PER_BLOCK from the input files, write the
1378    formatted block to standard output, and repeat until the specified
1379    maximum number of bytes has been read or until all input has been
1380    processed.  If the last block read is smaller than BYTES_PER_BLOCK
1381    and its size is not a multiple of the size associated with a format
1382    spec, extend the input block with zero bytes until its length is a
1383    multiple of all format spec sizes.  Write the final block.  Finally,
1384    write on a line by itself the offset of the byte after the last byte
1385    read.  Accumulate return values from calls to read_block and
1386    check_and_close, and if any was nonzero, return nonzero.
1387    Otherwise, return zero.  */
1388
1389 static int
1390 dump (void)
1391 {
1392   char *block[2];
1393   off_t current_offset;
1394   off_t end_offset;
1395   int idx;
1396   int err;
1397   size_t n_bytes_read;
1398
1399 #ifdef lint  /* Suppress `used before initialized' warning.  */
1400   end_offset = 0;
1401 #endif
1402
1403   block[0] = (char *) alloca (bytes_per_block);
1404   block[1] = (char *) alloca (bytes_per_block);
1405
1406   current_offset = n_bytes_to_skip;
1407
1408   idx = 0;
1409   err = 0;
1410   if (limit_bytes_to_format)
1411     {
1412       end_offset = n_bytes_to_skip + max_bytes_to_format;
1413
1414       while (1)
1415         {
1416           size_t n_needed;
1417           if (current_offset >= end_offset)
1418             {
1419               n_bytes_read = 0;
1420               break;
1421             }
1422           n_needed = MIN (end_offset - current_offset,
1423                           (off_t) bytes_per_block);
1424           err |= read_block (n_needed, block[idx], &n_bytes_read);
1425           if (n_bytes_read < bytes_per_block)
1426             break;
1427           assert (n_bytes_read == bytes_per_block);
1428           write_block (current_offset, n_bytes_read,
1429                        block[!idx], block[idx]);
1430           current_offset += n_bytes_read;
1431           idx = !idx;
1432         }
1433     }
1434   else
1435     {
1436       while (1)
1437         {
1438           err |= read_block (bytes_per_block, block[idx], &n_bytes_read);
1439           if (n_bytes_read < bytes_per_block)
1440             break;
1441           assert (n_bytes_read == bytes_per_block);
1442           write_block (current_offset, n_bytes_read,
1443                        block[!idx], block[idx]);
1444           current_offset += n_bytes_read;
1445           idx = !idx;
1446         }
1447     }
1448
1449   if (n_bytes_read > 0)
1450     {
1451       int l_c_m;
1452       size_t bytes_to_write;
1453
1454       l_c_m = get_lcm ();
1455
1456       /* Make bytes_to_write the smallest multiple of l_c_m that
1457          is at least as large as n_bytes_read.  */
1458       bytes_to_write = l_c_m * (int) ((n_bytes_read + l_c_m - 1) / l_c_m);
1459
1460       memset (block[idx] + n_bytes_read, 0, bytes_to_write - n_bytes_read);
1461       write_block (current_offset, bytes_to_write,
1462                    block[!idx], block[idx]);
1463       current_offset += n_bytes_read;
1464     }
1465
1466   if (output_address_fmt_string != NULL)
1467     printf ("%s\n", format_address (current_offset));
1468
1469   if (limit_bytes_to_format && current_offset > end_offset)
1470     err |= check_and_close ();
1471
1472   return err;
1473 }
1474
1475 /* STRINGS mode.  Find each "string constant" in the input.
1476    A string constant is a run of at least `string_min' ASCII
1477    graphic (or formatting) characters terminated by a null.
1478    Based on a function written by Richard Stallman for a
1479    pre-POSIX version of od.  Return nonzero if an error
1480    occurs.  Otherwise, return zero.  */
1481
1482 static int
1483 dump_strings (void)
1484 {
1485   size_t bufsize = MAX (100, string_min);
1486   char *buf = xmalloc (bufsize);
1487   off_t address = n_bytes_to_skip;
1488   int err;
1489
1490   err = 0;
1491   while (1)
1492     {
1493       unsigned int i;
1494       int c;
1495
1496       /* See if the next `string_min' chars are all printing chars.  */
1497     tryline:
1498
1499       if (limit_bytes_to_format
1500           && address >= (n_bytes_to_skip + max_bytes_to_format - string_min))
1501         break;
1502
1503       for (i = 0; i < string_min; i++)
1504         {
1505           err |= read_char (&c);
1506           address++;
1507           if (c < 0)
1508             {
1509               free (buf);
1510               return err;
1511             }
1512           if (!ISPRINT (c))
1513             /* Found a non-printing.  Try again starting with next char.  */
1514             goto tryline;
1515           buf[i] = c;
1516         }
1517
1518       /* We found a run of `string_min' printable characters.
1519          Now see if it is terminated with a null byte.  */
1520       while (!limit_bytes_to_format
1521              || address < n_bytes_to_skip + max_bytes_to_format)
1522         {
1523           if (i == bufsize)
1524             {
1525               bufsize = 1 + 3 * bufsize / 2;
1526               buf = xrealloc (buf, bufsize);
1527             }
1528           err |= read_char (&c);
1529           address++;
1530           if (c < 0)
1531             {
1532               free (buf);
1533               return err;
1534             }
1535           if (c == '\0')
1536             break;              /* It is; print this string.  */
1537           if (!ISPRINT (c))
1538             goto tryline;       /* It isn't; give up on this string.  */
1539           buf[i++] = c;         /* String continues; store it all.  */
1540         }
1541
1542       /* If we get here, the string is all printable and null-terminated,
1543          so print it.  It is all in `buf' and `i' is its length.  */
1544       buf[i] = 0;
1545       if (output_address_fmt_string != NULL)
1546         {
1547           printf ("%s ", format_address (address - i - 1));
1548         }
1549       for (i = 0; (c = buf[i]); i++)
1550         {
1551           switch (c)
1552             {
1553             case '\007':
1554               fputs ("\\a", stdout);
1555               break;
1556
1557             case '\b':
1558               fputs ("\\b", stdout);
1559               break;
1560
1561             case '\f':
1562               fputs ("\\f", stdout);
1563               break;
1564
1565             case '\n':
1566               fputs ("\\n", stdout);
1567               break;
1568
1569             case '\r':
1570               fputs ("\\r", stdout);
1571               break;
1572
1573             case '\t':
1574               fputs ("\\t", stdout);
1575               break;
1576
1577             case '\v':
1578               fputs ("\\v", stdout);
1579               break;
1580
1581             default:
1582               putc (c, stdout);
1583             }
1584         }
1585       putchar ('\n');
1586     }
1587
1588   /* We reach this point only if we search through
1589      (max_bytes_to_format - string_min) bytes before reachine EOF.  */
1590
1591   free (buf);
1592
1593   err |= check_and_close ();
1594   return err;
1595 }
1596
1597 int
1598 main (int argc, char **argv)
1599 {
1600   int c;
1601   int n_files;
1602   unsigned int i;
1603   unsigned int l_c_m;
1604   unsigned int address_pad_len;
1605   unsigned long int desired_width;
1606   int width_specified = 0;
1607   int n_failed_decodes = 0;
1608   int err;
1609
1610   /* The old-style `pseudo starting address' to be printed in parentheses
1611      after any true address.  */
1612   long int pseudo_start;
1613
1614 #ifdef lint  /* Suppress `used before initialized' warning.  */
1615   pseudo_start = 0;
1616 #endif
1617
1618   program_name = argv[0];
1619   setlocale (LC_ALL, "");
1620   bindtextdomain (PACKAGE, LOCALEDIR);
1621   textdomain (PACKAGE);
1622
1623   err = 0;
1624
1625   for (i = 0; i <= MAX_INTEGRAL_TYPE_SIZE; i++)
1626     integral_type_size[i] = NO_SIZE;
1627
1628   integral_type_size[sizeof (char)] = CHAR;
1629   integral_type_size[sizeof (short int)] = SHORT;
1630   integral_type_size[sizeof (int)] = INT;
1631   integral_type_size[sizeof (long int)] = LONG;
1632
1633   for (i = 0; i <= MAX_FP_TYPE_SIZE; i++)
1634     fp_type_size[i] = NO_SIZE;
1635
1636   fp_type_size[sizeof (float)] = FLOAT_SINGLE;
1637   /* The array entry for `double' is filled in after that for LONG_DOUBLE
1638      so that if `long double' is the same type or if long double isn't
1639      supported FLOAT_LONG_DOUBLE will never be used.  */
1640   fp_type_size[sizeof (LONG_DOUBLE)] = FLOAT_LONG_DOUBLE;
1641   fp_type_size[sizeof (double)] = FLOAT_DOUBLE;
1642
1643   n_specs = 0;
1644   n_specs_allocated = 5;
1645   spec = (struct tspec *) xmalloc (n_specs_allocated * sizeof (struct tspec));
1646
1647   output_address_fmt_string = "%07o";
1648   format_address = format_address_std;
1649   address_pad_len = 7;
1650   flag_dump_strings = 0;
1651
1652   while ((c = getopt_long (argc, argv, "abcdfhilos::xw::A:j:N:t:v",
1653                            long_options, (int *) 0))
1654          != EOF)
1655     {
1656       unsigned long int tmp;
1657       enum strtol_error s_err;
1658
1659       switch (c)
1660         {
1661         case 0:
1662           break;
1663
1664         case 'A':
1665           switch (optarg[0])
1666             {
1667             case 'd':
1668               output_address_fmt_string = "%07d";
1669               format_address = format_address_std;
1670               address_pad_len = 7;
1671               break;
1672             case 'o':
1673               output_address_fmt_string = "%07o";
1674               format_address = format_address_std;
1675               address_pad_len = 7;
1676               break;
1677             case 'x':
1678               output_address_fmt_string = "%06x";
1679               format_address = format_address_std;
1680               address_pad_len = 6;
1681               break;
1682             case 'n':
1683               output_address_fmt_string = NULL;
1684               format_address = format_address_none;
1685               address_pad_len = 0;
1686               break;
1687             default:
1688               error (EXIT_FAILURE, 0,
1689                      _("invalid output address radix `%c'; \
1690 it must be one character from [doxn]"),
1691                      optarg[0]);
1692               break;
1693             }
1694           break;
1695
1696         case 'j':
1697           s_err = xstrtoul (optarg, NULL, 0, &tmp, "bkm");
1698           n_bytes_to_skip = tmp;
1699           if (s_err != LONGINT_OK)
1700             STRTOL_FATAL_ERROR (optarg, _("skip argument"), s_err);
1701           break;
1702
1703         case 'N':
1704           limit_bytes_to_format = 1;
1705
1706           /* FIXME: if off_t is long long and that's an 8-byte type,
1707              use xstrtouq here.  */
1708           s_err = xstrtoul (optarg, NULL, 0, &tmp, "bkm");
1709           max_bytes_to_format = tmp;
1710           if (s_err != LONGINT_OK)
1711             STRTOL_FATAL_ERROR (optarg, _("limit argument"), s_err);
1712
1713           if (tmp > LONG_MAX)
1714             error (EXIT_FAILURE, 0,
1715                    _("specified number of bytes `%s' is larger than \
1716 the maximum\nrepresentable value of type `long'"), optarg);
1717           break;
1718
1719         case 's':
1720           if (optarg == NULL)
1721             string_min = 3;
1722           else
1723             {
1724               s_err = xstrtoul (optarg, NULL, 0, &string_min, "bkm");
1725               if (s_err != LONGINT_OK)
1726                 STRTOL_FATAL_ERROR (optarg, _("minimum string length"), s_err);
1727             }
1728           ++flag_dump_strings;
1729           break;
1730
1731         case 't':
1732           if (decode_format_string (optarg))
1733             ++n_failed_decodes;
1734           break;
1735
1736         case 'v':
1737           abbreviate_duplicate_blocks = 0;
1738           break;
1739
1740         case 'B':
1741           traditional = 1;
1742           break;
1743
1744           /* The next several cases map the old, pre-POSIX format
1745              specification options to the corresponding POSIX format
1746              specs.  GNU od accepts any combination of old- and
1747              new-style options.  Format specification options accumulate.  */
1748
1749 #define CASE_OLD_ARG(old_char,new_string)               \
1750         case old_char:                                  \
1751           {                                             \
1752             if (decode_format_string (new_string))      \
1753               ++n_failed_decodes;                       \
1754           }                                             \
1755           break
1756
1757           CASE_OLD_ARG ('a', "a");
1758           CASE_OLD_ARG ('b', "oC");
1759           CASE_OLD_ARG ('c', "c");
1760           CASE_OLD_ARG ('d', "u2");
1761           CASE_OLD_ARG ('f', "fF");
1762           CASE_OLD_ARG ('h', "x2");
1763           CASE_OLD_ARG ('i', "d2");
1764           CASE_OLD_ARG ('l', "d4");
1765           CASE_OLD_ARG ('o', "o2");
1766           CASE_OLD_ARG ('x', "x2");
1767
1768 #undef CASE_OLD_ARG
1769
1770         case 'w':
1771           width_specified = 1;
1772           if (optarg == NULL)
1773             {
1774               desired_width = 32;
1775             }
1776           else
1777             {
1778               s_err = xstrtoul (optarg, NULL, 10, &desired_width, NULL);
1779               if (s_err != LONGINT_OK)
1780                 STRTOL_FATAL_ERROR (optarg, _("width specification"), s_err);
1781             }
1782           break;
1783
1784         default:
1785           usage (1);
1786           break;
1787         }
1788     }
1789
1790   if (n_failed_decodes > 0)
1791     exit (EXIT_FAILURE);
1792
1793   if (show_version)
1794     {
1795       printf ("od - %s\n", PACKAGE_VERSION);
1796       exit (EXIT_SUCCESS);
1797     }
1798
1799   if (show_help)
1800     usage (0);
1801
1802   if (flag_dump_strings && n_specs > 0)
1803     error (EXIT_FAILURE, 0,
1804            _("no type may be specified when dumping strings"));
1805
1806   n_files = argc - optind;
1807
1808   /* If the --backward-compatible option is used, there may be from
1809      0 to 3 remaining command line arguments;  handle each case
1810      separately.
1811         od [file] [[+]offset[.][b] [[+]label[.][b]]]
1812      The offset and pseudo_start have the same syntax.  */
1813
1814   if (traditional)
1815     {
1816       off_t offset;
1817
1818       if (n_files == 1)
1819         {
1820           if ((offset = parse_old_offset (argv[optind])) >= 0)
1821             {
1822               n_bytes_to_skip = offset;
1823               --n_files;
1824               ++argv;
1825             }
1826         }
1827       else if (n_files == 2)
1828         {
1829           off_t o1, o2;
1830           if ((o1 = parse_old_offset (argv[optind])) >= 0
1831               && (o2 = parse_old_offset (argv[optind + 1])) >= 0)
1832             {
1833               n_bytes_to_skip = o1;
1834               flag_pseudo_start = 1;
1835               pseudo_start = o2;
1836               argv += 2;
1837               n_files -= 2;
1838             }
1839           else if ((o2 = parse_old_offset (argv[optind + 1])) >= 0)
1840             {
1841               n_bytes_to_skip = o2;
1842               --n_files;
1843               argv[optind + 1] = argv[optind];
1844               ++argv;
1845             }
1846           else
1847             {
1848               error (0, 0,
1849                      _("invalid second operand in compatibility mode `%s'"),
1850                      argv[optind + 1]);
1851               usage (1);
1852             }
1853         }
1854       else if (n_files == 3)
1855         {
1856           off_t o1, o2;
1857           if ((o1 = parse_old_offset (argv[optind + 1])) >= 0
1858               && (o2 = parse_old_offset (argv[optind + 2])) >= 0)
1859             {
1860               n_bytes_to_skip = o1;
1861               flag_pseudo_start = 1;
1862               pseudo_start = o2;
1863               argv[optind + 2] = argv[optind];
1864               argv += 2;
1865               n_files -= 2;
1866             }
1867           else
1868             {
1869               error (0, 0,
1870             _("in compatibility mode the last 2 arguments must be offsets"));
1871               usage (1);
1872             }
1873         }
1874       else
1875         {
1876           error (0, 0,
1877            _("in compatibility mode there may be no more than 3 arguments"));
1878           usage (1);
1879         }
1880
1881       if (flag_pseudo_start)
1882         {
1883           static char buf[10];
1884
1885           if (output_address_fmt_string == NULL)
1886             {
1887               output_address_fmt_string = "(%07o)";
1888               format_address = format_address_std;
1889             }
1890           else
1891             {
1892               sprintf (buf, "%s (%s)",
1893                        output_address_fmt_string,
1894                        output_address_fmt_string);
1895               output_address_fmt_string = buf;
1896               format_address = format_address_label;
1897             }
1898         }
1899     }
1900
1901   assert (address_pad_len <= MAX_ADDRESS_LENGTH);
1902   for (i = 0; i < address_pad_len; i++)
1903     address_pad[i] = ' ';
1904   address_pad[address_pad_len] = '\0';
1905
1906   if (n_specs == 0)
1907     {
1908       if (decode_one_format ("o2", "o2", NULL, &(spec[0])))
1909         {
1910           /* This happens on Cray systems that don't have a 2-byte
1911              integral type.  */
1912           exit (EXIT_FAILURE);
1913         }
1914
1915       n_specs = 1;
1916     }
1917
1918   if (n_files > 0)
1919     file_list = (char const *const *) &argv[optind];
1920   else
1921     {
1922       /* If no files were listed on the command line, set up the
1923          global array FILE_LIST so that it contains the null-terminated
1924          list of one name: "-".  */
1925       static char const *const default_file_list[] = {"-", NULL};
1926
1927       file_list = default_file_list;
1928     }
1929
1930   err |= skip (n_bytes_to_skip);
1931   if (in_stream == NULL)
1932     goto cleanup;
1933
1934   pseudo_offset = (flag_pseudo_start ? pseudo_start - n_bytes_to_skip : 0);
1935
1936   /* Compute output block length.  */
1937   l_c_m = get_lcm ();
1938
1939   if (width_specified)
1940     {
1941       if (desired_width != 0 && desired_width % l_c_m == 0)
1942         bytes_per_block = desired_width;
1943       else
1944         {
1945           error (0, 0, _("warning: invalid width %lu; using %d instead"),
1946                  desired_width, l_c_m);
1947           bytes_per_block = l_c_m;
1948         }
1949     }
1950   else
1951     {
1952       if (l_c_m < DEFAULT_BYTES_PER_BLOCK)
1953         bytes_per_block = l_c_m * (int) (DEFAULT_BYTES_PER_BLOCK / l_c_m);
1954       else
1955         bytes_per_block = l_c_m;
1956     }
1957
1958 #ifdef DEBUG
1959   for (i = 0; i < n_specs; i++)
1960     {
1961       printf (_("%d: fmt=\"%s\" width=%d\n"),
1962               i, spec[i].fmt_string, width_bytes[spec[i].size]);
1963     }
1964 #endif
1965
1966   err |= (flag_dump_strings ? dump_strings () : dump ());
1967
1968 cleanup:;
1969
1970   if (have_read_stdin && fclose (stdin) == EOF)
1971     error (EXIT_FAILURE, errno, _("standard input"));
1972
1973   if (fclose (stdout) == EOF)
1974     error (EXIT_FAILURE, errno, _("write error"));
1975
1976   exit (err == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
1977 }