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