home *** CD-ROM | disk | FTP | other *** search
/ Fresh Fish 9 / FreshFishVol9-CD2.bin / bbs / gnu / textutils-1.11-src.lha / textutils-1.11 / src / od.c < prev    next >
Encoding:
C/C++ Source or Header  |  1994-11-13  |  48.2 KB  |  2,043 lines

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