Commit | Line | Data |
---|---|---|
b2441318 | 1 | // SPDX-License-Identifier: GPL-2.0 |
1da177e4 LT |
2 | /* |
3 | * hex2hex reads stdin in Intel HEX format and produces an | |
4 | * (unsigned char) array which contains the bytes and writes it | |
5 | * to stdout using C syntax | |
6 | */ | |
7 | ||
8 | #include <stdio.h> | |
9 | #include <string.h> | |
10 | #include <stdlib.h> | |
11 | ||
12 | #define ABANDON(why) { fprintf(stderr, "%s\n", why); exit(1); } | |
13 | #define MAX_SIZE (256*1024) | |
14 | unsigned char buf[MAX_SIZE]; | |
15 | ||
e8e63cbf | 16 | static int loadhex(FILE *inf, unsigned char *buf) |
1da177e4 LT |
17 | { |
18 | int l=0, c, i; | |
19 | ||
20 | while ((c=getc(inf))!=EOF) | |
21 | { | |
22 | if (c == ':') /* Sync with beginning of line */ | |
23 | { | |
24 | int n, check; | |
25 | unsigned char sum; | |
26 | int addr; | |
27 | int linetype; | |
28 | ||
29 | if (fscanf(inf, "%02x", &n) != 1) | |
30 | ABANDON("File format error"); | |
31 | sum = n; | |
32 | ||
33 | if (fscanf(inf, "%04x", &addr) != 1) | |
34 | ABANDON("File format error"); | |
35 | sum += addr/256; | |
36 | sum += addr%256; | |
37 | ||
38 | if (fscanf(inf, "%02x", &linetype) != 1) | |
39 | ABANDON("File format error"); | |
40 | sum += linetype; | |
41 | ||
42 | if (linetype != 0) | |
43 | continue; | |
44 | ||
45 | for (i=0;i<n;i++) | |
46 | { | |
47 | if (fscanf(inf, "%02x", &c) != 1) | |
48 | ABANDON("File format error"); | |
49 | if (addr >= MAX_SIZE) | |
50 | ABANDON("File too large"); | |
51 | buf[addr++] = c; | |
52 | if (addr > l) | |
53 | l = addr; | |
54 | sum += c; | |
55 | } | |
56 | ||
57 | if (fscanf(inf, "%02x", &check) != 1) | |
58 | ABANDON("File format error"); | |
59 | ||
60 | sum = ~sum + 1; | |
61 | if (check != sum) | |
62 | ABANDON("Line checksum error"); | |
63 | } | |
64 | } | |
65 | ||
66 | return l; | |
67 | } | |
68 | ||
69 | int main( int argc, const char * argv [] ) | |
70 | { | |
71 | const char * varline; | |
72 | int i,l; | |
73 | int id=0; | |
74 | ||
75 | if(argv[1] && strcmp(argv[1], "-i")==0) | |
76 | { | |
77 | argv++; | |
78 | argc--; | |
79 | id=1; | |
80 | } | |
81 | if(argv[1]==NULL) | |
82 | { | |
83 | fprintf(stderr,"hex2hex: [-i] filename\n"); | |
84 | exit(1); | |
85 | } | |
86 | varline = argv[1]; | |
87 | l = loadhex(stdin, buf); | |
88 | ||
89 | printf("/*\n *\t Computer generated file. Do not edit.\n */\n"); | |
90 | printf("static int %s_len = %d;\n", varline, l); | |
91 | printf("static unsigned char %s[] %s = {\n", varline, id?"__initdata":""); | |
92 | ||
93 | for (i=0;i<l;i++) | |
94 | { | |
95 | if (i) printf(","); | |
96 | if (i && !(i % 16)) printf("\n"); | |
97 | printf("0x%02x", buf[i]); | |
98 | } | |
99 | ||
100 | printf("\n};\n\n"); | |
101 | return 0; | |
102 | } |