1#!/usr/bin/env python3
2# -*- coding: utf-8 -*-
3
4#
5# Copyright (c) 2023 Huawei Device Co., Ltd.
6# Licensed under the Apache License, Version 2.0 (the "License");
7# you may not use this file except in compliance with the License.
8# You may obtain a copy of the License at
9#
10#     http://www.apache.org/licenses/LICENSE-2.0
11#
12# Unless required by applicable law or agreed to in writing, software
13# distributed under the License is distributed on an "AS IS" BASIS,
14# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15# See the License for the specific language governing permissions and
16# limitations under the License.
17#
18
19import argparse
20import os
21import subprocess
22import sys
23
24OUTPUT_TARGET = {
25    "x86": "elf32-i386",
26    "x64": "elf64-x86-64",
27    "x86_64": "pe-x86-64",
28    "arm": "elf32-littlearm",
29    "arm64": "elf64-littleaarch64",
30}
31
32BUILD_ID_LINK_OUTPUT = {
33    "x86": "i386",
34    "x64": "i386:x86-64",
35    "x86_64": "i386:x86-64",
36    "arm": "arm",
37    "arm64": "aarch64",
38}
39
40
41def main():
42    parser = argparse.ArgumentParser(
43        description="Translate and copy data file to object file"
44    )
45    parser.add_argument(
46        "-e", "--objcopy", type=str, required=True, help="The path of objcopy"
47    )
48    parser.add_argument(
49        "-a", "--arch", type=str, required=True, help="The architecture of target"
50    )
51    parser.add_argument(
52        "-i", "--input", type=str, required=True, help="The path of input file"
53    )
54    parser.add_argument(
55        "-o", "--output", type=str, required=True, help="The path of output target"
56    )
57
58    args = parser.parse_args()
59    input_dir, input_file = os.path.split(args.input)
60
61    cmd = [
62        args.objcopy,
63        "-I",
64        "binary",
65        "-B",
66        BUILD_ID_LINK_OUTPUT[args.arch],
67        "-O",
68        OUTPUT_TARGET[args.arch],
69        input_file,
70        args.output,
71    ]
72
73    process = subprocess.Popen(
74        cmd,
75        stdout=subprocess.PIPE,
76        stderr=subprocess.STDOUT,
77        universal_newlines=True,
78        cwd=input_dir,
79    )
80    for line in iter(process.stdout.readline, ""):
81        sys.stdout.write(line)
82        sys.stdout.flush()
83
84    process.wait()
85    ret_code = process.returncode
86
87    return ret_code
88
89
90if __name__ == "__main__":
91    sys.exit(main())
92