Repository navigation
Replace RegexMatchContext with Regex::Options - #13748
Conversation
bryancall
left a comment
There was a problem hiding this comment.
✅ Approve
Replacing the class with a plain value is the right shape. Copying the shared context after the JIT stack is assigned carries the 1 MiB stack over (pcre2_match_context_copy copies the whole struct). The per-thread scratch context is safe, because get_instance() is thread_local and the JIT reads the limit once when the match starts. A grep of the tree, including plugins/experimental, cripts, tools and doc, finds no other users of RegexMatchContext or get_general_context.
Verified by running it
- With the patch:
test_tsutil "[Regex]"passes, 411 assertions in 22 test cases (dev-asan, x86_64, PCRE2 10.47). - Options context created blank again, the way
RegexMatchContextused to create it: "keeps the shared JIT stack" fails attest_Regex.cc:1007(opts_rc > 0). - Default calls routed through the options context, so a limit carries over: "does not leak between calls" fails at
:986with-47 == 4. - Standalone PCRE2 check on arm64 and x86_64:
- The 3 KB #5762 URL gives
-46on a blank context and a match on the shared one, so the autest's change to expecting a 301 is correct. - The 256 KiB subject still gives
-46on the 1 MiB stack.
- The 3 KB #5762 URL gives
Non-blocking: handle allocation failure in RegexContext
Regex.cc:127can crash. It callspcre2_match_context_copy(_match_context)without a null check, and the copy dereferences its argument. If thecreateat:124fails, the thread crashes on its first regex use, where before it just ran on PCRE2 defaults. Guard it withif (_match_context != nullptr).Regex.cc:113silently drops a requested limit. When_options_match_contextis null, the caller's limit is ignored. ESI's 1750 limit then quietly becomes PCRE2's 10M, whileIncludeUrlValidator.cc:318-320promises it fails closed. Consider returningPCRE2_ERROR_NOMEMORYfromexecwhenopts.match_limit != 0and the context is missing. ESI already treats any negative return as not allowlisted. Both failures need a ~100-byte malloc to fail, so this is hardening, not a practical bug.
Non-blocking: upgrading note for the removed API
tsutil/Regex.h is an installed header, and RegexMatchContext shipped in 10.2.0. Removing it breaks both source and ABI for any out-of-tree plugin that uses it. The Incompatible label is there. A short entry in doc/release-notes/upgrading.en.rst next to the ts::Metrics one would tell plugin authors what to change. For the same reason this shouldn't be backported to 10.x.
Non-blocking: widen the JIT-stack test's margin
On a blank context, ^(?:(a)|b)*$ first hits the stack limit at 819 characters. I measured that on both arm64 and x86_64 with PCRE2 10.47. At 1000 the test is only 1.22x past that point, so a different sljit frame size or PCRE2 version could let it pass without the fix. std::string(8000, 'a') is about 10x past the 32 KiB limit and still well under the 1 MiB one, which first fails around 26K.
Non-blocking: tighten the exhaustion assertion
In "reports resource exhaustion rather than crashing", REQUIRE(rc < 0) also accepts -1 (NOMATCH), which would be a wrong answer for a subject that should match. Under JIT the result is PCRE2_ERROR_JIT_STACKLIMIT (-46), so assert that exactly. A one-line comment on why nothing is asserted without JIT would help: the interpreter keeps its frames on the heap and just matches.
Non-blocking: the "every field is reapplied" comment
The comment at Regex.cc:104-109 is true only while Options has one field. The early return tests match_limit == 0, and only match_limit is written to the scratch context. So a future depth_limit set on its own would be ignored, and one left on the scratch context would carry into the next call on that thread. Adding bool operator==(Options const &) const = default; and early-returning on opts == Options{} makes the check cover new fields automatically. Alternatively, say in the comment that each new field has to be added in both places.
Nit: leftovers
- The no-argument
get_match_context()atRegex.cc:99has no callers now. - The new overload's doc copies the
ovector/ovecsizeparagraph, and neither parameter exists in this API. That's now three copies inRegex.h. A singleexec(..., uint32_t flags, Options const &opts = {})would leave one declaration and one doc block. match_context_test_tandmatch_context_test_dataintest_Regex.ccstill carry the old class's name.
e6b0d57 to
96d14df
Compare
96d14df to
e705ed0
Compare
|
Thanks @bryancall. Addressed the non-blocking points in e705ed0:
I kept the separate 3-argument overload instead of |
bryancall
left a comment
There was a problem hiding this comment.
✅ Approve
I reviewed e6b0d57b6..e705ed01a. Both revisions sit on the same base (493bc01d1), so git range-diff pairs the one commit and the delta is 5 files, +50/-26: Regex.cc, Regex.h, test_Regex.cc, the regex_remap autest comment and upgrading.en.rst. I built e705ed01a with gcc 16.2.1 and ASAN on Fedora 44 x86_64 (PCRE2 10.47) and ran the Regex unit tests, the ESI unit tests and the regex_remap, ESI, regex_revalidate and header_rewrite autests. Three mutations of Regex.cc show the tests notice the changed behavior. Every point from my last review is addressed, and both Copilot threads are fixed and resolved.
Fixed: allocation failure in RegexContext
The constructor now skips the JIT stack assign and the copy when the create fails (Regex.cc:128-131), and a non-default Options with no context returns PCRE2_ERROR_NOMEMORY (Regex.cc:445-450). ESI treats any negative return as not allowlisted, so it fails closed. I forced _options_match_context to null and the limited calls returned -48, not a match without the limit. No test covers that branch on its own, and one can't without an allocator seam, which is fine for three lines.
Fixed: upgrading note
It names the removal, shows the replacement and says plugins need a rebuild. Two wording points are in the nit below.
Fixed: JIT-stack test margin and the exhaustion assertion
At 8000 characters (test_Regex.cc:999) the test sits about 10x past the blank-context failure point and about 3x under the 1 MiB one. rc == PCRE2_ERROR_JIT_STACKLIMIT (:1030) holds exactly on this build.
Fixed: future Options fields
The defaulted operator== and the opts != Options{} gate do what I asked. See the non-blocking note below for the one gap left.
Agreed: keeping the 3-argument overload
You're right about CWG 1397. Options const &opts = {} inside Regex fails on both clang and gcc 16 with -std=c++20. The leftovers are gone: the no-argument get_match_context() is used again, the ovector paragraphs are removed and the test data is renamed.
Verified by running it
test_tsutil "[Regex]": 411 assertions in 22 test cases pass (binary51c2ac21d35a2651).test_include_url_validator_esi: 7 of 7 pass.- Options context created blank (
pcre2_match_context_createinstead of the copy): fails attest_Regex.cc:1007withopts_rc := -46. - Options context forced to null: fails at
:973(-48 == 1),:985and:1007(opts_rc := -48). - Gate removed, so default calls also go through the copy: 54 assertions fail, for example
:886with-47 == 4. - After restoring the file, the source is byte identical, the binary hash is back to
51c2ac21d35a2651and all 22 cases pass. - Autests: regex_remap, regex_remap_long_query, esi, esi_ssrf_validate, esi_nested_include, regex_revalidate, regex_revalidate_miss, header_rewrite_bundle and header_rewrite_url_glob pass. Some runs had
traffic_serverexit 1 on LeakSanitizer reports fromConfigReloadTask::start_progress_checker()and header_rewrite'srun-pluginoperator. Those stacks have no Regex frames, and the tests pass withdetect_leaks=0. cache_promote was skipped because go-httpbin isn't installed.
Non-blocking: a zero field reaches PCRE2 as a real limit
Regex.h:109 says a zero field means "use the shared default". But get_match_context(opts) passes match_limit straight to pcre2_set_match_limit (Regex.cc:118), and in PCRE2 zero is a real limit, not a default. Removing the gate shows what that does: every match returns -47. That can't happen today, because with one field, non-default means match_limit != 0. The comment at Regex.cc:107-108 tells the next author to apply every field on every call, though, and once a second field exists, setting only that field will call pcre2_set_match_limit(ctx, 0). Map zero to the shared value, for example from pcre2_config(PCRE2_CONFIG_MATCHLIMIT, ...), or say in that comment that a zero field must restore the default.
Nit: upgrading note placement and wording
- The entry at
upgrading.en.rst:48-61sits between the two Metrics paragraphs. The paragraph at:63, "Metrics::Storage::createSpan()andMetrics::rename()are also removed", now reads as following the Regex change. Moving the Regex entry below it keeps the Metrics entry in one piece. - "Plugins that call
Regex::execwith a flags argument" (:59-61) is broader than the break.bool exec(subject, flags)(Regex.h:185) keeps its symbol. Onlyexec(subject, matches, flags)resolved to the removed default-argument overload. - The doc for the
Optionsoverload (Regex.h:208-218) could mention the newPCRE2_ERROR_NOMEMORYreturn, since callers can see it.
e705ed0 to
9169ed6
Compare
bryancall
left a comment
There was a problem hiding this comment.
❌ Request changes
The library change is the same one I approved last round, and the rebase onto RE_FULL_MATCH came out right: both exec paths enforce full-match and the Options path still fails closed. The regex_remap test port to pytest checks the same things the autest did.
Blocking: tools/benchmark/benchmark_Regex.cc no longer compiles
#13670 landed after the last round and added "Regex match with a caller supplied context" (benchmark_Regex.cc:563-592), which still uses RegexMatchContext and exec(..., 0, nullptr) / exec(..., 0, &context). With this PR's Regex.h that fails with unknown type name 'RegexMatchContext' at :567 and no matching exec at :574 and :584. CI doesn't build it because ENABLE_BENCHMARKS is off. Converting the case to compare exec(s, m, 0) with exec(s, m, 0, opts) using a non-zero match_limit, or dropping it, would fix it.
Nit: stale comment in regex_remap
regex_remap.cc:118 still says "the match context and profiling hit counts are passed in as arguments". Only the hit counts are now.
Non-blocking: still open from last round
The zero-field note on Options, the upgrading-note placement and wording, and mentioning PCRE2_ERROR_NOMEMORY in the overload doc are still as they were. None of them blocks.
|
[approve ci urtest clang-tidy] |
|
[approve ci urtest 1] |
RegexMatchContext required callers to own a heap-allocated PCRE2 context just to set a match limit, lost the shared JIT stack, and had unsafe copy and move behavior. This patch replaces it with a value type whose defaults use the shared context and whose overrides use a per-thread copy. This preserves shared configuration, removes the no-op allocator, and updates plugin and benchmark callers and compatibility notes. The Uranium regex_remap test now expects the intended redirect for its 3 KB URL. Unit coverage preserves the exhaustion regression and checks that options do not leak between calls or lose the shared JIT stack. Fixes: apache#13663 Co-authored-by: GPT-6 Astra Medium Co-Authored-By: Claude Opus 5.5 <[email protected]>
9169ed6 to
2c96b9a
Compare
|
Thanks @bryancall. Rebased on master and addressed everything in 2c96b9a: Blocking, Nit, Zero upgrading.en.rst: moved the Regex entry below the "
Tested locally: |
bryancall
left a comment
There was a problem hiding this comment.
✅ Approve
I compared 9169ed6d2 with 2c96b9a5c using git range-diff across your rebase. Apart from the rebase, the changes are the benchmark port, the zero limit mapping, and the comment and doc fixes. I built the head on Fedora 44 with ASAN and benchmarks enabled.
Fixed: benchmark_Regex.cc builds
With benchmarks enabled, 9169ed6d2 fails at benchmark_Regex.cc:567 ('RegexMatchContext' was not declared in this scope), and 2c96b9a5c builds and passes. The new case compares exec(s, m, 0) with exec(s, m, 0, opts), which is what I asked for. On a release build both take about 25 ns a call, and the default path runs at the same speed as on master. On master the caller supplied context was about 12% slower than the shared one (27.0 against 24.0 ns), so a match limit now costs nothing measurable.
Fixed: the earlier notes
- A zero
match_limitnow maps to PCRE2's built-in limit (Regex.cc:119,Regex.cc:133). That is the shared context's limit, since nothing changes it. - The
regex_remap.cc:118comment, the upgrading note's placement and wording, and thePCRE2_ERROR_NOMEMORYline inRegex.h:289are all done.
Verified by running it
test_tsutil "[Regex]"passes 583 assertions in 33 test cases under ASAN, and all 1187 ctest tests pass, the ESI ones included.- Uranium with CI's
ci-fedora-urtestbuild in its fedora:44 image: the regex_remap, esi, regex_revalidate and header_rewrite tests, 28 of 28, pass. - The same 28 pass with ASAN, with no memory errors and no leaks that master doesn't have.
Nit: two comments
benchmark_Regex.cc:572says that withPATTERN_PATHbroken the options path measures about half the default one. With an empty pattern I get 15.7 ns against 15.5 ns, so I'd drop that clause.- The comment at
test_Regex.cc:1013names #5762 and the old PCRE1 crash, andtest_regex_remap.py:169says "historical". The new comment rules inAGENTS.mdkeep issue numbers and history in the commit message instead.
Master replaced RegexMatchContext with Regex::Options in apache#13748, which gives every thread its own match contexts and JIT stack. That leaves no match context shared between threads, so the JIT stack callback and the pthread key that served it have nothing to do. Regex.h and Regex.cc take master's version. In test_Regex.cc the RegexMatchContext cases go with the type. Master's "Regex::Options keeps the shared JIT stack" covers what the first of them checked. Both sides added a "Regex reports resource exhaustion rather than crashing" case; the one kept gates on JIT code for the pattern rather than PCRE2_CONFIG_JIT and takes master's exact PCRE2_ERROR_JIT_STACKLIMIT expectation. The concurrency case now sends half its threads through non-default options instead of a caller-supplied context. The regex_remap Uranium test keeps master's Ruff formatting and its shutdown log check, which now also allows the resource error the JIT stack exhaustion request produces.
Cover the per-thread match contexts from #13748: eight threads share one Regex and check captures, misses, per-thread match limits and deep subjects that only match on the 1MiB JIT stack. The JIT stack exhaustion case now runs only when pcre2_jit_compile() yields JIT code, so hosts that refuse executable memory skip it instead of failing. traffic_layout info reports TS_HAS_PCRE2_JIT, and a regex_remap Uranium test checks that an exhausted JIT stack falls through to the origin.


