Skip to content

Commit

Permalink
Allow cc_binary with dynamic_deps to be extended
Browse files Browse the repository at this point in the history
`cc_binary` has an initializer that may set a private attribute, which is only permitted for built-in rules. The allowlist check always used the outermost rule class, thus failing if `cc_binary` is extended by a non-built-in rule. This is fixed by checking the rule class that actually declares the initializer.

Work towards bazelbuild#19507 (comment)

Closes bazelbuild#24778.

PiperOrigin-RevId: 711361632
Change-Id: I3c0b6e1e6c50fd1af9f1dc635052d0054114ee2d
  • Loading branch information
fmeum authored and bazel-io committed Jan 2, 2025
1 parent c85e59b commit 42d744c
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -1694,7 +1694,7 @@ public Object call(StarlarkThread thread, Tuple args, Dict<String, Object> kwarg
checkAttributeName(arg);
if (arg.startsWith("_")) {
// allow setting private attributes from initializers in builtins
Label definitionLabel = ruleClass.getRuleDefinitionEnvironmentLabel();
Label definitionLabel = currentRuleClass.getRuleDefinitionEnvironmentLabel();
BuiltinRestriction.failIfLabelOutsideAllowlist(
definitionLabel,
RepositoryMapping.ALWAYS_FALLBACK,
Expand Down
41 changes: 41 additions & 0 deletions src/test/shell/bazel/cc_integration_test.sh
Original file line number Diff line number Diff line change
Expand Up @@ -2079,4 +2079,45 @@ EOF
bazel build //pkg:testCodegen &> "$TEST_log" || fail "Build failed"
}

function test_extend_cc_binary_with_dynamic_deps() {
mkdir -p pkg
cat >pkg/BUILD <<'EOF'
load("my_cc_binary.bzl", "my_cc_binary")
constraint_setting(name = "foo")
constraint_value(name = "never_selected", constraint_setting = ":foo")
my_cc_binary(
name = "hello",
srcs = ["main.cpp"],
# Ensure that the select has no effect but can't be simplified.
dynamic_deps = select({":never_selected": ["unused"], "//conditions:default": []}),
)
EOF

cat >pkg/my_cc_binary.bzl << 'EOF'
def _my_cc_binary_impl(ctx):
print("Hello from my_cc_binary")
return ctx.super()
my_cc_binary = rule(
implementation = _my_cc_binary_impl,
parent = native.cc_binary,
)
EOF

cat >pkg/main.cpp <<'EOF'
#include <iostream>
int main() {
std::cout << "Hello from main.cpp" << std::endl;
return 0;
}
EOF

bazel run //pkg:hello &> $TEST_log || fail "Expected success"
expect_log "Hello from my_cc_binary"
expect_log "Hello from main.cpp"
}

run_suite "cc_integration_test"

0 comments on commit 42d744c

Please sign in to comment.