-
Notifications
You must be signed in to change notification settings - Fork 24
/
misc.c
100 lines (93 loc) · 1.7 KB
/
misc.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#include <misc.h>
uint64_t file_save(const char * filename, void * buf, uint64_t len)
{
FILE * out;
int r;
if(strcmp(filename, "-") == 0)
out = stdout;
else
out = fopen(filename, "wb");
if(!out)
{
perror("Failed to open output file");
exit(-1);
}
r = fwrite(buf, len, 1, out);
if(out != stdout)
fclose(out);
return r;
}
void * file_load(const char * filename, uint64_t * len)
{
uint64_t offset = 0, bufsize = 8192;
char * buf = malloc(bufsize);
FILE * in;
if(strcmp(filename, "-") == 0)
in = stdin;
else
in = fopen(filename, "rb");
if(!in)
{
perror("Failed to open input file");
exit(-1);
}
while(1)
{
uint64_t len = bufsize - offset;
uint64_t n = fread(buf + offset, 1, len, in);
offset += n;
if(n < len)
break;
bufsize *= 2;
buf = realloc(buf, bufsize);
if(!buf)
{
perror("Failed to resize load_file() buffer");
exit(-1);
}
}
if(len)
*len = offset;
if(in != stdin)
fclose(in);
return buf;
}
static inline unsigned char hex_to_bin(char c)
{
if((c >= 'a') && (c <= 'f'))
return c - 'a' + 10;
if((c >= '0') && (c <= '9'))
return c - '0';
if((c >= 'A') && (c <= 'F'))
return c - 'A' + 10;
return 0;
}
unsigned char hex_string(const char * s, int o)
{
return (hex_to_bin(s[o]) << 4) | hex_to_bin(s[o + 1]);
}
void hexdump(uint32_t addr, void * buf, size_t len)
{
unsigned char * p = buf;
size_t i, j;
for(j = 0; j < len; j += 16)
{
printf("%08x: ", (uint32_t)(addr + j));
for(i = 0; i < 16; i++)
{
if(j + i < len)
printf("%02x ", p[j + i]);
else
printf(" ");
}
putchar(' ');
for(i = 0; i < 16; i++)
{
if(j + i >= len)
putchar(' ');
else
putchar(isprint(p[j + i]) ? p[j + i] : '.');
}
printf("\r\n");
}
}