ModSecurity icon indicating copy to clipboard operation
ModSecurity copied to clipboard

Reuse the precompiled regex for collection variable selectors

Open chweidling opened this issue 5 months ago • 3 comments

what

  • Add a fast-path InMemoryPerProcess::resolveRegularExpression(const Utils::Regex *) overload that takes an already-compiled regex.
  • Tx_DictElementRegexp (the TX:/regex/ variable selector) now reuses its pre-compiled m_r: it dynamic_casts the TX collection to InMemoryPerProcess and calls the fast path if possible.
  • Adds a regression test for TX:/regex/ selection (positive + negative cases).

why

  • The collection backends' resolveRegularExpression(const std::string&, ...) built a fresh Utils::Regex — i.e. a pcre2_compile() and pcre2_jit_compile() — on every call.
  • For a regex variable selector such as TX:/regex/ that is evaluated per transaction (e.g. CRS 921180), this recompiled the same pattern on every request, even though the calling VariableRegex already holds it compiled once at configuration time in m_r. That compiled regex was simply being ignored.
  • Behaviour is unchanged: m_r is constructed with the same arguments — Utils::Regex(pattern, /*ignoreCase=*/true) — that the backend used, so the identical regex is applied; it is just compiled once instead of per transaction.
  • Measured (built against v3/master, gcc -O2, system PCRE2 with JIT):
    • Microbenchmark of the resolution call: reusing the compiled regex vs recompiling is ~1.6× faster for a short selector, and the saving grows with pattern length (it is the eliminated compile + JIT).
  • No behaviour change: the full regression suite passes (634 passed, 80 skipped — unchanged), including the new test.

references

  • Related (not fixed by this change): #2972 and #3409 discuss general PCRE2 overhead; this PR removes one specific source of repeated PCRE2 compilation.

chweidling avatar Jun 10 '26 09:06 chweidling

The failing cppcheck check is unrelated to this PR. On a clean v3/master checkout with no changes, make check-static already fails under cppcheck 2.21.0 (and passes under 2.20.0) — the job installs cppcheck unpinned, so the analyzer version drifts. All 31 findings are in files this PR doesn't touch.

Filed as #3574.

All other CI jobs (Linux x32/x64 gcc+clang, all configs, macOS) pass.

chweidling avatar Jun 10 '26 17:06 chweidling

Hi @chweidling,

could you pick these changes or update your branch?

Thanks!

airween avatar Jun 16 '26 18:06 airween