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 11import sys 12 13 14def get_args(): 15 16 parser = argparse.ArgumentParser(description='Converts a binary file ' 17 'into C source file defining binary ' 18 'data as a constant byte array.') 19 20 parser.add_argument('--bin', required=True, 21 help='Path to the input binary file') 22 23 parser.add_argument('--vname', required=True, 24 help='Variable name for the generated table in ' 25 'the output C source file.') 26 27 parser.add_argument('--out', required=True, 28 help='Path for the generated C file') 29 30 parser.add_argument('--text', required=False, action='store_true', 31 help='Treat input as a text file') 32 33 return parser.parse_args() 34 35 36def main(): 37 38 args = get_args() 39 40 with open(args.bin, 'rb') as indata: 41 bytes = indata.read() 42 if args.text: 43 bytes += b'\0' 44 size = len(bytes) 45 46 f = open(args.out, 'w') 47 f.write('/* Generated from ' + args.bin + ' by ' + 48 os.path.basename(__file__) + ' */\n\n') 49 f.write('#include <compiler.h>\n') 50 f.write('#include <stdint.h>\n') 51 if args.text: 52 f.write('__extension__ const char ' + args.vname + '[] = {\n') 53 else: 54 f.write('__extension__ const uint8_t ' + args.vname + '[] ' + 55 ' __aligned(__alignof__(uint64_t)) = {\n') 56 i = 0 57 while i < size: 58 if i % 8 == 0: 59 f.write('\t\t') 60 if args.text and i != size - 1 and bytes[i] == b'\0': 61 print('Error: null byte encountered in text file') 62 sys.exit(1) 63 f.write('0x' + '{:02x}'.format(bytes[i]) + ',') 64 i = i + 1 65 if i % 8 == 0 or i == size: 66 f.write('\n') 67 else: 68 f.write(' ') 69 f.write('};\n') 70 f.close() 71 72 73if __name__ == "__main__": 74 main() 75