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