1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3# Copyright (c) 2022 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
20from util import build_utils
21
22
23def parse_args(args):
24    parser = argparse.ArgumentParser()
25    build_utils.add_depfile_option(parser)
26
27    parser.add_argument('--clang-path', help='path to clang')
28    parser.add_argument('--include-dirs', nargs='+', help='path to header files')
29    parser.add_argument('--output-file', help='path to .o file')
30    parser.add_argument('--input-file', nargs='+', help='path to .c file')
31    parser.add_argument('--defines', nargs='+', help='clang defines')
32
33    options = parser.parse_args(args)
34    return options
35
36
37def bpf_compile(options, cmd: str):
38    my_env = None
39    for f in options.input_file:
40        cmd.extend(['-c', f])
41        cmd.extend(['-o', options.output_file])
42        build_utils.check_output(cmd, env=my_env)
43
44
45def main(args):
46    options = parse_args(args)
47    cmd = [options.clang_path]
48    cmd.extend(['-v', '-g', '-c', '-O2', '-target', 'bpf'])
49    for include_dir in options.include_dirs:
50        cmd.extend(['-I', include_dir])
51
52    if options.defines:
53        for define in options.defines:
54            cmd.extend(['-D', define])
55
56    outputs = [options.output_file]
57
58    build_utils.call_and_write_depfile_if_stale(
59        lambda: bpf_compile(options, cmd),
60        options,
61        depfile_deps=([options.clang_path]),
62        input_paths=(options.input_file + [options.clang_path]),
63        output_paths=(outputs),
64        input_strings=cmd,
65        force=False,
66        add_pydeps=False
67    )
68
69
70if __name__ == '__main__':
71    sys.exit(main(sys.argv[1:]))
72