Skip to content

Commit

Permalink
userland: add "hexdump" command
Browse files Browse the repository at this point in the history
  • Loading branch information
mosmeh committed Jun 21, 2024
1 parent 6f9db7f commit 67c8149
Show file tree
Hide file tree
Showing 2 changed files with 88 additions and 0 deletions.
1 change: 1 addition & 0 deletions userland/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ BIN_TARGET_NAMES := \
fib \
grep \
halt \
hexdump \
imgview \
init \
init-test \
Expand Down
87 changes: 87 additions & 0 deletions userland/hexdump.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

static void dump_file(int fd, bool canonical) {
size_t offset = 0;
for (;;) {
uint8_t buf[16];
ssize_t nread;
size_t cursor = 0;
for (; cursor < sizeof(buf);) {
nread = read(fd, (char*)buf + cursor, sizeof(buf) - cursor);
if (nread < 0) {
perror("read");
return;
}
if (nread == 0)
break;
cursor += nread;
}
size_t len = cursor;
if (len == 0)
break;

printf("%08x", offset);
offset += 0x10;

if (canonical) {
printf(" ");
for (size_t i = 0; i < sizeof(buf); ++i) {
if (i < len)
printf(" %02x", buf[i]);
else
printf(" ");
if (i == 7)
printf(" ");
}
printf(" |");
for (size_t i = 0; i < len; ++i)
putchar(isprint(buf[i]) ? buf[i] : '.');
printf("|\n");
} else {
for (size_t i = 0; i < len; i += 2) {
if (i + 1 < cursor)
printf(" %04x", (buf[i + 1] << 8) | buf[i]);
else
printf(" 00%02x", buf[i]);
}
puts("");
}

if (nread == 0)
break;
}
}

int main(int argc, char* argv[]) {
if (argc < 2) {
dprintf(STDERR_FILENO, "Usage: hexdump [-C] FILE...\n");
return EXIT_FAILURE;
}

bool canonical = false;
for (int i = 1; i < argc; ++i) {
if (!strcmp(argv[i], "-C")) {
canonical = true;
break;
}
}

for (int i = 1; i < argc; ++i) {
const char* filename = argv[i];
if (!strcmp(filename, "-C"))
continue;
int fd = open(filename, O_RDONLY);
if (fd < 0) {
perror("open");
continue;
}
dump_file(fd, canonical);
close(fd);
}

return EXIT_SUCCESS;
}

0 comments on commit 67c8149

Please sign in to comment.