Skip to content

Replace RegexMatchContext with Regex::Options - #13748

Merged
bneradt merged 1 commit into
apache:masterfrom
bneradt:regex-options-value-type
Nov 4, 2026
Merged

bneradt merged 1 commit into
apache:masterfrom
bneradt:regex-options-value-type

Conversation

@bneradt

@bneradt bneradt commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

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

Copilot AI balanced review requested due to automatic review settings September 29, 2026 20:19
@bneradt bneradt added this to the 11.0.0 milestone Sep 29, 2026
@bneradt bneradt self-assigned this Sep 29, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

bryancall
bryancall previously approved these changes Sep 30, 2026

@bryancall bryancall left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ 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 RegexMatchContext used to create it: "keeps the shared JIT stack" fails at test_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 :986 with -47 == 4.
  • Standalone PCRE2 check on arm64 and x86_64:
    • The 3 KB #5762 URL gives -46 on 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 -46 on the 1 MiB stack.

Non-blocking: handle allocation failure in RegexContext

  • Regex.cc:127 can crash. It calls pcre2_match_context_copy(_match_context) without a null check, and the copy dereferences its argument. If the create at :124 fails, the thread crashes on its first regex use, where before it just ran on PCRE2 defaults. Guard it with if (_match_context != nullptr).
  • Regex.cc:113 silently drops a requested limit. When _options_match_context is null, the caller's limit is ignored. ESI's 1750 limit then quietly becomes PCRE2's 10M, while IncludeUrlValidator.cc:318-320 promises it fails closed. Consider returning PCRE2_ERROR_NOMEMORY from exec when opts.match_limit != 0 and 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() at Regex.cc:99 has no callers now.
  • The new overload's doc copies the ovector / ovecsize paragraph, and neither parameter exists in this API. That's now three copies in Regex.h. A single exec(..., uint32_t flags, Options const &opts = {}) would leave one declaration and one doc block.
  • match_context_test_t and match_context_test_data in test_Regex.cc still carry the old class's name.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot review overview

🟡 Changes recommended

Match-context allocation failure silently disables the ESI backtracking limit.

Review effort: Balanced
Findings: 1 High severity · 1 Low severity

Open (2)

Comment thread src/tsutil/Regex.cc Resolved
Comment thread src/tsutil/unit_tests/test_Regex.cc Resolved
Copilot AI balanced review requested due to automatic review settings October 5, 2026 16:19
@bneradt
bneradt force-pushed the regex-options-value-type branch from e6b0d57 to 96d14df Compare October 5, 2026 16:19

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@bneradt
bneradt requested a review from bryancall October 5, 2026 16:20
@bneradt
bneradt force-pushed the regex-options-value-type branch from 96d14df to e705ed0 Compare October 5, 2026 18:20
Copilot AI balanced review requested due to automatic review settings October 5, 2026 18:20

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@bneradt

bneradt commented Oct 5, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @bryancall. Addressed the non-blocking points in e705ed0:

  • Allocation failure: the constructor guards the JIT stack assignment and the copy, and a non-default Options whose context could not be allocated returns PCRE2_ERROR_NOMEMORY, so ESI fails closed.
  • Upgrading note: added under "Upgrading to ATS v11.x", next to the ts::Metrics entry.
  • JIT-stack test margin: the subject is now 8000 characters.
  • Exhaustion assertion: now PCRE2_ERROR_JIT_STACKLIMIT exactly, with a comment on why nothing is asserted without JIT.
  • Future Options fields: Options has a defaulted operator==, the default check compares against Options{}, and the comment says each field must be applied on every call.
  • Leftovers: the no-argument get_match_context() is used again by the default path, the stale ovector paragraph is gone from all three exec docs, and the test data is renamed.

I kept the separate 3-argument overload instead of Options const &opts = {}. A default argument of a nested type with default member initializers hits CWG 1397 and fails to compile inside the enclosing class.

bryancall
bryancall previously approved these changes Oct 6, 2026

