forked from OP-TEE/optee_os
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbin_to_c.py
executable file
·62 lines (47 loc) · 1.77 KB
/
bin_to_c.py
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
#!/usr/bin/env python3
# SPDX-License-Identifier: BSD-2-Clause
#
# Copyright (c) 2018, Linaro Limited
#
import argparse
import array
import os
import re
def get_args():
parser = argparse.ArgumentParser(description='Converts a binary file '
'into C source file defining binary '
'data as a constant byte array.')
parser.add_argument('--bin', required=True,
help='Path to the input binary file')
parser.add_argument('--vname', required=True,
help='Variable name for the generated table in '
'the output C source file.')
parser.add_argument('--out', required=True,
help='Path for the generated C file')
return parser.parse_args()
def main():
args = get_args()
with open(args.bin, 'rb') as indata:
bytes = indata.read()
size = len(bytes)
f = open(args.out, 'w')
f.write('/* Generated from ' + args.bin + ' by ' +
os.path.basename(__file__) + ' */\n\n')
f.write('#include <compiler.h>\n')
f.write('#include <stdint.h>\n')
f.write('__extension__ const uint8_t ' + args.vname + '[] ' +
' __aligned(__alignof__(uint64_t)) = {\n')
i = 0
while i < size:
if i % 8 == 0:
f.write('\t\t')
f.write('0x' + '{:02x}'.format(bytes[i]) + ',')
i = i + 1
if i % 8 == 0 or i == size:
f.write('\n')
else:
f.write(' ')
f.write('};\n')
f.close()
if __name__ == "__main__":
main()