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.
15 /* This is a NOEXEC applet. Be very careful! */
18 static void bb_dump_addfile(dumper_t *dumper, char *name)
24 fp = xfopen(name, "r");
26 while ((buf = xmalloc_fgetline(fp)) != NULL) {
27 p = skip_whitespace(buf);
29 if (*p && (*p != '#')) {
30 bb_dump_add(dumper, p);
37 static const char *const add_strings[] = {
38 "\"%07.7_ax \" 16/1 \"%03o \" \"\\n\"", /* b */
39 "\"%07.7_ax \" 16/1 \"%3_c \" \"\\n\"", /* c */
40 "\"%07.7_ax \" 8/2 \" %05u \" \"\\n\"", /* d */
41 "\"%07.7_ax \" 8/2 \" %06o \" \"\\n\"", /* o */
42 "\"%07.7_ax \" 8/2 \" %04x \" \"\\n\"", /* x */
45 static const char add_first[] ALIGN1 = "\"%07.7_Ax\n\"";
47 static const char hexdump_opts[] ALIGN1 = "bcdoxCe:f:n:s:v" USE_FEATURE_HEXDUMP_REVERSE("R");
49 static const struct suffix_mult suffixes[] = {
56 int hexdump_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
57 int hexdump_main(int argc, char **argv)
59 dumper_t *dumper = alloc_dumper();
62 #if ENABLE_FEATURE_HEXDUMP_REVERSE
67 if (ENABLE_HD && !applet_name[2]) { /* we are "hd" */
72 /* We cannot use getopt32: in hexdump options are cumulative.
73 * E.g. "hexdump -C -C file" should dump each line twice */
74 while ((ch = getopt(argc, argv, hexdump_opts)) > 0) {
75 p = strchr(hexdump_opts, ch);
78 if ((p - hexdump_opts) < 5) {
79 bb_dump_add(dumper, add_first);
80 bb_dump_add(dumper, add_strings[(int)(p - hexdump_opts)]);
82 /* Save a little bit of space below by omitting the 'else's. */
85 bb_dump_add(dumper, "\"%08.8_Ax\n\"");
86 bb_dump_add(dumper, "\"%08.8_ax \" 8/1 \"%02x \" \" \" 8/1 \"%02x \" ");
87 bb_dump_add(dumper, "\" |\" 16/1 \"%_p\" \"|\\n\"");
90 bb_dump_add(dumper, optarg);
93 bb_dump_addfile(dumper, optarg);
96 dumper->dump_length = xatoi_u(optarg);
99 dumper->dump_skip = xatoul_range_sfx(optarg, 0, LONG_MAX, suffixes);
102 dumper->dump_vflag = ALL;
104 #if ENABLE_FEATURE_HEXDUMP_REVERSE
111 if (!dumper->fshead) {
112 bb_dump_add(dumper, add_first);
113 bb_dump_add(dumper, "\"%07.7_ax \" 8/2 \"%04x \" \"\\n\"");
118 #if !ENABLE_FEATURE_HEXDUMP_REVERSE
119 return bb_dump_dump(dumper, argv);
122 return bb_dump_dump(dumper, argv);
125 /* -R: reverse of 'hexdump -Cv' */
134 fp = xfopen(*argv, "r");
136 while ((buf = xmalloc_fgetline(fp)) != NULL) {
139 /* skip address or previous byte */
140 while (isxdigit(*p)) p++;
141 while (*p == ' ') p++;
142 /* '|' char will break the line */
143 if (!isxdigit(*p) || sscanf(p, "%x ", &ch) != 1)
152 fflush_stdout_and_exit(EXIT_SUCCESS);