robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

Justin M. Keyesfix(xxd): signed left-shift overflow in -r mode #40246f350e39b77

master
34.7 KiB1220 linesraw
1/* xxd: my hexdump facility. jw
2 *
3 *  2.10.90 changed to word output
4 *  3.03.93 new indent style, dumb bug inserted and fixed.
5 *          -c option, mls
6 * 26.04.94 better option parser, -ps, -l, -s added.
7 *  1.07.94 -r badly needs - as input file.  Per default autoskip over
8 *             consecutive lines of zeroes, as unix od does.
9 *          -a shows them too.
10 *          -i dump as c-style #include "file.h"
11 *  1.11.95 if "xxd -i" knows the filename, an 'unsigned char filename_bits[]'
12 *          array is written in correct c-syntax.
13 *          -s improved, now defaults to absolute seek, relative requires a '+'.
14 *          -r improved, now -r -s -0x... is supported.
15 *             change/suppress leading '\0' bytes.
16 *          -l n improved: stops exactly after n bytes.
17 *          -r improved, better handling of partial lines with trailing garbage.
18 *          -r improved, now -r -p works again!
19 *          -r improved, less flushing, much faster now! (that was silly)
20 *  3.04.96 Per repeated request of a single person: autoskip defaults to off.
21 * 15.05.96 -v added. They want to know the version.
22 *          -a fixed, to show last line inf file ends in all zeros.
23 *          -u added: Print upper case hex-letters, as preferred by unix bc.
24 *          -h added to usage message. Usage message extended.
25 *          Now using outfile if specified even in normal mode, aehem.
26 *          No longer mixing of ints and longs. May help doze people.
27 *          Added binify ioctl for same reason. (Enough Doze stress for 1996!)
28 * 16.05.96 -p improved, removed occasional superfluous linefeed.
29 * 20.05.96 -l 0 fixed. tried to read anyway.
30 * 21.05.96 -i fixed. now honours -u, and prepends __ to numeric filenames.
31 *          compile -DWIN32 for NT or W95. George V. Reilly, * -v improved :-)
32 *          support --gnuish-longhorn-options
33 * 25.05.96 MAC support added: CodeWarrior already uses ``outline'' in Types.h
34 *          which is included by MacHeaders (Axel Kielhorn). Renamed to
35 *          xxdline().
36 *  7.06.96 -i printed 'int' instead of 'char'. *blush*
37 *          added Bram's OS2 ifdefs...
38 * 18.07.96 gcc -Wall @ SunOS4 is now silent.
39 *          Added osver for MSDOS/DJGPP/WIN32.
40 * 29.08.96 Added size_t to strncmp() for Amiga.
41 * 24.03.97 Windows NT support (Phil Hanna). Clean exit for Amiga WB (Bram)
42 * 02.04.97 Added -E option, to have EBCDIC translation instead of ASCII
43 *          (azc10@yahoo.com)
44 * 22.05.97 added -g (group octets) option (jcook@namerica.kla.com).
45 * 23.09.98 nasty -p -r misfeature fixed: slightly wrong output, when -c was
46 *          missing or wrong.
47 * 26.09.98 Fixed: 'xxd -i infile outfile' did not truncate outfile.
48 * 27.10.98 Fixed: -g option parser required blank.
49 *          option -b added: 01000101 binary output in normal format.
50 * 16.05.00 Added VAXC changes by Stephen P. Wall
51 * 16.05.00 Improved MMS file and merge for VMS by Zoltan Arpadffy
52 * 2011 March  Better error handling by Florian Zumbiehl.
53 * 2011 April  Formatting by Bram Moolenaar
54 * 08.06.2013  Little-endian hexdump (-e) and offset (-o) by Vadim Vygonets.
55 * 11.01.2019  Add full 64/32 bit range to -o and output by Christer Jensen.
56 * 04.02.2020  Add -d for decimal offsets by Aapo Rantalainen
57 * 14.01.2022  Disable extra newlines with -c0 -p by Erik Auerswald.
58 * 20.06.2022  Permit setting the variable names used by -i by David Gow
59 * 31.08.2023  -R never/auto/always prints colored output
60 * 06.10.2023  enable -r -b to reverse bit dumps
61 * 12.01.2024  disable auto-conversion for z/OS (MVS)
62 * 17.01.2024  use size_t instead of usigned int for code-generation (-i), #13876
63 * 25.01.2024  revert the previous patch (size_t instead of unsigned int)
64 * 10.02.2024  fix buffer-overflow when writing color output to buffer, #14003
65 * 10.05.2024  fix another buffer-overflow when writing colored output to buffer, #14738
66 * 10.09.2024  Support -b and -i together, #15661
67 * 19.10.2024  -e did add an extra space #15899
68 * 11.11.2024  improve end-of-options argument parser #9285
69 * 07.12.2024  fix overflow with xxd --autoskip and large sparse files #16175
70 * 15.06.2025  improve color code logic
71 * 08.08.2025  fix overflow with bitwise output
72 * 20.08.2025  remove external library call for autoconversion on z/OS (MVS)
73 * 24.08.2025  avoid NULL dereference with autoskip colorless
74 * 26.11.2025  update indent in exit_with_usage()
75 *
76 * (c) 1990-1998 by Juergen Weigert (jnweiger@gmail.com)
77 *
78 * I hereby grant permission to distribute and use xxd
79 * under X11-MIT or GPL-2.0 (at the user's choice).
80 *
81 * Contributions by Bram Moolenaar et al.
82 */
83
84// Visual Studio 2005 has 'deprecated' many of the standard CRT functions
85#if _MSC_VER >= 1400
86# define _CRT_SECURE_NO_DEPRECATE
87# define _CRT_NONSTDC_NO_DEPRECATE
88#endif
89#if !defined(CYGWIN) && defined(__CYGWIN__)
90# define CYGWIN
91#endif
92
93#if (defined(__linux__) && !defined(__ANDROID__)) || defined(__CYGWIN__)
94# define _XOPEN_SOURCE 700   /* for fdopen() */
95#endif
96
97#include <stdio.h>
98#ifdef VAXC
99# include <file.h>
100#else
101# include <fcntl.h>
102#endif
103#if defined(WIN32) || defined(CYGWIN)
104# include <io.h>        // for setmode()
105#endif
106#ifdef WIN32
107# include <windows.h>
108#endif
109#ifdef UNIX
110# include <unistd.h>
111#endif
112#include <ctype.h>
113#include <limits.h>
114#include <stdlib.h>
115#include <string.h>
116#if __MWERKS__ && !defined(BEBOX)
117# include <unix.h>      // for fdopen() on MAC
118#endif
119
120/*  This corrects the problem of missing prototypes for certain functions
121 *  in some GNU installations (e.g. SunOS 4.1.x).
122 *  Darren Hiebert <darren@hmi.com> (sparc-sun-sunos4.1.3_U1/2.7.2.2)
123 */
124#if defined(__GNUC__) && defined(__STDC__)
125# ifndef __USE_FIXED_PROTOTYPES__
126#  define __USE_FIXED_PROTOTYPES__
127# endif
128#endif
129
130#ifndef __USE_FIXED_PROTOTYPES__
131/*
132 * This is historic and works only if the compiler really has no prototypes:
133 *
134 * Include prototypes for Sun OS 4.x, when using an ANSI compiler.
135 * FILE is defined on OS 4.x, not on 5.x (Solaris).
136 * if __SVR4 is defined (some Solaris versions), don't include this.
137 */
138# if defined(sun) && defined(FILE) && !defined(__SVR4) && defined(__STDC__)
139#  define __P(a) a
140// excerpt from my sun_stdlib.h
141extern int fprintf __P((FILE *, char *, ...));
142extern int fputs   __P((char *, FILE *));
143extern int _flsbuf __P((unsigned char, FILE *));
144extern int _filbuf __P((FILE *));
145extern int fflush  __P((FILE *));
146extern int fclose  __P((FILE *));
147extern int fseek   __P((FILE *, long, int));
148extern int rewind  __P((FILE *));
149
150extern void perror __P((char *));
151# endif
152#endif
153
154char version[] = "xxd 2025-11-26 by Juergen Weigert et al.";
155#ifdef WIN32
156char osver[] = " (Win32)";
157#else
158char osver[] = "";
159#endif
160
161#if defined(WIN32)
162# define BIN_READ(yes)  ((yes) ? "rb" : "rt")
163# define BIN_WRITE(yes) ((yes) ? "wb" : "wt")
164# define BIN_CREAT(yes) ((yes) ? (O_CREAT|O_BINARY) : O_CREAT)
165# define BIN_ASSIGN(fp, yes) setmode(fileno(fp), (yes) ? O_BINARY : O_TEXT)
166# define PATH_SEP '\\'
167#elif defined(CYGWIN)
168# define BIN_READ(yes)  ((yes) ? "rb" : "rt")
169# define BIN_WRITE(yes) ((yes) ? "wb" : "w")
170# define BIN_CREAT(yes) ((yes) ? (O_CREAT|O_BINARY) : O_CREAT)
171# define BIN_ASSIGN(fp, yes) ((yes) ? (void)setmode(fileno(fp), O_BINARY) : (void)(fp))
172# define PATH_SEP '/'
173#else
174# ifdef VMS
175#  define BIN_READ(dummy)  "r"
176#  define BIN_WRITE(dummy) "w"
177#  define BIN_CREAT(dummy) O_CREAT
178#  define BIN_ASSIGN(fp, dummy) fp
179#  define PATH_SEP ']'
180#  define FILE_SEP '.'
181# else
182#  define BIN_READ(dummy)  "r"
183#  define BIN_WRITE(dummy) "w"
184#  define BIN_CREAT(dummy) O_CREAT
185#  define BIN_ASSIGN(fp, dummy) fp
186#  define PATH_SEP '/'
187# endif
188#endif
189
190// open has only to arguments on the Mac
191#if __MWERKS__
192# define OPEN(name, mode, umask) open(name, mode)
193#else
194# define OPEN(name, mode, umask) open(name, mode, umask)
195#endif
196
197#ifdef AMIGA
198# define STRNCMP(s1, s2, l) strncmp(s1, s2, (size_t)l)
199#else
200# define STRNCMP(s1, s2, l) strncmp(s1, s2, l)
201#endif
202
203#ifndef __P
204# if defined(__STDC__) || defined(WIN32)
205#  define __P(a) a
206# else
207#  define __P(a) ()
208# endif
209#endif
210
211#define TRY_SEEK        /* attempt to use lseek, or skip forward by reading */
212#define COLS 256        /* change here, if you ever need more columns */
213
214/*
215 * LLEN is the maximum length of a line; other than the visible characters
216 * we need to consider also the escape color sequence prologue/epilogue ,
217 * (11 bytes for each character).
218 */
219#define LLEN \
220  (39            /* addr: ⌈log10(ULONG_MAX)⌉ if "-d" flag given. We assume ULONG_MAX = 2**128 */ \
221   + 2            /* ": " */ \
222   + 13 * COLS    /* hex dump with colors */ \
223   + (COLS - 1)   /* whitespace between groups if "-g1" option given and "-c" maxed out */ \
224   + 2            /* whitespace */ \
225   + 12 * COLS    /* ASCII dump with colors */ \
226   + 2)           /* "\n\0" */
227
228/*
229 * LLEN_NO_COLOR is the maximum length of a line excluding the colors.
230 */
231#define LLEN_NO_COLOR \
232  (39            /* addr: ⌈log10(ULONG_MAX)⌉ if "-d" flag given. We assume ULONG_MAX = 2**128 */ \
233   + 2            /* ": " */ \
234   + 9 * COLS     /* hex dump, worst case: bitwise output using -b */ \
235   + 2            /* whitespace */ \
236   + COLS         /* ASCII dump */ \
237   + 2)           /* "\n\0" */
238
239char hexxa[] = "0123456789abcdef0123456789ABCDEF", *hexx = hexxa;
240
241// the different hextypes known by this program:
242#define HEX_NORMAL         0x00  /* no flags set */
243#define HEX_POSTSCRIPT     0x01
244#define HEX_CINCLUDE       0x02
245#define HEX_BITS           0x04  /* not hex a dump, but bits: 01111001 */
246#define HEX_LITTLEENDIAN   0x08
247
248#define CONDITIONAL_CAPITALIZE(c) (capitalize ? toupper((unsigned char)(c)) : (c))
249
250#define COLOR_PROLOGUE(color) \
251  l_colored[c++] = '\033'; \
252  l_colored[c++] = '['; \
253  l_colored[c++] = '1'; \
254  l_colored[c++] = ';'; \
255  l_colored[c++] = '3'; \
256  l_colored[c++] = (color); \
257  l_colored[c++] = 'm';
258
259#define COLOR_EPILOGUE \
260  l_colored[c++] = '\033'; \
261  l_colored[c++] = '['; \
262  l_colored[c++] = '0'; \
263  l_colored[c++] = 'm';
264#define COLOR_RED '1'
265#define COLOR_GREEN '2'
266#define COLOR_YELLOW '3'
267#define COLOR_BLUE '4'
268#define COLOR_WHITE '7'
269
270static char *pname;
271
272static void exit_with_usage(void)
273{
274  fprintf(stderr, "Usage:\n       %s [options] [infile [outfile]]\n", pname);
275  fprintf(stderr, "    or\n       %s -r [-s [-]offset] [-c cols] [-ps] [infile [outfile]]\n",
276          pname);
277  fprintf(stderr, "Options:\n"
278          "    -a          toggle autoskip: A single '*' replaces nul-lines. Default off.\n"
279          "    -b          binary digit dump (incompatible with -ps). Default hex.\n"
280          "    -C          capitalize variable names in C include file style (-i).\n"
281          "    -c cols     format <cols> octets per line. Default 16 (-i: 12, -ps: 30).\n"
282          "    -E          show characters in EBCDIC. Default ASCII.\n"
283          "    -e          little-endian dump (incompatible with -ps,-i,-r).\n"
284          "    -g bytes    number of octets per group in normal output. Default 2 (-e: 4).\n"
285          "    -h          print this summary.\n"
286          "    -i          output in C include file style.\n"
287          "    -l len      stop after <len> octets.\n"
288          "    -n name     set the variable name used in C include output (-i).\n"
289          "    -o off      add <off> to the displayed file position.\n"
290          "    -ps         output in postscript plain hexdump style.\n"
291          "    -r          reverse operation: convert (or patch) hexdump into binary.\n"
292          "    -r -s off   revert with <off> added to file positions found in hexdump.\n"
293          "    -d          show offset in decimal instead of hex.\n");
294  fprintf(stderr, "    -s %sseek  start at <seek> bytes abs. %sinfile offset.\n",
295#ifdef TRY_SEEK
296          "[+][-]", "(or +: rel.) ");
297#else
298          "", "");
299#endif
300  fprintf(stderr, "    -u          use upper case hex letters.\n"
301          "    -R when     colorize the output; <when> can be 'always', 'auto' or 'never'. Default: 'auto'.\n"
302          "    -v          show version: \"%s%s\".\n", version, osver);
303  exit(1);
304}
305
306static void perror_exit(int ret)
307{
308  fprintf(stderr, "%s: ", pname);
309  perror(NULL);
310  exit(ret);
311}
312
313static void error_exit(int ret, char *msg)
314{
315  fprintf(stderr, "%s: %s\n", pname, msg);
316  exit(ret);
317}
318
319static int getc_or_die(FILE *fpi)
320{
321  int c = getc(fpi);
322  if (c == EOF && ferror(fpi)) {
323    perror_exit(2);
324  }
325  return c;
326}
327
328static void putc_or_die(int c, FILE *fpo)
329{
330  if (putc(c, fpo) == EOF) {
331    perror_exit(3);
332  }
333}
334
335static void fputs_or_die(char *s, FILE *fpo)
336{
337  if (fputs(s, fpo) == EOF) {
338    perror_exit(3);
339  }
340}
341
342// Use a macro to allow for different arguments.
343#define FPRINTF_OR_DIE(args) if (fprintf args < 0) perror_exit(3)
344
345static void fclose_or_die(FILE *fpi, FILE *fpo)
346{
347  if (fclose(fpo) != 0) {
348    perror_exit(3);
349  }
350  if (fclose(fpi) != 0) {
351    perror_exit(2);
352  }
353}
354
355/*
356 * If "c" is a hex digit, return the value.
357 * Otherwise return -1.
358 */
359static int parse_hex_digit(int c)
360{
361  return (c >= '0' && c <= '9') ? c - '0'
362                                : (c >= 'a' && c <= 'f') ? c - 'a' + 10
363                                                         : (c >= 'A' && c <= 'F') ? c - 'A' + 10
364                                                                                  : -1;
365}
366
367/*
368 * If "c" is a bin digit, return the value.
369 * Otherwise return -1.
370 */
371static int parse_bin_digit(int c)
372{
373  return (c >= '0' && c <= '1') ? c - '0'
374                                : -1;
375}
376
377/*
378 * Ignore text on "fpi" until end-of-line or end-of-file.
379 * Return the '\n' or EOF character.
380 * When an error is encountered exit with an error message.
381 */
382static int skip_to_eol(FILE *fpi, int c)
383{
384  while (c != '\n' && c != EOF) {
385    c = getc_or_die(fpi);
386  }
387  return c;
388}
389
390/*
391 * Max. cols binary characters are decoded from the input stream per line.
392 * Two adjacent garbage characters after evaluated data delimit valid data.
393 * Everything up to the next newline is discarded.
394 *
395 * The name is historic and came from 'undo type opt h'.
396 */
397static int huntype(FILE *fpi, FILE *fpo, int cols, int hextype, long base_off)
398{
399  int c, ign_garb = 1, n1 = -1, n2 = 0, n3 = 0, p = cols, bt = 0, b = 0, bcnt = 0;
400  long have_off = 0, want_off = 0;
401
402  rewind(fpi);
403
404  while ((c = getc(fpi)) != EOF) {
405    if (c == '\r') {  // Doze style input file?
406      continue;
407    }
408
409    /* Allow multiple spaces.  This doesn't work when there is normal text
410     * after the hex codes in the last line that looks like hex, thus only
411     * use it for PostScript format. */
412    if (hextype == HEX_POSTSCRIPT && (c == ' ' || c == '\n' || c == '\t')) {
413      continue;
414    }
415
416    if (hextype == HEX_NORMAL || hextype == HEX_POSTSCRIPT) {
417      n3 = n2;
418      n2 = n1;
419
420      n1 = parse_hex_digit(c);
421      if (n1 == -1 && ign_garb) {
422        continue;
423      }
424    } else {  // HEX_BITS
425      n1 = parse_hex_digit(c);
426      if (n1 == -1 && ign_garb) {
427        continue;
428      }
429
430      bt = parse_bin_digit(c);
431      if (bt != -1) {
432        b = ((b << 1) | bt);
433        ++bcnt;
434      }
435    }
436
437    ign_garb = 0;
438
439    if ((hextype != HEX_POSTSCRIPT) && (p >= cols)) {
440      if (hextype == HEX_NORMAL) {
441        if (n1 < 0) {
442          p = 0;
443          continue;
444        }
445        // Cast through unsigned to avoid signed left-shift overflow (UB) when
446        // garbage input feeds more than ~16 hex digits into the address column.
447        want_off = (long)(((unsigned long)want_off << 4) | (unsigned)n1);
448      } else {  // HEX_BITS
449        if (n1 < 0) {
450          p = 0;
451          bcnt = 0;
452          continue;
453        }
454        want_off = (long)(((unsigned long)want_off << 4) | (unsigned)n1);
455      }
456      continue;
457    }
458
459    if (base_off + want_off != have_off) {
460      if (fflush(fpo) != 0) {
461        perror_exit(3);
462      }
463#ifdef TRY_SEEK
464      if (fseek(fpo, base_off + want_off - have_off, SEEK_CUR) >= 0) {
465        have_off = base_off + want_off;
466      }
467#endif
468      if (base_off + want_off < have_off) {
469        error_exit(5, "Cannot seek backwards.");
470      }
471      for (; have_off < base_off + want_off; have_off++) {
472        putc_or_die(0, fpo);
473      }
474    }
475
476    if (hextype == HEX_NORMAL || hextype == HEX_POSTSCRIPT) {
477      if (n2 >= 0 && n1 >= 0) {
478        putc_or_die((n2 << 4) | n1, fpo);
479        have_off++;
480        want_off++;
481        n1 = -1;
482        if (!hextype && (++p >= cols)) {
483          // skip the rest of the line as garbage
484          c = skip_to_eol(fpi, c);
485        }
486      } else if (n1 < 0 && n2 < 0 && n3 < 0) {
487        // already stumbled into garbage, skip line, wait and see
488        c = skip_to_eol(fpi, c);
489      }
490    } else {  // HEX_BITS
491      if (bcnt == 8) {
492        putc_or_die(b, fpo);
493        have_off++;
494        want_off++;
495        b = 0;
496        bcnt = 0;
497        if (++p >= cols) {
498          // skip the rest of the line as garbage
499          c = skip_to_eol(fpi, c);
500        }
501      }
502    }
503
504    if (c == '\n') {
505      if (hextype == HEX_NORMAL || hextype == HEX_BITS) {
506        want_off = 0;
507      }
508      p = cols;
509      ign_garb = 1;
510    }
511  }
512  if (fflush(fpo) != 0) {
513    perror_exit(3);
514  }
515#ifdef TRY_SEEK
516  fseek(fpo, 0L, SEEK_END);
517#endif
518  fclose_or_die(fpi, fpo);
519  return 0;
520}
521
522/*
523 * Print line l with given colors.
524 */
525static void print_colored_line(FILE *fp, char *l, char *colors)
526{
527  static char l_colored[LLEN + 1];
528
529  if (colors) {
530    int c = 0;
531    if (colors[0]) {
532      COLOR_PROLOGUE(colors[0])
533    }
534    l_colored[c++] = l[0];
535    int i;
536    for (i = 1; l[i]; i++) {
537      if (colors[i] != colors[i - 1]) {
538        if (colors[i - 1]) {
539          COLOR_EPILOGUE
540        }
541        if (colors[i]) {
542          COLOR_PROLOGUE(colors[i])
543        }
544      }
545      l_colored[c++] = l[i];
546    }
547
548    if (colors[i]) {
549      COLOR_EPILOGUE
550    }
551    l_colored[c++] = '\0';
552
553    fputs_or_die(l_colored, fp);
554  } else {
555    fputs_or_die(l, fp);
556  }
557}
558
559/*
560 * Print line l with given colors. If nz is false, xxdline regards the line as a line of
561 * zeroes. If there are three or more consecutive lines of zeroes,
562 * they are replaced by a single '*' character.
563 *
564 * If the output ends with more than two lines of zeroes, you
565 * should call xxdline again with l being the last line and nz
566 * negative. This ensures that the last line is shown even when
567 * it is all zeroes.
568 *
569 * If nz is always positive, lines are never suppressed.
570 */
571static void xxdline(FILE *fp, char *l, char *colors, int nz)
572{
573  static char z[LLEN_NO_COLOR + 1];
574  static char z_colors[LLEN_NO_COLOR + 1];
575  static signed char zero_seen = 0;
576
577  if (!nz && zero_seen == 1) {
578    snprintf(z, sizeof(z), "%s", l);
579    if (colors) {
580      memcpy(z_colors, colors, strlen(z));
581    }
582  }
583
584  if (nz || !zero_seen++) {
585    if (nz) {
586      if (nz < 0) {
587        zero_seen--;
588      }
589      if (zero_seen == 2) {
590        print_colored_line(fp, z, z_colors);
591      }
592      if (zero_seen > 2) {
593        fputs_or_die("*\n", fp);
594      }
595    }
596    if (nz >= 0 || zero_seen > 0) {
597      print_colored_line(fp, l, colors);
598    }
599
600    if (nz) {
601      zero_seen = 0;
602    }
603  }
604
605  /* If zero_seen > 3, then its exact value doesn't matter, so long as it
606   * remains >3 and incrementing it will not cause overflow. */
607  if (zero_seen >= 0x7F) {
608    zero_seen = 4;
609  }
610}
611
612// This is an EBCDIC to ASCII conversion table
613// from a proposed BTL standard April 16, 1979
614static unsigned char etoa64[] = {
615  0040, 0240, 0241, 0242, 0243, 0244, 0245, 0246,
616  0247, 0250, 0325, 0056, 0074, 0050, 0053, 0174,
617  0046, 0251, 0252, 0253, 0254, 0255, 0256, 0257,
618  0260, 0261, 0041, 0044, 0052, 0051, 0073, 0176,
619  0055, 0057, 0262, 0263, 0264, 0265, 0266, 0267,
620  0270, 0271, 0313, 0054, 0045, 0137, 0076, 0077,
621  0272, 0273, 0274, 0275, 0276, 0277, 0300, 0301,
622  0302, 0140, 0072, 0043, 0100, 0047, 0075, 0042,
623  0303, 0141, 0142, 0143, 0144, 0145, 0146, 0147,
624  0150, 0151, 0304, 0305, 0306, 0307, 0310, 0311,
625  0312, 0152, 0153, 0154, 0155, 0156, 0157, 0160,
626  0161, 0162, 0136, 0314, 0315, 0316, 0317, 0320,
627  0321, 0345, 0163, 0164, 0165, 0166, 0167, 0170,
628  0171, 0172, 0322, 0323, 0324, 0133, 0326, 0327,
629  0330, 0331, 0332, 0333, 0334, 0335, 0336, 0337,
630  0340, 0341, 0342, 0343, 0344, 0135, 0346, 0347,
631  0173, 0101, 0102, 0103, 0104, 0105, 0106, 0107,
632  0110, 0111, 0350, 0351, 0352, 0353, 0354, 0355,
633  0175, 0112, 0113, 0114, 0115, 0116, 0117, 0120,
634  0121, 0122, 0356, 0357, 0360, 0361, 0362, 0363,
635  0134, 0237, 0123, 0124, 0125, 0126, 0127, 0130,
636  0131, 0132, 0364, 0365, 0366, 0367, 0370, 0371,
637  0060, 0061, 0062, 0063, 0064, 0065, 0066, 0067,
638  0070, 0071, 0372, 0373, 0374, 0375, 0376, 0377
639};
640
641static char get_color_char(int e, int ebcdic)
642{
643  if (ebcdic) {
644    if ((e >= 75 && e <= 80) || (e >= 90 && e <= 97)
645        || (e >= 107 && e <= 111) || (e >= 121 && e <= 127)
646        || (e >= 129 && e <= 137) || (e >= 145 && e <= 154)
647        || (e >= 162 && e <= 169) || (e >= 192 && e <= 201)
648        || (e >= 208 && e <= 217) || (e >= 226 && e <= 233)
649        || (e >= 240 && e <= 249) || (e == 189) || (e == 64)
650        || (e == 173) || (e == 224)) {
651      return COLOR_GREEN;
652    } else if (e == 37 || e == 13 || e == 5) {
653      return COLOR_YELLOW;
654    } else if (e == 0) {
655      return COLOR_WHITE;
656    } else if (e == 255) {
657      return COLOR_BLUE;
658    } else {
659      return COLOR_RED;
660    }
661  } else {  // ASCII
662#if defined(__MVS__) && __CHARSET_LIB == 0
663    if (e >= 64) {
664      return COLOR_GREEN;
665    }
666#else
667    if (e > 31 && e < 127) {
668      return COLOR_GREEN;
669    }
670#endif
671
672    else if (e == 9 || e == 10 || e == 13) {
673      return COLOR_YELLOW;
674    } else if (e == 0) {
675      return COLOR_WHITE;
676    } else if (e == 255) {
677      return COLOR_BLUE;
678    } else {
679      return COLOR_RED;
680    }
681  }
682  return 0;
683}
684
685static int enable_color(void)
686{
687#ifdef WIN32
688  DWORD mode;
689  HANDLE out;
690
691  if (!isatty(1)) {
692    return 0;
693  }
694
695  out = GetStdHandle(STD_OUTPUT_HANDLE);
696  GetConsoleMode(out, &mode);
697  mode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
698  return (int)SetConsoleMode(out, mode);
699#elif defined(UNIX)
700  return isatty(STDOUT_FILENO);
701#else
702  return 0;
703#endif
704}
705
706int main(int argc, char *argv[])
707{
708  FILE *fp, *fpo;
709  int c, e, p = 0, relseek = 1, negseek = 0, revert = 0, i, x;
710  int cols = 0, colsgiven = 0, nonzero = 0, autoskip = 0, hextype = HEX_NORMAL;
711  int capitalize = 0, decimal_offset = 0;
712  int ebcdic = 0;
713  int octspergrp = -1;  // number of octets grouped in output
714  int grplen;           // total chars per octet group excluding colors
715  long length = -1, n = 0, seekoff = 0;
716  unsigned long displayoff = 0;
717  static char l[LLEN_NO_COLOR + 1];  // static because it may be too big for stack
718  static char colors[LLEN_NO_COLOR + 1];  // color array
719  char *pp;
720  char *varname = NULL;
721  int addrlen = 9;
722  int color = 0;
723  char *no_color;
724  char cur_color = 0;
725
726  no_color = getenv("NO_COLOR");
727  if (no_color == NULL || no_color[0] == '\0') {
728    color = enable_color();
729  }
730
731#ifdef AMIGA
732  // This program doesn't work when started from the Workbench
733  if (argc == 0) {
734    exit(1);
735  }
736#endif
737
738  pname = argv[0];
739  for (pp = pname; *pp;) {
740    if (*pp++ == PATH_SEP) {
741      pname = pp;
742    }
743  }
744#ifdef FILE_SEP
745  for (pp = pname; *pp; pp++) {
746    if (*pp == FILE_SEP) {
747      *pp = '\0';
748      break;
749    }
750  }
751#endif
752
753  while (argc >= 2) {
754    pp = argv[1] + (!STRNCMP(argv[1], "--", 2) && argv[1][2]);
755    if (!STRNCMP(pp, "-a", 2)) {
756      autoskip = 1 - autoskip;
757    } else if (!STRNCMP(pp, "-b", 2)) {
758      hextype |= HEX_BITS;
759    } else if (!STRNCMP(pp, "-e", 2)) {
760      hextype |= HEX_LITTLEENDIAN;
761    } else if (!STRNCMP(pp, "-u", 2)) {
762      hexx = hexxa + 16;
763    } else if (!STRNCMP(pp, "-p", 2)) {
764      hextype |= HEX_POSTSCRIPT;
765    } else if (!STRNCMP(pp, "-i", 2)) {
766      hextype |= HEX_CINCLUDE;
767    } else if (!STRNCMP(pp, "-C", 2)) {
768      capitalize = 1;
769    } else if (!STRNCMP(pp, "-d", 2)) {
770      decimal_offset = 1;
771    } else if (!STRNCMP(pp, "-r", 2)) {
772      revert++;
773    } else if (!STRNCMP(pp, "-E", 2)) {
774      ebcdic++;
775    } else if (!STRNCMP(pp, "-v", 2)) {
776      fprintf(stderr, "%s%s\n", version, osver);
777      exit(0);
778    } else if (!STRNCMP(pp, "-c", 2)) {
779      if (pp[2] && !STRNCMP("apitalize", pp + 2, 9)) {
780        capitalize = 1;
781      } else if (pp[2] && STRNCMP("ols", pp + 2, 3)) {
782        colsgiven = 1;
783        cols = (int)strtol(pp + 2, NULL, 0);
784      } else {
785        if (!argv[2]) {
786          exit_with_usage();
787        }
788        colsgiven = 1;
789        cols = (int)strtol(argv[2], NULL, 0);
790        argv++;
791        argc--;
792      }
793    } else if (!STRNCMP(pp, "-g", 2)) {
794      if (pp[2] && STRNCMP("roup", pp + 2, 4)) {
795        octspergrp = (int)strtol(pp + 2, NULL, 0);
796      } else {
797        if (!argv[2]) {
798          exit_with_usage();
799        }
800        octspergrp = (int)strtol(argv[2], NULL, 0);
801        argv++;
802        argc--;
803      }
804    } else if (!STRNCMP(pp, "-o", 2)) {
805      int reloffset = 0;
806      int negoffset = 0;
807      if (pp[2] && STRNCMP("ffset", pp + 2, 5)) {
808        displayoff = strtoul(pp + 2, NULL, 0);
809      } else {
810        if (!argv[2]) {
811          exit_with_usage();
812        }
813
814        if (argv[2][0] == '+') {
815          reloffset++;
816        }
817        if (argv[2][reloffset] == '-') {
818          negoffset++;
819        }
820
821        if (negoffset) {
822          displayoff = ULONG_MAX - strtoul(argv[2] + reloffset + negoffset, NULL, 0) + 1;
823        } else {
824          displayoff = strtoul(argv[2] + reloffset + negoffset, NULL, 0);
825        }
826
827        argv++;
828        argc--;
829      }
830    } else if (!STRNCMP(pp, "-s", 2)) {
831      relseek = 0;
832      negseek = 0;
833      if (pp[2] && STRNCMP("kip", pp + 2, 3) && STRNCMP("eek", pp + 2, 3)) {
834#ifdef TRY_SEEK
835        if (pp[2] == '+') {
836          relseek++;
837        }
838        if (pp[2 + relseek] == '-') {
839          negseek++;
840        }
841#endif
842        seekoff = strtol(pp + 2 + relseek + negseek, (char **)NULL, 0);
843      } else {
844        if (!argv[2]) {
845          exit_with_usage();
846        }
847#ifdef TRY_SEEK
848        if (argv[2][0] == '+') {
849          relseek++;
850        }
851        if (argv[2][relseek] == '-') {
852          negseek++;
853        }
854#endif
855        seekoff = strtol(argv[2] + relseek + negseek, (char **)NULL, 0);
856        argv++;
857        argc--;
858      }
859    } else if (!STRNCMP(pp, "-l", 2)) {
860      if (pp[2] && STRNCMP("en", pp + 2, 2)) {
861        length = strtol(pp + 2, (char **)NULL, 0);
862      } else {
863        if (!argv[2]) {
864          exit_with_usage();
865        }
866        length = strtol(argv[2], (char **)NULL, 0);
867        argv++;
868        argc--;
869      }
870    } else if (!STRNCMP(pp, "-n", 2)) {
871      if (pp[2] && STRNCMP("ame", pp + 2, 3)) {
872        varname = pp + 2;
873      } else {
874        if (!argv[2]) {
875          exit_with_usage();
876        }
877        varname = argv[2];
878        argv++;
879        argc--;
880      }
881    } else if (!STRNCMP(pp, "-R", 2)) {
882      char *pw = pp + 2;
883      if (!pw[0]) {
884        pw = argv[2];
885        argv++;
886        argc--;
887      }
888      if (!pw) {
889        exit_with_usage();
890      }
891      if (!STRNCMP(pw, "always", 6)) {
892        (void)enable_color();
893        color = 1;
894      } else if (!STRNCMP(pw, "never", 5)) {
895        color = 0;
896      } else if (!STRNCMP(pw, "auto", 4)) {
897        color = enable_color();
898      } else {
899        exit_with_usage();
900      }
901    } else if (!strcmp(argv[1], "--")) {  // end of options
902      argv++;
903      argc--;
904      break;
905    } else if (pp[0] == '-' && pp[1]) {  // unknown option
906      exit_with_usage();
907    } else {
908      break;                          // not an option
909    }
910    argv++;                           // advance to next argument
911    argc--;
912  }
913
914  if (hextype != (HEX_CINCLUDE | HEX_BITS)) {
915    // Allow at most one bit to be set in hextype
916    if (hextype & (hextype - 1)) {
917      error_exit(1, "only one of -b, -e, -u, -p, -i can be used");
918    }
919  }
920
921  if (!colsgiven || (!cols && hextype != HEX_POSTSCRIPT)) {
922    switch (hextype) {
923    case HEX_POSTSCRIPT:
924      cols = 30; break;
925    case HEX_CINCLUDE:
926      cols = 12; break;
927    case HEX_CINCLUDE | HEX_BITS:
928    case HEX_BITS:
929      cols = 6; break;
930    case HEX_NORMAL:
931    case HEX_LITTLEENDIAN:
932    default:
933      cols = 16; break;
934    }
935  }
936
937  if (octspergrp < 0) {
938    switch (hextype) {
939    case HEX_CINCLUDE | HEX_BITS:
940    case HEX_BITS:
941      octspergrp = 1; break;
942    case HEX_NORMAL:
943      octspergrp = 2; break;
944    case HEX_LITTLEENDIAN:
945      octspergrp = 4; break;
946    case HEX_POSTSCRIPT:
947    case HEX_CINCLUDE:
948    default:
949      octspergrp = 0; break;
950    }
951  }
952
953  if ((hextype == HEX_POSTSCRIPT && cols < 0)
954      || (hextype != HEX_POSTSCRIPT && cols < 1)
955      || ((hextype == HEX_NORMAL || hextype == HEX_BITS || hextype == HEX_LITTLEENDIAN)
956          && (cols > COLS))) {
957    fprintf(stderr, "%s: invalid number of columns (max. %d).\n", pname, COLS);
958    exit(1);
959  }
960
961  if (octspergrp < 1 || octspergrp > cols) {
962    octspergrp = cols;
963  } else if (hextype == HEX_LITTLEENDIAN && (octspergrp & (octspergrp - 1))) {
964    error_exit(1, "number of octets per group must be a power of 2 with -e.");
965  }
966
967  if (argc > 3) {
968    exit_with_usage();
969  }
970
971  if (argc == 1 || (argv[1][0] == '-' && !argv[1][1])) {
972    BIN_ASSIGN(fp = stdin, !revert);
973  } else {
974    if ((fp = fopen(argv[1], BIN_READ(!revert))) == NULL) {
975      fprintf(stderr, "%s: ", pname);
976      perror(argv[1]);
977      return 2;
978    }
979  }
980
981  if (argc < 3 || (argv[2][0] == '-' && !argv[2][1])) {
982    BIN_ASSIGN(fpo = stdout, revert);
983  } else {
984    int fd;
985    int mode = revert ? O_WRONLY : (O_TRUNC|O_WRONLY);
986
987    if (((fd = OPEN(argv[2], mode | BIN_CREAT(revert), 0666)) < 0)
988        || (fpo = fdopen(fd, BIN_WRITE(revert))) == NULL) {
989      fprintf(stderr, "%s: ", pname);
990      perror(argv[2]);
991      return 3;
992    }
993    rewind(fpo);
994  }
995
996  if (revert) {
997    switch (hextype) {
998    case HEX_NORMAL:
999    case HEX_POSTSCRIPT:
1000    case HEX_BITS:
1001      return huntype(fp, fpo, cols, hextype,
1002                     negseek ? -seekoff : seekoff);
1003      break;
1004    default:
1005      error_exit(-1, "Cannot revert this type of hexdump");
1006    }
1007  }
1008
1009  if (seekoff || negseek || !relseek) {
1010#ifdef TRY_SEEK
1011    if (relseek) {
1012      e = fseek(fp, negseek ? -seekoff : seekoff, SEEK_CUR);
1013    } else {
1014      e = fseek(fp, negseek ? -seekoff : seekoff,
1015                negseek ? SEEK_END : SEEK_SET);
1016    }
1017    if (e < 0 && negseek) {
1018      error_exit(4, "Cannot seek.");
1019    }
1020    if (e >= 0) {
1021      seekoff = ftell(fp);
1022    } else
1023#endif
1024    {
1025      long s = seekoff;
1026
1027      while (s--) {
1028        if (getc_or_die(fp) == EOF) {
1029          error_exit(4, "Cannot seek.");
1030        }
1031      }
1032    }
1033  }
1034
1035  if (hextype & HEX_CINCLUDE) {
1036    // A user-set variable name overrides fp == stdin
1037    if (varname == NULL && fp != stdin) {
1038      varname = argv[1];
1039    }
1040
1041    if (varname != NULL) {
1042      FPRINTF_OR_DIE((fpo, "unsigned char %s", isdigit((unsigned char)varname[0]) ? "__" : ""));
1043      for (e = 0; (c = varname[e]) != 0; e++) {
1044        putc_or_die(isalnum((unsigned char)c) ? CONDITIONAL_CAPITALIZE(c) : '_', fpo);
1045      }
1046      fputs_or_die("[] = {\n", fpo);
1047    }
1048
1049    p = 0;
1050    while ((length < 0 || p < length) && (c = getc_or_die(fp)) != EOF) {
1051      if (hextype & HEX_BITS) {
1052        if (p == 0) {
1053          fputs_or_die("  ", fpo);
1054        } else if (p % cols == 0) {
1055          fputs_or_die(",\n  ", fpo);
1056        } else {
1057          fputs_or_die(", ", fpo);
1058        }
1059
1060        FPRINTF_OR_DIE((fpo, "0b"));
1061        for (int j = 7; j >= 0; j--) {
1062          putc_or_die((c & (1 << j)) ? '1' : '0', fpo);
1063        }
1064        p++;
1065      } else {
1066        FPRINTF_OR_DIE((fpo, (hexx == hexxa) ? "%s0x%02x" : "%s0X%02X",
1067                        (p % cols) ? ", " : (!p ? "  " : ",\n  "), c));
1068        p++;
1069      }
1070    }
1071
1072    if (p) {
1073      fputs_or_die("\n", fpo);
1074    }
1075
1076    if (varname != NULL) {
1077      fputs_or_die("};\n", fpo);
1078      FPRINTF_OR_DIE((fpo, "unsigned int %s", isdigit((unsigned char)varname[0]) ? "__" : ""));
1079      for (e = 0; (c = varname[e]) != 0; e++) {
1080        putc_or_die(isalnum((unsigned char)c) ? CONDITIONAL_CAPITALIZE(c) : '_', fpo);
1081      }
1082      FPRINTF_OR_DIE((fpo, "_%s = %d;\n", capitalize ? "LEN" : "len", p));
1083    }
1084
1085    fclose_or_die(fp, fpo);
1086    return 0;
1087  }
1088
1089  if (hextype == HEX_POSTSCRIPT) {
1090    p = cols;
1091    while ((length < 0 || n < length) && (e = getc_or_die(fp)) != EOF) {
1092      putc_or_die(hexx[(e >> 4) & 0xf], fpo);
1093      putc_or_die(hexx[e & 0xf], fpo);
1094      n++;
1095      if (cols > 0 && !--p) {
1096        putc_or_die('\n', fpo);
1097        p = cols;
1098      }
1099    }
1100    if (cols == 0 || p < cols) {
1101      putc_or_die('\n', fpo);
1102    }
1103    fclose_or_die(fp, fpo);
1104    return 0;
1105  }
1106
1107  // hextype: HEX_NORMAL or HEX_BITS or HEX_LITTLEENDIAN
1108
1109  if (hextype != HEX_BITS) {
1110    grplen = octspergrp + octspergrp + 1;     // chars per octet group
1111  } else {  // hextype == HEX_BITS
1112    grplen = 8 * octspergrp + 1;
1113  }
1114
1115  while ((length < 0 || n < length) && (e = getc_or_die(fp)) != EOF) {
1116    if (p == 0) {
1117      addrlen = sprintf(l, decimal_offset ? "%08ld:" : "%08lx:",
1118                        ((unsigned long)(n + seekoff + displayoff)));
1119      for (c = addrlen; c < LLEN_NO_COLOR; l[c++] = ' ') {}
1120    }
1121    x = hextype == HEX_LITTLEENDIAN ? p ^ (octspergrp - 1) : p;
1122    c = addrlen + 1 + (grplen * x) / octspergrp;
1123    if (hextype == HEX_NORMAL || hextype == HEX_LITTLEENDIAN) {
1124      if (color) {
1125        cur_color = get_color_char(e, ebcdic);
1126        colors[c] = cur_color;
1127        colors[c + 1] = cur_color;
1128      }
1129
1130      l[c] = hexx[(e >> 4) & 0xf];
1131      l[++c] = hexx[e & 0xf];
1132    } else {  // hextype == HEX_BITS
1133      for (i = 7; i >= 0; i--) {
1134        l[c++] = (e & (1 << i)) ? '1' : '0';
1135      }
1136    }
1137    if (e) {
1138      nonzero++;
1139    }
1140    // When changing this update definition of LLEN and LLEN_NO_COLOR above.
1141    if (hextype == HEX_LITTLEENDIAN) {
1142      // last group will be fully used, round up
1143      c = grplen * ((cols + octspergrp - 1) / octspergrp);
1144    } else {
1145      c = (grplen * cols - 1) / octspergrp;
1146    }
1147
1148    if (ebcdic) {
1149      e = (e < 64) ? '.' : etoa64[e - 64];
1150    }
1151
1152    if (hextype == HEX_LITTLEENDIAN) {
1153      c -= 1;
1154    }
1155
1156    c += addrlen + 3 + p;
1157    if (color) {
1158      colors[c] = cur_color;
1159    }
1160    l[c++] =
1161#if defined(__MVS__) && __CHARSET_LIB == 0
1162      (e >= 64)
1163#else
1164      (e > 31 && e < 127)
1165#endif
1166      ? e : '.';
1167    n++;
1168    if (++p == cols) {
1169      l[c++] = '\n';
1170      l[c] = '\0';
1171
1172      xxdline(fpo, l, color ? colors : NULL, autoskip ? nonzero : 1);
1173      memset(colors, 0, c);
1174      nonzero = 0;
1175      p = 0;
1176    }
1177  }
1178  if (p) {
1179    l[c++] = '\n';
1180    l[c] = '\0';
1181    if (color) {
1182      x = p;
1183      if (hextype == HEX_LITTLEENDIAN) {
1184        int fill = octspergrp - (p % octspergrp);
1185        if (fill == octspergrp) {
1186          fill = 0;
1187        }
1188
1189        c = addrlen + 1 + (grplen * (x - (octspergrp - fill))) / octspergrp;
1190
1191        for (i = 0; i < fill; i++) {
1192          colors[c] = COLOR_RED;
1193          l[c++] = ' ';  // empty space
1194          x++;
1195          p++;
1196        }
1197      }
1198
1199      if (hextype != HEX_BITS) {
1200        c = addrlen + 1 + (grplen * x) / octspergrp;
1201        c += cols - p;
1202        c += (cols - p) / octspergrp;
1203
1204        for (i = cols - p; i > 0; i--) {
1205          colors[c] = COLOR_RED;
1206          l[c++] = ' ';  // empty space
1207        }
1208      }
1209      xxdline(fpo, l, colors, 1);
1210    } else {
1211      xxdline(fpo, l, NULL, 1);
1212    }
1213  } else if (autoskip) {
1214    xxdline(fpo, l, color ? colors : NULL, -1);  // last chance to flush out suppressed lines
1215  }
1216  fclose_or_die(fp, fpo);
1217  return 0;
1218}
1219
1220// vi:set ts=8 sw=4 sts=2 cino+={2 cino+=n-2 :