@bryancall bryancall left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ 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 (binary 51c2ac21d35a2651). test_include_url_validator_esi: 7 of 7 pass.
  • Options context created blank (pcre2_match_context_create instead of the copy): fails at test_Regex.cc:1007 with opts_rc := -46.
  • Options context forced to null: fails at :973 (-48 == 1), :985 and :1007 (opts_rc := -48).
  • Gate removed, so default calls also go through the copy: 54 assertions fail, for example :886 with -47 == 4.
  • After restoring the file, the source is byte identical, the binary hash is back to 51c2ac21d35a2651 and 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_server exit 1 on LeakSanitizer reports from ConfigReloadTask::start_progress_checker() and header_rewrite's run-plugin operator. Those stacks have no Regex frames, and the tests pass with detect_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-61 sits between the two Metrics paragraphs. The paragraph at :63, "Metrics::Storage::createSpan() and Metrics::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::exec with a flags argument" (:59-61) is broader than the break. bool exec(subject, flags) (Regex.h:185) keeps its symbol. Only exec(subject, matches, flags) resolved to the removed default-argument overload.
  • The doc for the Options overload (Regex.h:208-218) could mention the new PCRE2_ERROR_NOMEMORY return, since callers can see it.

@bneradt
bneradt force-pushed the regex-options-value-type branch from e705ed0 to 9169ed6 Compare October 26, 2026 20:51
Copilot AI balanced review requested due to automatic review settings October 26, 2026 20:51

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota.

@bryancall bryancall left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

❌ 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.

@bryancall

Copy link
Copy Markdown
Contributor

[approve ci urtest clang-tidy]

@bryancall

Copy link
Copy Markdown
Contributor

[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]>
@bneradt
bneradt force-pushed the regex-options-value-type branch from 9169ed6 to 2c96b9a Compare November 3, 2026 16:35
Copilot AI balanced review requested due to automatic review settings November 3, 2026 16:35
@bneradt

bneradt commented Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @bryancall. Rebased on master and addressed everything in 2c96b9a:

Blocking, benchmark_Regex.cc: the case is now "Regex match with caller supplied options" and compares exec(s, m, 0) with exec(s, m, 0, opts) where opts.match_limit = 100000. Both paths are still required to match before timing. Built with -DENABLE_BENCHMARKS=ON and ran it: the two come in at about 330 us each.

Nit, regex_remap.cc:118: the comment now says only the profiling hit counts are passed in as arguments.

Zero Options field: get_match_context(opts) now maps a zero match_limit to the shared value, which it reads once with pcre2_config(PCRE2_CONFIG_MATCHLIMIT, ...), so a zero field no longer reaches PCRE2 as a real limit of 0. The comment on that function now says each field must be reapplied on every call and a zero field restores the shared value.

upgrading.en.rst: moved the Regex entry below the "Metrics::Storage::createSpan() and Metrics::rename() are also removed" paragraph. The recompile sentence now names only Regex::exec(subject, matches, flags).

PCRE2_ERROR_NOMEMORY: the Options overload's @return now says it returns PCRE2_ERROR_NOMEMORY when opts is not the default and the match context could not be allocated.

Tested locally: test_tsutil "[Regex]" passes, the ESI unit tests (38) pass, and the regex_remap / esi / regex_revalidate / header_rewrite urtests (28) pass.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota.

@bneradt
bneradt requested a review from bryancall November 3, 2026 16:36

@bryancall bryancall left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ 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_limit now 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:118 comment, the upgrading note's placement and wording, and the PCRE2_ERROR_NOMEMORY line in Regex.h:289 are 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-urtest build 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:572 says that with PATTERN_PATH broken 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:1013 names #5762 and the old PCRE1 crash, and test_regex_remap.py:169 says "historical". The new comment rules in AGENTS.md keep issue numbers and history in the commit message instead.

@bneradt
bneradt merged commit 933d704 into apache:master Nov 4, 2026
14 checks passed
@bneradt
bneradt deleted the regex-options-value-type branch November 4, 2026 16:13
bryancall added a commit to bryancall/trafficserver that referenced this pull request Nov 11, 2026
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.
bryancall added a commit that referenced this pull request Nov 12, 2026
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Regex: replace RegexMatchContext with a value type; the current one has a latent double free

3 participants