bryancall commented on code in PR #13683:
URL: https://github.com/apache/trafficserver/pull/13683#discussion_r4532236716


##########
src/tsutil/unit_tests/test_Regex.cc:
##########
@@ -1646,3 +1651,358 @@ TEST_CASE("Regex copies answer the same as their 
original", "[libts][Regex][copy
     CHECK(original.exec(ordinary, original_ordinary) == copy.exec(ordinary, 
copy_ordinary));
   }
 }
+
+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.
+ *
+ * This asks about one pattern, deliberately: PCRE2 declines some pattern 
items and
+ * leaves PCRE2_INFO_JITSIZE at zero on a build whose JIT is otherwise fine, 
so the
+ * library-wide probes (pcre2_config, PCRE2_JIT_TEST_ALLOC) answer a different
+ * question. Call it from the test thread only; Catch2 assertions are not 
thread safe.
+ */
+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);
+
+  // A pattern that will not compile is a broken test, not a build without a 
JIT.
+  // Reporting it as "no JIT" would turn a typo into a silent skip.
+  REQUIRE(code != nullptr);
+
+  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 drops
+// everything the shared one configures, the JIT stack callback included, and a
+// match through it then runs on 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));
+
+  // 40 bytes of JIT stack per subject character, so PCRE2's 32KiB fallback 
stops at
+  // 818 characters and the shared context's 1MiB stack at 26,213. 5,000 sits 
six
+  // times above the first and five times below the second, so a blank context 
and
+  // the shared one give different answers with margin either way.
+  std::string const subject(5000, '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 copy paths must carry the inherited configuration too. Building a 
blank
+  // context in either of them is the same defect, and nothing else here 
notices.
+  RegexMatchContext const copied{match_context};
+  RegexMatchContext       assigned;
+
+  assigned = match_context;
+
+  RegexMatches copied_matches;
+  RegexMatches assigned_matches;
+
+  REQUIRE(re.exec(subject, copied_matches, 0, &copied) == shared_rc);
+  REQUIRE(re.exec(subject, assigned_matches, 0, &assigned) == shared_rc);
+}
+
+// Ownership only, and deliberately not inside the case above.
+//
+// That case SKIPs when pattern_has_jit() is false, which is right for what it 
tests and
+// wrong for this: move construction and move assignment have nothing to do 
with the JIT,
+// and a double free matters as much on a PCRE2 without JIT, or on a hardened 
runtime
+// where JIT allocation fails, as anywhere else. Inside that case this 
coverage would
+// skip on exactly those builds and still report green.
+TEST_CASE("RegexMatchContext move operations transfer ownership", 
"[libts][Regex][RegexMatchContext]")
+{
+  Regex re;
+
+  REQUIRE(re.compile("^(a+)(b+)$"));
+
+  std::string_view const subject{"aaabbb"};
+
+  auto matches_through = [&](RegexMatchContext const *ctx) {
+    RegexMatches m;
+    return re.exec(subject, m, 0, ctx);
+  };
+
+  // Baseline through a plain context, so a later mismatch means the move 
broke something
+  // rather than the pattern never having matched.
+  RegexMatchContext plain;
+  int const         expected = matches_through(&plain);
+
+  REQUIRE(expected > 0);
+
+  SECTION("move construction")
+  {
+    RegexMatchContext       donor;
+    RegexMatchContext const moved{std::move(donor)};
+
+    REQUIRE(matches_through(&moved) == expected);
+    // A double free aborts when donor and moved are both destroyed, so 
leaving this
+    // section is itself the second assertion.
+  }
+
+  SECTION("move assignment onto a destination that already holds a context")
+  {
+    // On an ordinary build the assertions below do not detect a dropped
+    // pcre2_match_context_free(old): removing that call leaves this section 
passing,
+    // because a leak has no observer here. The oracle for the leak is 
LeakSanitizer,
+    // which AddressSanitizer turns on by default on Linux but not on macOS.
+    //
+    // The section still earns its place: it is what gives LSan a move 
assignment onto a
+    // live context to observe, which no other case in this file produces. 
Without it
+    // the leak is unreachable and therefore undetectable anywhere.
+    RegexMatchContext destination;
+
+    REQUIRE(matches_through(&destination) == expected);
+
+    RegexMatchContext donor;
+
+    destination = std::move(donor);
+
+    REQUIRE(matches_through(&destination) == expected);
+  }
+
+  SECTION("self move assignment")
+  {
+    RegexMatchContext ctx;
+
+    // A match limit of one fails this match, so the result after the move 
shows whether
+    // ctx still holds its own context. Without the this != &that guard the 
operator frees
+    // the context and then nulls itself, and the match runs on PCRE2's 
defaults instead.
+    ctx.set_match_limit(1);
+    REQUIRE(matches_through(&ctx) == PCRE2_ERROR_MATCHLIMIT);
+
+    auto &alias = ctx;
+
+    ctx = std::move(alias);
+
+    REQUIRE(matches_through(&ctx) == PCRE2_ERROR_MATCHLIMIT);
+  }
+}
+
+// A pattern that backtracks once per character must fail cleanly rather than 
run
+// the thread out of stack. A regex engine that recurses on the machine stack 
crashes
+// the server on a long enough subject; PCRE2 must report an error instead.
+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));
+
+  // This pattern starts failing at roughly 43KiB of subject against a 1MiB JIT
+  // stack, measured identically on x86_64 and arm64. Smaller JIT frames get 
more
+  // subject out of the same stack and so push that threshold up; 256KiB keeps 
a
+  // six times margin against that. Do not trim this to just above 43KiB.
+  std::string subject{"/alpha/bravo/?"};
+  subject.append(256 * 1024, 'x');
+
+  RegexMatches matches;
+  int const    rc = re.exec(subject, matches);
+  CAPTURE(rc);
+
+  // Reaching this line at all is the crash assertion.
+  REQUIRE(rc < 0);
+  REQUIRE(rc != RE_ERROR_NOMATCH);
+
+  // The paired positive control, and the only part of this case that can tell 
a
+  // 1MiB stack from PCRE2's 32KiB fallback: 256KiB overruns both bounds, so 
every
+  // assertion above also holds with the JIT stack callback deleted. 10,000 is 
seven
+  // times over the fallback's bound and four times under the 1MiB stack's. 
Neither
+  // bound pins 1MiB itself; the suite only requires a maximum in roughly
+  // [240KB, 6MB].
+  std::string smaller{"/alpha/bravo/?"};
+  smaller.append(10000, 'x');
+
+  RegexMatches small_matches;
+  int const    small_rc = re.exec(smaller, small_matches);
+  CAPTURE(small_rc);
+
+  REQUIRE(small_rc > 0);
+}
+
+namespace
+{
+/** A reusable barrier, so every round starts with all threads alive and 
inside it. The
+ * matches of one round then start together on every thread. std::barrier 
would say this
+ * directly; it is hand-rolled here to match notstd::barrier in 
benchmark_LogObject.cc.

Review Comment:
   std::barrier is reusable from one phase to the next, so it's the right tool 
here. I switched to it in 4cadf1629693 and deleted the hand-rolled class:
   
https://github.com/apache/trafficserver/blob/f7ec6bc9058fcb051ddf0117ca10523a0fdc9d36/src/tsutil/unit_tests/test_Regex.cc#L1858
   
   The log benchmark's notstd::barrier came in with #9096 in September 2022, 
when the tree still built with -std=c++17, so std::barrier wasn't available to 
it:
   
https://github.com/apache/trafficserver/blob/6c600a3f6432864a0bec463de6183db32f887085/configure.ac#L677
   It's also one-shot, so it couldn't be reused here. Its count goes to zero 
once and never resets, and a second crossing leaves both threads blocked for 
good. std::barrier builds and runs with GCC 11 from the Rocky 8 CI image, GCC 
16, and Apple clang 21.
   
   The barrier does earn its place. I broke the code on purpose so every thread 
shares one JIT stack: the test failed 300 of 300 runs with the barrier and 276 
of 300 without it. Those numbers are in the 4cadf1629693 commit message.



##########
src/tsutil/unit_tests/test_Regex.cc:
##########
@@ -1646,3 +1651,358 @@ TEST_CASE("Regex copies answer the same as their 
original", "[libts][Regex][copy
     CHECK(original.exec(ordinary, original_ordinary) == copy.exec(ordinary, 
copy_ordinary));
   }
 }
+
+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.
+ *
+ * This asks about one pattern, deliberately: PCRE2 declines some pattern 
items and
+ * leaves PCRE2_INFO_JITSIZE at zero on a build whose JIT is otherwise fine, 
so the
+ * library-wide probes (pcre2_config, PCRE2_JIT_TEST_ALLOC) answer a different
+ * question. Call it from the test thread only; Catch2 assertions are not 
thread safe.
+ */
+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);
+
+  // A pattern that will not compile is a broken test, not a build without a 
JIT.
+  // Reporting it as "no JIT" would turn a typo into a silent skip.
+  REQUIRE(code != nullptr);
+
+  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 drops
+// everything the shared one configures, the JIT stack callback included, and a
+// match through it then runs on 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));
+
+  // 40 bytes of JIT stack per subject character, so PCRE2's 32KiB fallback 
stops at
+  // 818 characters and the shared context's 1MiB stack at 26,213. 5,000 sits 
six
+  // times above the first and five times below the second, so a blank context 
and
+  // the shared one give different answers with margin either way.
+  std::string const subject(5000, '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 copy paths must carry the inherited configuration too. Building a 
blank
+  // context in either of them is the same defect, and nothing else here 
notices.
+  RegexMatchContext const copied{match_context};
+  RegexMatchContext       assigned;
+
+  assigned = match_context;
+
+  RegexMatches copied_matches;
+  RegexMatches assigned_matches;
+
+  REQUIRE(re.exec(subject, copied_matches, 0, &copied) == shared_rc);
+  REQUIRE(re.exec(subject, assigned_matches, 0, &assigned) == shared_rc);
+}
+
+// Ownership only, and deliberately not inside the case above.
+//
+// That case SKIPs when pattern_has_jit() is false, which is right for what it 
tests and
+// wrong for this: move construction and move assignment have nothing to do 
with the JIT,
+// and a double free matters as much on a PCRE2 without JIT, or on a hardened 
runtime
+// where JIT allocation fails, as anywhere else. Inside that case this 
coverage would
+// skip on exactly those builds and still report green.
+TEST_CASE("RegexMatchContext move operations transfer ownership", 
"[libts][Regex][RegexMatchContext]")
+{
+  Regex re;
+
+  REQUIRE(re.compile("^(a+)(b+)$"));
+
+  std::string_view const subject{"aaabbb"};
+
+  auto matches_through = [&](RegexMatchContext const *ctx) {
+    RegexMatches m;
+    return re.exec(subject, m, 0, ctx);
+  };
+
+  // Baseline through a plain context, so a later mismatch means the move 
broke something
+  // rather than the pattern never having matched.
+  RegexMatchContext plain;
+  int const         expected = matches_through(&plain);
+
+  REQUIRE(expected > 0);
+
+  SECTION("move construction")
+  {
+    RegexMatchContext       donor;
+    RegexMatchContext const moved{std::move(donor)};
+
+    REQUIRE(matches_through(&moved) == expected);
+    // A double free aborts when donor and moved are both destroyed, so 
leaving this
+    // section is itself the second assertion.
+  }
+
+  SECTION("move assignment onto a destination that already holds a context")
+  {
+    // On an ordinary build the assertions below do not detect a dropped
+    // pcre2_match_context_free(old): removing that call leaves this section 
passing,
+    // because a leak has no observer here. The oracle for the leak is 
LeakSanitizer,
+    // which AddressSanitizer turns on by default on Linux but not on macOS.
+    //
+    // The section still earns its place: it is what gives LSan a move 
assignment onto a
+    // live context to observe, which no other case in this file produces. 
Without it
+    // the leak is unreachable and therefore undetectable anywhere.
+    RegexMatchContext destination;
+
+    REQUIRE(matches_through(&destination) == expected);
+
+    RegexMatchContext donor;
+
+    destination = std::move(donor);
+
+    REQUIRE(matches_through(&destination) == expected);
+  }
+
+  SECTION("self move assignment")
+  {
+    RegexMatchContext ctx;
+
+    // A match limit of one fails this match, so the result after the move 
shows whether
+    // ctx still holds its own context. Without the this != &that guard the 
operator frees
+    // the context and then nulls itself, and the match runs on PCRE2's 
defaults instead.
+    ctx.set_match_limit(1);
+    REQUIRE(matches_through(&ctx) == PCRE2_ERROR_MATCHLIMIT);
+
+    auto &alias = ctx;
+
+    ctx = std::move(alias);
+
+    REQUIRE(matches_through(&ctx) == PCRE2_ERROR_MATCHLIMIT);
+  }
+}
+
+// A pattern that backtracks once per character must fail cleanly rather than 
run
+// the thread out of stack. A regex engine that recurses on the machine stack 
crashes
+// the server on a long enough subject; PCRE2 must report an error instead.
+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));
+
+  // This pattern starts failing at roughly 43KiB of subject against a 1MiB JIT
+  // stack, measured identically on x86_64 and arm64. Smaller JIT frames get 
more
+  // subject out of the same stack and so push that threshold up; 256KiB keeps 
a
+  // six times margin against that. Do not trim this to just above 43KiB.
+  std::string subject{"/alpha/bravo/?"};
+  subject.append(256 * 1024, 'x');
+
+  RegexMatches matches;
+  int const    rc = re.exec(subject, matches);
+  CAPTURE(rc);
+
+  // Reaching this line at all is the crash assertion.
+  REQUIRE(rc < 0);
+  REQUIRE(rc != RE_ERROR_NOMATCH);
+
+  // The paired positive control, and the only part of this case that can tell 
a
+  // 1MiB stack from PCRE2's 32KiB fallback: 256KiB overruns both bounds, so 
every
+  // assertion above also holds with the JIT stack callback deleted. 10,000 is 
seven
+  // times over the fallback's bound and four times under the 1MiB stack's. 
Neither
+  // bound pins 1MiB itself; the suite only requires a maximum in roughly
+  // [240KB, 6MB].
+  std::string smaller{"/alpha/bravo/?"};
+  smaller.append(10000, 'x');
+
+  RegexMatches small_matches;
+  int const    small_rc = re.exec(smaller, small_matches);
+  CAPTURE(small_rc);
+
+  REQUIRE(small_rc > 0);
+}
+
+namespace
+{
+/** A reusable barrier, so every round starts with all threads alive and 
inside it. The
+ * matches of one round then start together on every thread. std::barrier 
would say this
+ * directly; it is hand-rolled here to match notstd::barrier in 
benchmark_LogObject.cc.
+ *
+ * Each completed round advances the generation, which is what releases the 
waiters, so
+ * the barrier can be crossed any number of times. Exactly `expected` threads 
must call
+ * arrive_and_wait() every round or the rest block forever, and the barrier 
must outlive
+ * all of them, since destroying a condition_variable with waiters on it is 
undefined.
+ */
+class RoundBarrier

Review Comment:
   Switching to std::barrier in 4cadf1629693 makes this moot for the test, but 
I did try it. The obvious semaphore version counts arrivals, and the last 
thread releases N-1 permits. Nothing ties a permit to a round, so a thread 
released early can loop around and take a permit meant for a thread still 
waiting in the previous round. At 8 threads and 2000 rounds the first run hung. 
With a timeout on the acquire, every run had 7 to 9 waits that never got a 
permit, and each of those is a hang without the timeout. A correct version 
needs a second turnstile, which is more code than the mutex version was.



-- 
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: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to