You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@trafficserver.apache.org by "bryancall (via GitHub)" <gi...@apache.org> on 2026/09/09 22:57:20 UTC

[PR] Inherit the shared match context configuration in RegexMatchContext [trafficserver]

bryancall opened a new pull request, #13661:
URL: https://github.com/apache/trafficserver/pull/13661

   `RegexMatchContext` builds an empty PCRE2 match context, so a caller that supplies
   its own context silently loses everything the shared context configures. Today that
   is a 1 MB JIT stack, replaced by PCRE2's 32 KB fallback. `regex_remap` and `esi` are
   the only two users of the type, and both ran on the fallback.
   
   Nobody chose 32 KB. It is what PCRE2 uses when no stack is assigned, and it arrived
   by omission when the type was introduced in #12575.
   
   This builds the context as a copy of the shared one instead, so a caller cannot
   silently lack what the shared context has, and anything added to the shared context
   later applies automatically. The shared context now resolves its JIT stack through a
   callback rather than assigning one directly, because PCRE2 requires a distinct stack
   per thread and a copied context can be used on another thread. There is no change to
   `regex_remap.cc`; the plugin keeps its context and the context now starts correct.
   
   Issue: https://github.com/apache/trafficserver/issues/13660
   
   ## What this changes in behaviour
   
   Measured with `pcre2test` 10.47 against the rule and the 3071 byte URL already in
   `replay/yts-2819.replay.json`:
   
   ```
   ~^/alpha/bravo/[?]((?!action=(newsfeed|calendar|contacts|notepad)).)*$~
     jitstack=32     Failed: error -46: JIT stack limit reached
     jitstack=1024   matches
   ```
   
   That URL now redirects rather than falling through to origin, which is what the rule
   always intended. The first `-46` threshold for this rule moves from 1377 bytes to
   43702 bytes.
   
   The default 32 KB fallback lives on the machine stack. An assigned stack is heap
   allocated. So this reduces thread stack pressure rather than raising it, which is
   worth stating because the limit this rule has been hitting since 2019 traces back to
   #5762, where the concern was machine stack exhaustion.
   
   ## The #5762 crash guard is preserved, not removed
   
   The AuTest run that guards #5762 previously used the 3071 byte URL. Since that URL
   now matches, the run would no longer have exercised a resource limit. Rather than
   drop the guard, the run keeps its shape at a subject large enough to still exhaust
   1 MB, and the request header limit is raised for it. Verified in the sandbox:
   
   ```
   Bad regular expression result -46 ("JIT stack limit reached") from "^/alpha/bravo/..."
   Bad regular expression result -47 ("match limit exceeded") from "^/match_limit/(a+)+$"
   ```
   
   Two unit tests are added in `test_Regex.cc`: one asserting a caller-supplied context
   reaches the same verdict as the shared one, and one asserting that resource
   exhaustion is reported rather than crashing. The second is a direct assertion of the
   property #5762 was protecting, which the AuTest can only reach indirectly.
   
   ## Testing
   
   On a dev-asan build:
   
   - `test_tsutil` full suite: all pass. `[libts][Regex]` is 386 assertions in 20 cases.
   - Full `ctest` suite: 134 of 134 pass. This touches shared `tsutil` code, so the whole
     suite is the relevant blast radius rather than the Regex tests alone.
   - `regex_remap` and `regex_remap_long_query` AuTests pass.
   
   ## A pre-existing AuTest flake, not introduced here
   
   The `regex_remap` AuTest is nondeterministic on master today. LeakSanitizer reports a
   104 byte leak from `ConfigReloadTask::start_progress_checker()` at
   `src/mgmt/config/ConfigReloadTrace.cc:394`, which fails the `traffic_server` process
   exit code. It has nothing to do with regex matching. Five runs of each, same machine,
   same build settings:
   
   | revision | pass | fail |
   |---|---|---|
   | unmodified master 7ed34a3d3c | 1 | 4 |
   | this branch | 3 | 2 |
   
   Five runs each is too small to claim this branch is better; the point is only that
   the flake is present without it. Filed separately.
   
   ## Out of scope
   
   Whether `regex_remap` should carry a CPU bound at all, and what it should be, is a
   separate question from whether a caller-supplied context should silently differ from
   the shared one. Related: https://github.com/apache/trafficserver/issues/13654
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@trafficserver.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Inherit the shared match context configuration in RegexMatchContext [trafficserver]

Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #13661:
URL: https://github.com/apache/trafficserver/pull/13661#discussion_r3983985498


