xref: /optee_os/scripts/bin_to_c.py (revision 18c5148d357e51235bc842b7826ff6e8da109902)
1#!/usr/bin/env python3
2# SPDX-License-Identifier: BSD-2-Clause
3#
4# Copyright (c) 2018, Linaro Limited
5#
6
7import argparse
8import array
9import os
10import re
11
12
13def get_args():
14
15        parser = argparse.ArgumentParser(description='Converts a binary file '
16                                         'into C source file defining binary '
17                                         'data as a constant byte array.')
18
19        parser.add_argument('--bin', required=True,
20                            help='Path to the input binary file')
21
22        parser.add_argument('--vname', required=True,
23                            help='Variable name for the generated table in '
24                            'the output C source file.')
25
26        parser.add_argument('--out', required=True,
27                            help='Path for the generated C file')
28
29        return parser.parse_args()
30
31
32def main():
33
34        args = get_args()
35
36        with open(args.bin, 'rb') as indata:
37                bytes = indata.read()
38                size = len(bytes)
39
40        f = open(args.out, 'w')
41        f.write('/* Generated from ' + args.bin + ' by ' +
42                os.path.basename(__file__) + ' */\n\n')
43        f.write('#include <compiler.h>\n')
44        f.write('#include <stdint.h>\n')
45        f.write('__extension__ const uint8_t ' + args.vname + '[] ' +
46                ' __aligned(__alignof__(uint64_t)) = {\n')
47        i = 0
48        while i < size:
49                if i % 8 == 0:
50                        f.write('\t\t')
51                f.write('0x' + '{:02x}'.format(bytes[i]) + ',')
52                i = i + 1
53                if i % 8 == 0 or i == size:
54                        f.write('\n')
55                else:
56                        f.write(' ')
57        f.write('};\n')
58        f.close()
59
60
61if __name__ == "__main__":
62        main()
63