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 source tree.
15 /* This is a NOEXEC applet. Be very careful! */
17 static void bb_dump_addfile(dumper_t
*dumper
, char *name
)
23 fp
= xfopen_for_read(name
);
24 while ((buf
= xmalloc_fgetline(fp
)) != NULL
) {
25 p
= skip_whitespace(buf
);
26 if (*p
&& (*p
!= '#')) {
27 bb_dump_add(dumper
, p
);
34 static const char *const add_strings
[] = {
35 "\"%07.7_ax \" 16/1 \"%03o \" \"\\n\"", /* b */
36 "\"%07.7_ax \" 16/1 \"%3_c \" \"\\n\"", /* c */
37 "\"%07.7_ax \" 8/2 \" %05u \" \"\\n\"", /* d */
38 "\"%07.7_ax \" 8/2 \" %06o \" \"\\n\"", /* o */
39 "\"%07.7_ax \" 8/2 \" %04x \" \"\\n\"", /* x */
42 static const char add_first
[] ALIGN1
= "\"%07.7_Ax\n\"";
44 static const char hexdump_opts
[] ALIGN1
= "bcdoxCe:f:n:s:v" IF_FEATURE_HEXDUMP_REVERSE("R");
46 static const struct suffix_mult suffixes
[] = {
53 int hexdump_main(int argc
, char **argv
) MAIN_EXTERNALLY_VISIBLE
;
54 int hexdump_main(int argc
, char **argv
)
56 dumper_t
*dumper
= alloc_dumper();
59 #if ENABLE_FEATURE_HEXDUMP_REVERSE
64 if (ENABLE_HD
&& !applet_name
[2]) { /* we are "hd" */
69 /* We cannot use getopt32: in hexdump options are cumulative.
70 * E.g. "hexdump -C -C file" should dump each line twice */
71 while ((ch
= getopt(argc
, argv
, hexdump_opts
)) > 0) {
72 p
= strchr(hexdump_opts
, ch
);
75 if ((p
- hexdump_opts
) < 5) {
76 bb_dump_add(dumper
, add_first
);
77 bb_dump_add(dumper
, add_strings
[(int)(p
- hexdump_opts
)]);
79 /* Save a little bit of space below by omitting the 'else's. */
82 bb_dump_add(dumper
, "\"%08.8_Ax\n\"");
83 bb_dump_add(dumper
, "\"%08.8_ax \" 8/1 \"%02x \" \" \" 8/1 \"%02x \" ");
84 bb_dump_add(dumper
, "\" |\" 16/1 \"%_p\" \"|\\n\"");
87 bb_dump_add(dumper
, optarg
);
90 bb_dump_addfile(dumper
, optarg
);
93 dumper
->dump_length
= xatoi_positive(optarg
);
95 if (ch
== 's') { /* compat: -s accepts hex numbers too */
96 dumper
->dump_skip
= xstrtoul_range_sfx(optarg
, /*base:*/ 0, /*lo:*/ 0, /*hi:*/ LONG_MAX
, suffixes
);
99 dumper
->dump_vflag
= ALL
;
101 #if ENABLE_FEATURE_HEXDUMP_REVERSE
108 if (!dumper
->fshead
) {
109 bb_dump_add(dumper
, add_first
);
110 bb_dump_add(dumper
, "\"%07.7_ax \" 8/2 \"%04x \" \"\\n\"");
115 #if !ENABLE_FEATURE_HEXDUMP_REVERSE
116 return bb_dump_dump(dumper
, argv
);
119 return bb_dump_dump(dumper
, argv
);
122 /* -R: reverse of 'hexdump -Cv' */
131 fp
= xfopen_for_read(*argv
);
133 while ((buf
= xmalloc_fgetline(fp
)) != NULL
) {
136 /* skip address or previous byte */
137 while (isxdigit(*p
)) p
++;
138 while (*p
== ' ') p
++;
139 /* '|' char will break the line */
140 if (!isxdigit(*p
) || sscanf(p
, "%x ", &ch
) != 1)
149 fflush_stdout_and_exit(EXIT_SUCCESS
);