##########
src/tsutil/Regex.cc:
##########
@@ -79,6 +80,46 @@ my_free(void *ptr, void * /*caller*/)
   free(ptr);
 }
 
+//----------------------------------------------------------------------------
+// One match context is shared by every thread that matches through it, and PCRE2
+// requires a distinct JIT stack per thread, so the stack comes from a callback
+// invoked at match time rather than a pointer baked in when the context is built.
+//
+// The per thread stack is held in a pthread key rather than a thread_local. A
+// thread_local with a destructor registers it through __cxa_thread_atexit, which
+// takes the dynamic loader lock; doing that from a match would invert lock order
+// against a dlopen caller running a plugin's static initialization. See the same
+// hazard described at Diags::tag_activated. A pthread key registers its destructor
+// once, at key creation, and never from the matching path.
+pthread_key_t  jit_stack_key;
+pthread_once_t jit_stack_key_once = PTHREAD_ONCE_INIT;
+
+void
+destroy_jit_stack(void *stack)
+{
+  if (stack != nullptr) {
+    pcre2_jit_stack_free(static_cast<pcre2_jit_stack *>(stack));
+  }
+}
+
+void
+make_jit_stack_key()
+{
+  pthread_key_create(&jit_stack_key, destroy_jit_stack);

Review Comment:
   `pthread_key_create` can fail (for example with `EAGAIN` or `ENOMEM`), but this return value is ignored. `pthread_once` will still mark the initializer complete while `jit_stack_key` remains invalid/default-initialized, so the following `pthread_getspecific`/`pthread_setspecific` calls can use an invalid or unrelated key and return an unrelated pointer as a JIT stack. Check the creation result and make the callback handle key-initialization failure before using the key.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@trafficserver.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Inherit the shared match context configuration in RegexMatchContext [trafficserver]

Posted by "bryancall (via GitHub)" <gi...@apache.org>.
bryancall commented on code in PR #13661:
URL: https://github.com/apache/trafficserver/pull/13661#discussion_r3983498957


##########
src/tsutil/unit_tests/test_Regex.cc:
##########
@@ -1050,3 +1050,90 @@ TEST_CASE("Regex end-anchor with alternation", "[libts][Regex]")
   CHECK(r.exec("cdn.example.com.evil.com", matches) == RE_ERROR_NOMATCH);
   CHECK(r.exec("prefix.cdn.example.com", matches) == RE_ERROR_NOMATCH);
 }
