Linus Walleij | b9256fd | 2006-02-15 09:40:43 +0000 | [diff] [blame] | 1 | /** |
| 2 | * \file util.c |
| 3 | * |
| 4 | * This file contains generic utility functions such as can be |
| 5 | * used for debugging for example. |
| 6 | */ |
| 7 | |
| 8 | /* MSVC does not have these */ |
| 9 | #ifndef _MSC_VER |
| 10 | #include <sys/time.h> |
| 11 | #include <unistd.h> |
| 12 | #endif |
| 13 | |
| 14 | #include <stdio.h> |
| 15 | #include <stdlib.h> |
| 16 | #include <errno.h> |
| 17 | #include <sys/stat.h> |
| 18 | #include <fcntl.h> |
| 19 | #include "libmtp.h" |
| 20 | #include "util.h" |
| 21 | |
| 22 | /** |
| 23 | * This dumps out a number of bytes to a textual, hexadecimal |
| 24 | * dump. |
| 25 | * |
| 26 | * @param f the file to dump to (e.g. stdout or stderr) |
| 27 | * @param buf a pointer to the buffer containing the bytes to |
| 28 | * be dumped out in hex |
| 29 | * @param n the number of bytes to dump from this buffer |
| 30 | */ |
| 31 | void data_dump (FILE *f, void *buf, uint32_t n) |
| 32 | { |
| 33 | unsigned char *bp = (unsigned char *) buf; |
| 34 | uint32_t i; |
| 35 | |
| 36 | for (i = 0; i < n; i++) { |
| 37 | fprintf(f, "%02x ", *bp); |
| 38 | bp++; |
| 39 | } |
| 40 | fprintf(f, "\n"); |
| 41 | } |
| 42 | |
| 43 | /** |
| 44 | * This dumps out a number of bytes to a textual, hexadecimal |
| 45 | * dump, and also prints out the string ASCII representation |
| 46 | * for each line of bytes. It will also print the memory address |
| 47 | * offset from a certain boundry. |
| 48 | * |
| 49 | * @param f the file to dump to (e.g. stdout or stderr) |
| 50 | * @param buf a pointer to the buffer containing the bytes to |
| 51 | * be dumped out in hex |
| 52 | * @param n the number of bytes to dump from this buffer |
| 53 | * @param dump_boundry the address offset to start at (usually 0) |
| 54 | */ |
| 55 | void data_dump_ascii (FILE *f, void *buf, uint32_t n, uint32_t dump_boundry) |
| 56 | { |
| 57 | uint32_t remain = n; |
| 58 | uint32_t ln, lc; |
| 59 | int i; |
| 60 | unsigned char *bp = (unsigned char *) buf; |
| 61 | |
| 62 | lc = 0; |
| 63 | while (remain) { |
Linus Walleij | ca49859 | 2006-11-07 16:01:24 +0000 | [diff] [blame] | 64 | fprintf(f, "\t%04x:", dump_boundry-0x10); |
Linus Walleij | b9256fd | 2006-02-15 09:40:43 +0000 | [diff] [blame] | 65 | |
| 66 | ln = ( remain > 16 ) ? 16 : remain; |
| 67 | |
| 68 | for (i = 0; i < ln; i++) { |
| 69 | if ( ! (i%2) ) fprintf(f, " "); |
| 70 | fprintf(f, "%02x", bp[16*lc+i]); |
| 71 | } |
| 72 | |
| 73 | if ( ln < 16 ) { |
| 74 | int width = ((16-ln)/2)*5 + (2*(ln%2)); |
| 75 | fprintf(f, "%*.*s", width, width, ""); |
| 76 | } |
| 77 | |
| 78 | fprintf(f, "\t"); |
| 79 | for (i = 0; i < ln; i++) { |
| 80 | unsigned char ch= bp[16*lc+i]; |
| 81 | fprintf(f, "%c", ( ch >= 0x20 && ch <= 0x7e ) ? |
| 82 | ch : '.'); |
| 83 | } |
| 84 | fprintf(f, "\n"); |
| 85 | |
| 86 | lc++; |
| 87 | remain -= ln; |
| 88 | dump_boundry += ln; |
| 89 | } |
| 90 | } |