chiark / gitweb /
util: add hexdump() call to create pretty hexdumps of data
authorLennart Poettering <lennart@poettering.net>
Fri, 14 Mar 2014 20:11:31 +0000 (21:11 +0100)
committerLennart Poettering <lennart@poettering.net>
Fri, 14 Mar 2014 20:17:14 +0000 (21:17 +0100)
This is very useful when debugging sd-bus to look at messages.

src/shared/util.c
src/shared/util.h
src/test/test-util.c

index 8b8d2fb..7e17851 100644 (file)
@@ -6347,3 +6347,46 @@ char* mount_test_option(const char *haystack, const char *needle) {
 
         return hasmntopt(&me, needle);
 }
+
+void hexdump(FILE *f, const void *p, size_t s) {
+        const uint8_t *b = p;
+        unsigned n = 0;
+
+        assert(s == 0 || b);
+
+        while (s > 0) {
+                size_t i;
+
+                fprintf(f, "%04x  ", n);
+
+                for (i = 0; i < 16; i++) {
+
+                        if (i >= s)
+                                fputs("   ", f);
+                        else
+                                fprintf(f, "%02x ", b[i]);
+
+                        if (i == 7)
+                                fputc(' ', f);
+                }
+
+                fputc(' ', f);
+
+                for (i = 0; i < 16; i++) {
+
+                        if (i >= s)
+                                fputc(' ', f);
+                        else
+                                fputc(isprint(b[i]) ? (char) b[i] : '.', f);
+                }
+
+                fputc('\n', f);
+
+                if (s < 16)
+                        break;
+
+                n += 16;
+                b += 16;
+                s -= 16;
+        }
+}
index e99f8d1..c596d79 100644 (file)
@@ -914,3 +914,5 @@ const char *personality_to_string(unsigned long);
 uint64_t physical_memory(void);
 
 char* mount_test_option(const char *haystack, const char *needle);
+
+void hexdump(FILE *f, const void *p, size_t s);
index 229f492..6297182 100644 (file)
@@ -626,6 +626,25 @@ static void test_writing_tmpfile(void) {
         assert(streq(contents, "abc\n" ALPHANUMERICAL "\n"));
 }
 
+static void test_hexdump(void) {
+        uint8_t data[146];
+        unsigned i;
+
+        hexdump(stdout, NULL, 0);
+        hexdump(stdout, "", 0);
+        hexdump(stdout, "", 1);
+        hexdump(stdout, "x", 1);
+        hexdump(stdout, "x", 2);
+        hexdump(stdout, "foobar", 7);
+        hexdump(stdout, "f\nobar", 7);
+        hexdump(stdout, "xxxxxxxxxxxxxxxxxxxxyz", 23);
+
+        for (i = 0; i < ELEMENTSOF(data); i++)
+                data[i] = i*2;
+
+        hexdump(stdout, data, sizeof(data));
+}
+
 int main(int argc, char *argv[]) {
         log_parse_environment();
         log_open();
@@ -667,6 +686,7 @@ int main(int argc, char *argv[]) {
         test_get_files_in_directory();
         test_in_set();
         test_writing_tmpfile();
+        test_hexdump();
 
         return 0;
 }