+
+namespace
+{
+/** Does PCRE2 have JIT code for this pattern?
+ *
+ * The two tests below are about the JIT stack, and PCRE2 consults it only when it
+ * has JIT code to run. Without it both a blank context and the shared one take the
+ * interpreter and return the same answer, so the tests would pass whether or not
+ * the behaviour they describe is present. Ask PCRE2 rather than assume.
+ */
+bool
+pattern_has_jit(char const *pattern)
+{
+  int         errnum    = 0;
+  PCRE2_SIZE  erroffset = 0;
+  pcre2_code *code = pcre2_compile(reinterpret_cast<PCRE2_SPTR>(pattern), PCRE2_ZERO_TERMINATED, 0, &errnum, &erroffset, nullptr);
+  if (code == nullptr) {
+    return false;
+  }
+  pcre2_jit_compile(code, PCRE2_JIT_COMPLETE);
+  size_t jit_size = 0;
+  pcre2_pattern_info(code, PCRE2_INFO_JITSIZE, &jit_size);
+  pcre2_code_free(code);
+  return jit_size > 0;
+}
+} // namespace
+
+// A caller-supplied RegexMatchContext must behave like the shared context that
+// Regex::exec uses when none is supplied. A context built from scratch silently
+// drops everything the shared one configures, which is how regex_remap came to
+// run with PCRE2's fallback 32KiB JIT stack instead of the 1MiB one.
+TEST_CASE("RegexMatchContext matches the shared context", "[libts][Regex][RegexMatchContext]")
+{
+  // Quantified alternation of capture groups: every subject character pushes a
+  // backtracking frame, so the JIT stack size is what bounds this.
+  char const *const pattern = R"(^(?:(a)|(b))+$)";
+  if (!pattern_has_jit(pattern)) {
+    SKIP("PCRE2 has no JIT for this pattern, so the JIT stack is never consulted");
+  }
+
+  Regex re;
+  REQUIRE(re.compile(pattern));
+
+  std::string const subject(1000, 'a');
+
+  RegexMatches      shared_matches;
+  RegexMatchContext match_context;
+  RegexMatches      own_matches;
+
+  int const shared_rc = re.exec(subject, shared_matches);
+  int const own_rc    = re.exec(subject, own_matches, 0, &match_context);
+  CAPTURE(shared_rc, own_rc);
+
+  REQUIRE(shared_rc > 0);
+  REQUIRE(own_rc == shared_rc);
+}
+
+// The guard from #5762: a pattern that backtracks once per character must fail
+// cleanly rather than run the thread out of stack. PCRE1 recursed on the machine
+// stack and a long enough subject crashed the server; PCRE2 must report an error
+// instead. If this ever crashes rather than fails, that regression is back.
+TEST_CASE("Regex reports resource exhaustion rather than crashing", "[libts][Regex][limits]")
+{
+  // Only the JIT path has a bound to exhaust here. PCRE2's interpreter keeps its
+  // backtracking frames on the heap, so it matches this subject rather than running
+  // out of anything, and there is no resource error to assert.
+  char const *const pattern = R"(^/alpha/bravo/[?]((?!action=(newsfeed|calendar|contacts|notepad)).)*$)";
+  if (!pattern_has_jit(pattern)) {
+    SKIP("PCRE2 has no JIT for this pattern, so there is no stack bound to exhaust");
+  }
+
+  Regex re;
+  REQUIRE(re.compile(pattern));
+
+  // Past what a 1MiB JIT stack holds for this pattern, which starts failing at
+  // roughly 43KiB of subject, so the bound is still exercised.
+  std::string subject{"/alpha/bravo/?"};
+  subject.append(2 * 1024 * 1024, 'x');
+

Review Comment:
   Done in db72f15ace, sized to 256KiB.
   
   One correction to the reasoning, since the outcome is right but the stated cost is not
   what I measured. The match time does not scale with the subject here: it bails at the
   JIT stack limit long before traversing it. Measured against libpcre2 10.47:
   
   ```
        65536 bytes ( 1.5x threshold) -> rc=-46    0.172 ms
       131072 bytes ( 3.0x threshold) -> rc=-46    0.138 ms
       262144 bytes ( 6.0x threshold) -> rc=-46    0.136 ms
      2097152 bytes (48.0x threshold) -> rc=-46    0.148 ms
   ```
   
   So this was not slower and had no timing sensitivity to remove. What it did have was a
   48 times oversized allocation for no added coverage, which is worth fixing on its own.
   
   I chose 256KiB rather than something nearer the threshold to keep a six times margin.
   The 43KiB figure is measured, and it came out identical on x86_64 and arm64, but a
   platform with larger JIT frames would push it up, and a test that stops exercising the
   bound would pass silently rather than fail. The margin and that reasoning are now in a
   comment above the line so it does not get trimmed later.
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@trafficserver.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Inherit the shared match context configuration in RegexMatchContext [trafficserver]

Posted by "bryancall (via GitHub)" <gi...@apache.org>.
bryancall commented on PR #13661:
URL: https://github.com/apache/trafficserver/pull/13661#issuecomment-5648166444

   Superseded by #13671, which carries both commits from this PR as its first two, plus two
   more defects in the same file.
   
   Closing rather than updating for one reason. This PR bundled two backportable fixes (the
   shared-context constructor and the pthread-key JIT stack) with a source-breaking change
   (deleting `RegexMatchContext`'s copy and move members). Since a merged PR becomes a single
   squashed commit, that mix would have kept the backportable half off 10.2.x and 10.1.x: a
   release manager cherry-picking it would have taken the source break along with it. #13671
   is purely behavioural with no change to the public API surface, so it carries a Backport
   label and can travel as a unit.
   
   The member deletion is not lost, it is deferred to #13663, where `RegexMatchContext` is
   replaced by a value type and the question of deleting its members stops being a source
   break in isolation.
   
   Two things from the review here that carried over to #13671:
   
   - **The `pthread_key_create` failure path.** Your point stands and the handling added in
     `fff1a840a2` is in #13671 unchanged, along with the additional case where
     `pthread_setspecific` fails, which would otherwise have leaked a stack per match.
   - **The `thread_local` hazard was only half addressed here.** This PR moved the JIT stack
     to a pthread key, but the general, compile and match contexts were themselves in a
     `thread_local` with a destructor, so the first `compile()` or `exec()` on a thread still
     registered through `__cxa_thread_atexit` and still took the loader lock. #13671 makes
     those contexts process-wide, which is what actually closes it. The sentence in this PR's
     description claiming the hazard is gone was overstated, and that correction is the reason
     the follow-up exists.
   
   #13671 also adds the eight-thread concurrency test this file never had, and is clean under
   both ThreadSanitizer and AddressSanitizer.
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@trafficserver.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Inherit the shared match context configuration in RegexMatchContext [trafficserver]

Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #13661:
URL: https://github.com/apache/trafficserver/pull/13661#discussion_r3983934830


##########
src/tsutil/Regex.cc:
##########
@@ -499,6 +514,8 @@ Regex::exec(std::string_view subject, RegexMatches &matches, uint32_t flags, Reg
   bool const     full_match  = (flags & RE_FULL_MATCH) != 0;
   uint32_t const pcre2_flags = flags & ~RE_FULL_MATCH;
 
+  arm_jit_stack_cleanup();

Review Comment:
   `arm_jit_stack_cleanup()` still initializes a TLS object with a non-trivial destructor, which registers it through `__cxa_thread_atexit` and can take the loader lock. This call is unconditional and now also runs for caller-supplied contexts; moving it before `pcre2_match` only avoids initialization from PCRE2's callback, not the case where `Regex::exec()` itself is entered while a plugin is under the loader lock. The existing `src/tscore/Diags.cc:339-346` comment documents this lock-order hazard for `Regex::exec`; use a cleanup mechanism whose first-use path does not register a C++ TLS destructor, or otherwise initialize it before loader-sensitive code.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@trafficserver.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Inherit the shared match context configuration in RegexMatchContext [trafficserver]

Posted by "bryancall (via GitHub)" <gi...@apache.org>.
bryancall commented on PR #13661:
URL: https://github.com/apache/trafficserver/pull/13661#issuecomment-5610616587

   [approve ci autest 0]


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@trafficserver.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Inherit the shared match context configuration in RegexMatchContext [trafficserver]

Posted by "bryancall (via GitHub)" <gi...@apache.org>.
bryancall closed pull request #13661: Inherit the shared match context configuration in RegexMatchContext
URL: https://github.com/apache/trafficserver/pull/13661


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@trafficserver.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Inherit the shared match context configuration in RegexMatchContext [trafficserver]

Posted by "bryancall (via GitHub)" <gi...@apache.org>.
bryancall commented on code in PR #13661:
URL: https://github.com/apache/trafficserver/pull/13661#discussion_r3983952779


##########
src/tsutil/Regex.cc:
##########
@@ -499,6 +514,8 @@ Regex::exec(std::string_view subject, RegexMatches &matches, uint32_t flags, Reg
   bool const     full_match  = (flags & RE_FULL_MATCH) != 0;
   uint32_t const pcre2_flags = flags & ~RE_FULL_MATCH;
 
+  arm_jit_stack_cleanup();

Review Comment:
   Good catch, and the citation checks out. `Diags::tag_activated` documents exactly this
   hazard and works around it:
   
   > exec() can lazily construct a thread_local RegexContext whose destructor registration
   > via __cxa_thread_atexit_impl takes the dynamic loader lock. Holding tag_table_lock
   > across exec() therefore creates a lock-order inversion with dlopen() callers that
   > construct a DbgCtl during a plugin's static initialization.
   
   You are right that arming before the match only moved the registration out of PCRE2's
   callback and left it on `exec`. Worse, it put it on the caller-supplied context path,
   which previously never touched a thread local with a destructor at all, so this change
   was extending the hazard rather than containing it.
   
   Fixed in 143e53238f by taking the C++ thread local out entirely. The per thread stack now
   lives in a `pthread_key_t`, whose destructor is registered once at key creation through
   `pthread_once` and never from the matching path.
   
   That also deletes the arming function, its call in `exec`, and both thread locals, so the
   deadlock and leak trade this had been balancing goes away instead: 24 insertions against
   27 deletions.
   
   Verified on a dev-asan build: unit suite 134 of 134, the regex_remap AuTest passes with
   the 3KB URL returning 301 and one -46 plus one -47 in the diags log, and LeakSanitizer
   reports no `jit_stack_for_this_thread` allocation, so the key's destructor is running.
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@trafficserver.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Inherit the shared match context configuration in RegexMatchContext [trafficserver]

Posted by "bryancall (via GitHub)" <gi...@apache.org>.
bryancall commented on PR #13661:
URL: https://github.com/apache/trafficserver/pull/13661#issuecomment-5624269218

   [approve ci clang-analyzer freebsd autest 1 autest 2]


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@trafficserver.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Inherit the shared match context configuration in RegexMatchContext [trafficserver]

Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #13661:
URL: https://github.com/apache/trafficserver/pull/13661#discussion_r3983479962


##########
src/tsutil/unit_tests/test_Regex.cc:
##########
@@ -1050,3 +1050,90 @@ TEST_CASE("Regex end-anchor with alternation", "[libts][Regex]")
   CHECK(r.exec("cdn.example.com.evil.com", matches) == RE_ERROR_NOMATCH);
   CHECK(r.exec("prefix.cdn.example.com", matches) == RE_ERROR_NOMATCH);
 }
+
+namespace
+{
+/** Does PCRE2 have JIT code for this pattern?
+ *
+ * The two tests below are about the JIT stack, and PCRE2 consults it only when it
+ * has JIT code to run. Without it both a blank context and the shared one take the
+ * interpreter and return the same answer, so the tests would pass whether or not
+ * the behaviour they describe is present. Ask PCRE2 rather than assume.
+ */
+bool
+pattern_has_jit(char const *pattern)
+{
+  int         errnum    = 0;
+  PCRE2_SIZE  erroffset = 0;
+  pcre2_code *code = pcre2_compile(reinterpret_cast<PCRE2_SPTR>(pattern), PCRE2_ZERO_TERMINATED, 0, &errnum, &erroffset, nullptr);
+  if (code == nullptr) {
+    return false;
+  }
+  pcre2_jit_compile(code, PCRE2_JIT_COMPLETE);
+  size_t jit_size = 0;
+  pcre2_pattern_info(code, PCRE2_INFO_JITSIZE, &jit_size);
+  pcre2_code_free(code);
+  return jit_size > 0;
+}
+} // namespace
+
+// A caller-supplied RegexMatchContext must behave like the shared context that
+// Regex::exec uses when none is supplied. A context built from scratch silently
+// drops everything the shared one configures, which is how regex_remap came to
+// run with PCRE2's fallback 32KiB JIT stack instead of the 1MiB one.
+TEST_CASE("RegexMatchContext matches the shared context", "[libts][Regex][RegexMatchContext]")
+{
+  // Quantified alternation of capture groups: every subject character pushes a
+  // backtracking frame, so the JIT stack size is what bounds this.
+  char const *const pattern = R"(^(?:(a)|(b))+$)";
+  if (!pattern_has_jit(pattern)) {
+    SKIP("PCRE2 has no JIT for this pattern, so the JIT stack is never consulted");
+  }
+
+  Regex re;
+  REQUIRE(re.compile(pattern));
+
+  std::string const subject(1000, 'a');
+
+  RegexMatches      shared_matches;
+  RegexMatchContext match_context;
+  RegexMatches      own_matches;
+
+  int const shared_rc = re.exec(subject, shared_matches);
+  int const own_rc    = re.exec(subject, own_matches, 0, &match_context);
+  CAPTURE(shared_rc, own_rc);
+
+  REQUIRE(shared_rc > 0);
+  REQUIRE(own_rc == shared_rc);
+}
+
+// The guard from #5762: a pattern that backtracks once per character must fail
+// cleanly rather than run the thread out of stack. PCRE1 recursed on the machine
+// stack and a long enough subject crashed the server; PCRE2 must report an error
+// instead. If this ever crashes rather than fails, that regression is back.
+TEST_CASE("Regex reports resource exhaustion rather than crashing", "[libts][Regex][limits]")
+{
+  // Only the JIT path has a bound to exhaust here. PCRE2's interpreter keeps its
+  // backtracking frames on the heap, so it matches this subject rather than running
+  // out of anything, and there is no resource error to assert.
+  char const *const pattern = R"(^/alpha/bravo/[?]((?!action=(newsfeed|calendar|contacts|notepad)).)*$)";
+  if (!pattern_has_jit(pattern)) {
+    SKIP("PCRE2 has no JIT for this pattern, so there is no stack bound to exhaust");
+  }
+
+  Regex re;
+  REQUIRE(re.compile(pattern));
+
+  // Past what a 1MiB JIT stack holds for this pattern, which starts failing at
+  // roughly 43KiB of subject, so the bound is still exercised.
+  std::string subject{"/alpha/bravo/?"};
+  subject.append(2 * 1024 * 1024, 'x');
+

Review Comment:
   The resource-exhaustion unit test appends a 2 MiB subject even though the comment notes this pattern starts failing around ~43 KiB. Using a multi-megabyte subject can make the unit test suite slower than necessary (and may add flakiness on slower/contended CI hosts) without increasing coverage once the JIT stack limit is reached.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@trafficserver.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Inherit the shared match context configuration in RegexMatchContext [trafficserver]

Posted by "bryancall (via GitHub)" <gi...@apache.org>.
bryancall commented on code in PR #13661:
URL: https://github.com/apache/trafficserver/pull/13661#discussion_r3984320063


##########
src/tsutil/Regex.cc:
##########
@@ -79,6 +80,46 @@ my_free(void *ptr, void * /*caller*/)
   free(ptr);
 }
 
+//----------------------------------------------------------------------------
+// One match context is shared by every thread that matches through it, and PCRE2
+// requires a distinct JIT stack per thread, so the stack comes from a callback
+// invoked at match time rather than a pointer baked in when the context is built.
+//
+// The per thread stack is held in a pthread key rather than a thread_local. A
+// thread_local with a destructor registers it through __cxa_thread_atexit, which
+// takes the dynamic loader lock; doing that from a match would invert lock order
+// against a dlopen caller running a plugin's static initialization. See the same
+// hazard described at Diags::tag_activated. A pthread key registers its destructor
+// once, at key creation, and never from the matching path.
+pthread_key_t  jit_stack_key;
+pthread_once_t jit_stack_key_once = PTHREAD_ONCE_INIT;
+
+void
+destroy_jit_stack(void *stack)
+{
+  if (stack != nullptr) {
+    pcre2_jit_stack_free(static_cast<pcre2_jit_stack *>(stack));
+  }
+}
+
+void
+make_jit_stack_key()
+{
+  pthread_key_create(&jit_stack_key, destroy_jit_stack);

Review Comment:
   Valid, fixed in fff1a840a2.
   
   The dangerous part is not that the stack would be missing, it is that `jit_stack_key` is
   a namespace scope `pthread_key_t` and therefore zero initialized. Key 0 can be a live key
   belonging to another subsystem, so a failed create would have had the callback return
   that key's value and hand it to PCRE2 as a JIT stack.
   
   The callback now records whether the key was created and returns null when it was not.
   `pcre2jit` documents a null return as thread safe, so the match falls back to PCRE2's own
   default stack: degraded, but correct, and the same behaviour this plugin had before the
   change.
   
   The write to that flag happens inside the `pthread_once` initializer, so it is ordered
   before every reader.
   
   Verified on a dev-asan build: unit suite 134 of 134, regex_remap AuTest passes with the
   3KB URL returning 301 and one -46 plus one -47, and no leaked JIT stack.
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@trafficserver.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org