1load("@bazel_tools//tools/build_defs/cc:action_names.bzl", "OBJ_COPY_ACTION_NAME")
2load("@rules_cc//cc:find_cc_toolchain.bzl", "find_cpp_toolchain", "use_cc_toolchain")
3
4def _objcopy_to_bin_impl(ctx):
5    cc_toolchain = find_cpp_toolchain(ctx)
6    feature_configuration = cc_common.configure_features(
7        ctx = ctx,
8        cc_toolchain = cc_toolchain,
9        requested_features = ctx.features,
10        unsupported_features = ctx.disabled_features,
11    )
12    objcopy_tool_path = cc_common.get_tool_for_action(
13        feature_configuration = feature_configuration,
14        action_name = OBJ_COPY_ACTION_NAME,
15    )
16
17    ctx.actions.run(
18        inputs = depset(
19            direct = [ctx.file.src],
20            transitive = [cc_toolchain.all_files],
21        ),
22        executable = objcopy_tool_path,
23        outputs = [ctx.outputs.out],
24        arguments = [
25            ctx.file.src.path,
26            "-Obinary",
27            ctx.outputs.out.path,
28        ],
29    )
30
31objcopy_to_bin = rule(
32    implementation = _objcopy_to_bin_impl,
33    attrs = {
34        "src": attr.label(
35            allow_single_file = True,
36            mandatory = True,
37            doc = "File to use as input to objcopy command",
38        ),
39        "out": attr.output(
40            mandatory = True,
41            doc = "Destination file for objcopy command",
42        ),
43    },
44    fragments = ["cpp"],
45    toolchains = use_cc_toolchain(),
46)
47