| # SPDX-License-Identifier: GPL-2.0+ |
| # Copyright (c) 2022 Google, Inc |
| """Script for generating C array for binary files |
| |
| Usage: <script> output file1 file2 file3 ... |
| """ |
| |
| import subprocess |
| import sys |
| from pathlib import Path |
| |
| COPYRIGHT_HEADER = """/* |
| * Copyright (c) 2022 The Fuchsia Authors |
| * |
| * SPDX-License-Identifier: BSD-3-Clause |
| */ |
| |
| #include <stddef.h> |
| |
| """ |
| |
| def byte_array_declaration(data: bytes, name: str) -> str: |
| """Generates a byte C array declaration for a byte array""" |
| type_name = 'const uint8_t' |
| byte_str = ''.join([f'0x{b:02x},' for b in data]) |
| array_body = f'{{{byte_str}}}' |
| return f'{type_name} {name}[] = {array_body};' |
| |
| def main() -> int: |
| if len(sys.argv) < 3: |
| print("not enough arguments") |
| return |
| |
| with open(sys.argv[1], "w") as output_file: |
| output_file.write(COPYRIGHT_HEADER) |
| for file in sys.argv[2:]: |
| with open(file, "rb") as input_file: |
| # Best effort conversion to valid C variable name. |
| var_name = "arr_" + Path(file).name.replace(".", "_") |
| output_file.write(byte_array_declaration(input_file.read(), var_name)) |
| output_file.write("\n") |
| |
| subprocess.run([ |
| "/usr/bin/clang-format", |
| "--style=file", |
| "-i", |
| sys.argv[1], |
| ], check=True) |
| |
| return 0 |
| |
| if __name__ == "__main__": |
| sys.exit(main()) |