RegexMatchContext made every caller own a heap-allocated PCRE2 match
context just to set a match limit. Its constructor started from a
blank context rather than the shared one, so callers silently lost
the shared 1 MiB JIT stack, and its hand-rolled copy and defaulted
move members carried a latent null copy and double free. Passing a
null context meant "use the shared one," while the shared general
context wrapped malloc and free in a no-op allocator whose null would
have meant the same thing.
This patch replaces the type with Regex::Options, a plain value whose
zero fields mean the shared default. Regex now owns the only match
contexts: a default Options matches through the shared context, and a
non-default one is applied to a per-thread copy of it, so the JIT
stack and any future shared configuration carry over. The no-op
allocator is removed. The esi URL validator now passes its match
limit as Options, and regex_remap, which no longer set one, simply
uses the shared context.
Because regex_remap now gets the 1 MiB JIT stack, its 3 KB URL test
case redirects as the rule is written. The autest now expects that
redirect, and the #5762 crash property moves to a unit test that
asserts exhaustion is reported as an error. New unit tests also
cover that Options do not leak between calls and keep the shared
JIT stack. The upgrading notes describe the removal, which breaks
source and binary compatibility for plugins that use the old type
or call Regex::exec with flags.
Fixes: #13663
Co-authored-by: Claude Opus 5.5 Medium
Related: #13660, #13683. This overlaps #13683, which fixes the same JIT stack loss while keeping RegexMatchContext; whichever lands second will need a rebase.
🤖 Generated with Claude Code