Skip to content

rules: discard rules with provably-incompatible OS/arch/format constraints before analysis begins#2929

Open
devs6186 wants to merge 5 commits intomandiant:masterfrom
devs6186:fix/2127-global-feature-rule-pruning
Open

rules: discard rules with provably-incompatible OS/arch/format constraints before analysis begins#2929
devs6186 wants to merge 5 commits intomandiant:masterfrom
devs6186:fix/2127-global-feature-rule-pruning

Conversation

@devs6186
Copy link
Contributor

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__.pyRuleSet.filter_rules_by_meta_features()

New public method on RuleSet. Given a FeatureSet containing the binary's global features (OS, arch, format), it:

  1. 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: windows when the binary is os: linux, for example. NOT nodes, optional blocks (count: 0, 0 or more), and all non-global features are passed through as unknown / satisfiable.

  2. Rules that are provably unsatisfiable are excluded from the output RuleSet.

  3. 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 calling get_rules_and_dependencies() for each compatible rule.

  4. If no rules are pruned, self is returned unchanged to avoid an unnecessary rebuild.

capa/capabilities/static.pyfind_static_capabilities()

Calls extractor.extract_global_features() once before the function loop, then passes the result to ruleset.filter_rules_by_meta_features(). The filtered ruleset replaces the original for all downstream evaluation.

capa/capabilities/dynamic.pyfind_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 pass
  • pre-commit run --all-files — isort, black, ruff all pass

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
@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello, 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

  • Rule Pruning: Introduced a new mechanism to discard rules with provably incompatible OS, architecture, or format constraints early in the analysis process.
  • Performance Optimization: Eliminated the evaluation of incompatible rules against every scope (function, basic block, instruction), significantly reducing unnecessary processing.
  • Conservative Filtering: Implemented a conservative filtering approach that only removes rules when their global-feature constraints are demonstrably unsatisfiable, ensuring no valid rules are accidentally discarded.
  • Dependency Preservation: Ensured that all transitive dependencies of surviving rules are retained, maintaining the integrity of the rule set.
  • Integration: Applied the new rule pruning step to both static and dynamic capability analysis workflows.
  • Testing: Added dedicated unit tests to verify the correctness and robustness of the rule filtering logic for various OS scenarios.

🧠 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
  • CHANGELOG.md
    • Added a development entry for pruning rules based on incompatible global features.
  • capa/capabilities/dynamic.py
    • Integrated a one-time rule pruning step based on global features before dynamic analysis.
  • capa/capabilities/static.py
    • Integrated a one-time rule pruning step based on global features before static analysis.
  • capa/rules/init.py
    • Implemented the filter_rules_by_meta_features method to prune rules that cannot match the binary's global features.
    • Added logic to preserve transitive rule dependencies during pruning.
  • tests/test_match.py
    • Added OS_LINUX import.
    • Added new tests to verify the filter_rules_by_meta_features method for OS compatibility and wildcard scenarios.
Activity
  • The pull request addresses and closes issue prune rule logic using global features #2127.
  • The author has provided a test plan, including running pytest for test_match.py and test_rules.py, and pre-commit checks.
  • No other activity (comments, reviews, progress) has been recorded in the provided context.
Using Gemini Code Assist

The 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 /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

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 .gemini/ folder in the base of the repository. Detailed instructions can be found here.

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

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +1963 to +1966
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)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

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.

Suggested change
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)

@williballenthin
Copy link
Collaborator

williballenthin commented Mar 15, 2026

  1. i'm curious about the performance improvements with these changes. what difference are you seeing?

  2. the optimized rule matcher already computes a minimal set of features that must be present in order for a rule to match, so i'd expect that arch/os/format are checked very early during rule evaluation. it's true that the rules are not completely removed from evaluation, but i hope the overhead is negligible. can you disprove this?

…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.
@devs6186
Copy link
Contributor Author

Hey @williballenthin
I think I found the real source of overhead — _clone_with_rule_subset was doing a shallow copy and then compensating with an intersection_update(self.rules) guard inside _match. That guard ran on every single scope evaluation (every function, basic block, instruction), so it was adding per-call tax that the benchmarks were picking up.

Re-ran the benchmarks after fixing the intersection_update overhead. Quick summary:
image

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,
rules_by_namespace, the full feature indexes, string_rules, bytes_rules — so the hot path needs zero guards.

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
rule corpus grows to have many more platform-specific rules, the savings will scale. For now it's net-neutral at worst.

Happy to close if you'd rather keep scope narrow, but the implementation is clean now.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

prune rule logic using global features

2 participants