rules: discard rules with provably-incompatible OS/arch/format constraints before analysis begins#2929
Conversation
Add RuleSet.filter_rules_by_meta_features() which walks each rule's statement tree and removes rules whose OS, architecture, or format requirements are provably unsatisfiable given the binary's global features. The check is conservative: rules with no global-feature constraints or os: any are always kept; only rules that explicitly require a different platform are dropped. Transitive dependencies of surviving rules are preserved to maintain RuleSet invariants. Call the new method once at the start of find_static_capabilities() and find_dynamic_capabilities(), before the per-function/per-process loops, so that incompatible rules are excluded from every subsequent scope evaluation. Adds two tests: one verifying OS-specific rules are pruned/kept correctly, and one verifying cross-platform rules are never pruned. Closes: mandiant#2127
Summary of ChangesHello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed! This pull request introduces a significant optimization to capa's rule evaluation process. By identifying and discarding rules that are fundamentally incompatible with a binary's global features (such as its operating system, architecture, or file format) before detailed analysis begins, the system avoids redundant evaluations. This conservative pruning strategy ensures that only relevant rules are considered, leading to improved performance without compromising the accuracy of capability detection. Highlights
🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console. Changelog
Activity
Using Gemini Code AssistThe full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips. Invoking Gemini You can request assistance from Gemini at any point by creating a comment using either
Customization To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a Limitations & Feedback Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here. You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension. Footnotes
|
There was a problem hiding this comment.
Code Review
This pull request introduces a valuable optimization by pre-filtering rules based on global features like OS, architecture, and format. This avoids unnecessary evaluations in various scopes. The implementation is clean and the new method filter_rules_by_meta_features is well-designed, especially its conservative approach and handling of rule dependencies. The changes in find_static_capabilities and find_dynamic_capabilities correctly integrate this new filtering step. The added tests verify the core functionality. I have one suggestion to make the pruning logic for some statements even more effective.
capa/rules/__init__.py
Outdated
| if isinstance(node, (ceng.Or, ceng.Some)): | ||
| if isinstance(node, ceng.Some) and node.count == 0: | ||
| return True | ||
| return any(can_match(child) for child in node.children) |
There was a problem hiding this comment.
The current implementation for some statements in can_match is a bit too conservative. It checks if any child is satisfiable, which is correct for or statements, but for some: N statements, we can be more precise. A some: N statement is provably unsatisfiable if fewer than N of its children are potentially satisfiable. By counting the satisfiable children, we can prune more rules correctly.
This change would allow pruning rules like 2 or more: [os: windows, os: linux] when analyzing a Windows binary, which is currently kept but is provably unsatisfiable.
| if isinstance(node, (ceng.Or, ceng.Some)): | |
| if isinstance(node, ceng.Some) and node.count == 0: | |
| return True | |
| return any(can_match(child) for child in node.children) | |
| if isinstance(node, (ceng.Or, ceng.Some)): | |
| if isinstance(node, ceng.Some): | |
| if node.count == 0: | |
| return True | |
| # A `some` statement is unsatisfiable if fewer than `count` children are satisfiable. | |
| return sum(1 for child in node.children if can_match(child)) >= node.count | |
| # ceng.Or | |
| return any(can_match(child) for child in node.children) |
|
…eature-rule-pruning # Conflicts: # CHANGELOG.md
…_match guards
Previously _clone_with_rule_subset did a shallow copy and relied on a
candidate_rule_names.intersection_update(self.rules) guard in the hot
_match path to exclude pruned rules. That guard ran on every scope
evaluation (every function, basic-block, instruction call), adding
per-call overhead that the benchmarks showed dominated any savings.
This commit moves the filtering work to _clone_with_rule_subset where
it belongs — paid once at analysis start, not millions of times.
_clone_with_rule_subset now filters:
- rules_by_scope (per-scope Rule lists)
- _rule_index_by_scope (topological sort keys; gaps are fine)
- rules_by_namespace (Rule lists per namespace; empty entries dropped)
- _feature_indexes_by_scopes (rules_by_feature sets, string_rules,
bytes_rules — all trimmed to survivors)
- _dependencies_by_rule_name (dep sets for pruned rules dropped)
With consistent indexes, _match no longer needs:
- intersection_update(self.rules) after candidate collection
- "rule_name in self.rules" guard during dependency expansion
- list-comprehension filter in paranoid mode
Cost: O(total feature-index entries across all scopes) — comparable to
_index_rules_by_feature at init, paid once per binary analysis.
|
Hey @williballenthin Re-ran the benchmarks after fixing the intersection_update overhead. Quick summary: The old implementation had a per-call intersection_update guard in _match that ran on every scope evaluation (every function, basic block, instruction). That's what caused the +57-65% regressions I reported earlier. The fix was to make _clone_with_rule_subset do a proper one-time filtering of all derived structures — rules_by_scope, _rule_index_by_scope, As you predicted, evaluate.feature.rule count doesn't change, which confirms the optimizer was already handling global features cheaply. The small timing wins are probably cache effects from a slightly smaller data structure rather than saved evaluations. So to be honest: this PR doesn't meaningfully speed up capa on these samples. The gains are within noise. The case for merging is correctness and intent — rules that provably can't match are cleanly excluded before analysis begins, the RuleSet is in a fully consistent state after filtering, and the _match path has no compensating guards. If the Happy to close if you'd rather keep scope narrow, but the implementation is clean now. |

