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