1 /* vi: set sw=4 ts=4: */
3 * hexdump implementation for busybox
4 * Based on code from util-linux v 2.11l
7 * The Regents of the University of California. All rights reserved.
9 * Licensed under GPLv2 or later, see file License in this tarball for details.
16 /* This is a NOEXEC applet. Be very careful! */
19 static void bb_dump_addfile(char *name)
25 fp = xfopen(name, "r");
27 while ((buf = xmalloc_getline(fp)) != NULL) {
28 p = skip_whitespace(buf);
30 if (*p && (*p != '#')) {
38 static const char *const add_strings[] = {
39 "\"%07.7_ax \" 16/1 \"%03o \" \"\\n\"", /* b */
40 "\"%07.7_ax \" 16/1 \"%3_c \" \"\\n\"", /* c */
41 "\"%07.7_ax \" 8/2 \" %05u \" \"\\n\"", /* d */
42 "\"%07.7_ax \" 8/2 \" %06o \" \"\\n\"", /* o */
43 "\"%07.7_ax \" 8/2 \" %04x \" \"\\n\"", /* x */
46 static const char add_first[] ALIGN1 = "\"%07.7_Ax\n\"";
48 static const char hexdump_opts[] ALIGN1 = "bcdoxCe:f:n:s:v" USE_FEATURE_HEXDUMP_REVERSE("R");
50 static const struct suffix_mult suffixes[] = {
57 int hexdump_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
58 int hexdump_main(int argc, char **argv)
62 #if ENABLE_FEATURE_HEXDUMP_REVERSE
67 bb_dump_vflag = FIRST;
70 if (ENABLE_HD && !applet_name[2]) { /* we are "hd" */
75 /* We cannot use getopt32: in hexdump options are cumulative.
76 * E.g. hexdump -C -C file should dump each line twice */
77 while ((ch = getopt(argc, argv, hexdump_opts)) > 0) {
78 p = strchr(hexdump_opts, ch);
81 if ((p - hexdump_opts) < 5) {
82 bb_dump_add(add_first);
83 bb_dump_add(add_strings[(int)(p - hexdump_opts)]);
85 /* Save a little bit of space below by omitting the 'else's. */
88 bb_dump_add("\"%08.8_Ax\n\"");
89 bb_dump_add("\"%08.8_ax \" 8/1 \"%02x \" \" \" 8/1 \"%02x \" ");
90 bb_dump_add("\" |\" 16/1 \"%_p\" \"|\\n\"");
96 bb_dump_addfile(optarg);
99 bb_dump_length = xatoi_u(optarg);
102 bb_dump_skip = xatoul_range_sfx(optarg, 0, LONG_MAX, suffixes);
107 #if ENABLE_FEATURE_HEXDUMP_REVERSE
114 if (!bb_dump_fshead) {
115 bb_dump_add(add_first);
116 bb_dump_add("\"%07.7_ax \" 8/2 \"%04x \" \"\\n\"");
121 #if !ENABLE_FEATURE_HEXDUMP_REVERSE
122 return bb_dump_dump(argv);
125 return bb_dump_dump(argv);
128 /* -R: reverse of 'hexdump -Cv' */
137 fp = xfopen(*argv, "r");
139 while ((buf = xmalloc_getline(fp)) != NULL) {
142 /* skip address or previous byte */
143 while (isxdigit(*p)) p++;
144 while (*p == ' ') p++;
145 /* '|' char will break the line */
146 if (!isxdigit(*p) || sscanf(p, "%x ", &ch) != 1)
155 fflush_stdout_and_exit(EXIT_SUCCESS);