Summary
Closes #2127.
capa evaluates every rule against every function, basic block, and instruction in the binary under analysis. Rules that require a specific OS, architecture, or file format (e.g.
os: windows) are currently carried through all of these evaluations even when the binary is clearly not for that platform — they simply fail silently at each scope.Since the binary's OS, arch, and format are known before the per-function loop starts, we can prune incompatible rules once and eliminate them from every subsequent scope evaluation.
What changed
capa/rules/__init__.py—RuleSet.filter_rules_by_meta_features()New public method on
RuleSet. Given aFeatureSetcontaining the binary's global features (OS, arch, format), it:Walks each rule's statement tree with a conservative
can_match()predicate. A node is considered unsatisfiable only when a global feature requirement in it is provably contradicted by the known global features —os: windowswhen the binary isos: linux, for example.NOTnodes, optional blocks (count: 0,0 or more), and all non-global features are passed through as unknown / satisfiable.Rules that are provably unsatisfiable are excluded from the output
RuleSet.To preserve internal dependency invariants (
ensure_rule_dependencies_are_met), any rule that is a transitive dependency of a surviving rule is retained even if it would otherwise be filtered. This is handled by callingget_rules_and_dependencies()for each compatible rule.If no rules are pruned,
selfis returned unchanged to avoid an unnecessary rebuild.capa/capabilities/static.py—find_static_capabilities()Calls
extractor.extract_global_features()once before the function loop, then passes the result toruleset.filter_rules_by_meta_features(). The filtered ruleset replaces the original for all downstream evaluation.capa/capabilities/dynamic.py—find_dynamic_capabilities()Same one-time pruning step applied before the process loop.
Correctness
The filtering is conservative by design: a rule is only removed when its global-feature constraints are provably unsatisfiable. Rules with no global-feature constraints,
os: any-style wildcards, or ambiguous OR branches are always kept. No rule that could match is ever discarded.Tests
Two new tests in
tests/test_match.py:test_filter_rules_by_meta_features_prunes_incompatible_os— verifies that Windows-only rules are removed when analysing a Linux binary, and vice versa.test_filter_rules_by_meta_features_keeps_any_os— verifies that rules with no OS constraint survive regardless of the binary's OS.Test plan
pytest tests/test_match.py tests/test_rules.py -v— 67 tests passpre-commit run --all-files— isort, black, ruff all pass