1 /* 2 * Helper to hexdump a buffer 3 * 4 * Copyright (c) 2013 Red Hat, Inc. 5 * Copyright (c) 2013 Gerd Hoffmann <kraxel@redhat.com> 6 * Copyright (c) 2013 Peter Crosthwaite <peter.crosthwaite@xilinx.com> 7 * Copyright (c) 2013 Xilinx, Inc 8 * 9 * This work is licensed under the terms of the GNU GPL, version 2. See 10 * the COPYING file in the top-level directory. 11 * 12 * Contributions after 2012-01-13 are licensed under the terms of the 13 * GNU GPL, version 2 or (at your option) any later version. 14 */ 15 16 #include "qemu/osdep.h" 17 #include "qemu/cutils.h" 18 19 void qemu_hexdump_line(char *line, const void *bufptr, size_t len) 20 { 21 const char *buf = bufptr; 22 int i; 23 24 if (len > QEMU_HEXDUMP_LINE_BYTES) { 25 len = QEMU_HEXDUMP_LINE_BYTES; 26 } 27 28 for (i = 0; i < len; i++) { 29 if (i != 0 && (i % 4) == 0) { 30 *line++ = ' '; 31 } 32 line += sprintf(line, " %02x", (unsigned char)buf[i]); 33 } 34 *line = '\0'; 35 } 36 37 static void asciidump_line(char *line, const void *bufptr, size_t len) 38 { 39 const char *buf = bufptr; 40 41 for (size_t i = 0; i < len; i++) { 42 char c = buf[i]; 43 44 if (c < ' ' || c > '~') { 45 c = '.'; 46 } 47 *line++ = c; 48 } 49 *line = '\0'; 50 } 51 52 #define QEMU_HEXDUMP_LINE_WIDTH \ 53 (QEMU_HEXDUMP_LINE_BYTES * 2 + QEMU_HEXDUMP_LINE_BYTES / 4) 54 55 void qemu_hexdump(FILE *fp, const char *prefix, 56 const void *bufptr, size_t size) 57 { 58 char line[QEMU_HEXDUMP_LINE_LEN]; 59 char ascii[QEMU_HEXDUMP_LINE_BYTES + 1]; 60 size_t b, len; 61 62 for (b = 0; b < size; b += len) { 63 len = MIN(size - b, QEMU_HEXDUMP_LINE_BYTES); 64 65 qemu_hexdump_line(line, bufptr + b, len); 66 asciidump_line(ascii, bufptr + b, len); 67 68 fprintf(fp, "%s: %04zx: %-*s %s\n", 69 prefix, b, QEMU_HEXDUMP_LINE_WIDTH, line, ascii); 70 } 71 72 } 73