1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3# Copyright (c) 2020 Huawei Device Co., Ltd.
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8#     http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
16import argparse
17import os
18import sys
19
20
21def resource_file_to_bytecode(input_dir, input_file, output_path):
22    with open(os.path.join(input_dir, input_file), 'rb')\
23            as resource_file_object:
24        with open(output_path, 'a') as cpp_file_object:
25            length = 0;
26            all_the_content = resource_file_object.read();
27            template0 = "#include <stdint.h>\n";
28            template1 = "const uint8_t  _binary_$1_start[$2] = {$3};\n";
29            template2 = \
30                "const uint8_t* _binary_$1_end = _binary_$1_start + $2;";
31
32            formats = ","
33            seq = []
34            for content in all_the_content:
35                seq.append(str(hex(content)))
36                length = length + 1
37            byte_code = formats.join(seq);
38            input_file = input_file.replace(".", "_")
39            template1 = template1.replace("$1", str(input_file)) \
40                .replace("$2", str(length)) \
41                .replace("$3", str(byte_code))
42            template2 = template2.replace("$1", str(input_file)) \
43                .replace("$2", str(length))
44            cpp_file_object.seek(0)
45            cpp_file_object.truncate();
46            cpp_file_object.write(template0 + template1 + template2);
47
48
49def main():
50    parser = argparse.ArgumentParser()
51    parser.add_argument('--objcopy', type=str, required=False)
52    parser.add_argument('--input', type=str, required=True)
53    parser.add_argument('--output', type=str, required=True)
54    parser.add_argument('--arch', type=str, required=False)
55
56    args = parser.parse_args()
57
58    input_dir, input_file = os.path.split(args.input)
59    output_path = os.path.abspath(args.output)
60    resource_file_to_bytecode(input_dir, input_file, output_path)
61
62
63if __name__ == '__main__':
64    sys.exit(main())
65