[libc-commits] [libc] [libc][regex] Harden ExprPool, nullable, and pmatch (PR #243882)

Jeff Bailey via libc-commits libc-commits at lists.llvm.org
Wed Nov 18 06:56:14 PST 2026


https://github.com/kaladron created https://github.com/llvm/llvm-project/pull/243882

Evaluating nullable() recursively can blow small stacks on embedded and GPU targets when a pattern contains a long chain of anchors.  Store a 4-bit anchor truth table inside Expr (keeping it at 16 bytes) so nullable() runs in constant time with no recursion.

ExprPool also used an unseeded hash table with linear probing, letting crafted patterns cause long collision chains.  Mix heap and stack addresses into a per-pool seed during initialisation and switch to triangular probing.  Narrowing node_count to ExprId frees 4 bytes for the seed, keeping ExprPool at 72 bytes.

In NDEBUG builds, stripping assertions left invalid ExprIds and ByteSet indices unchecked.  Add runtime bounds checks across ExprPool and the matcher, and reject unknown anchor bits before interning.

In regexec, a match previously left caller-provided pmatch arrays unchecked and uninitialised.  Check pmatch for null when nmatch is positive without REG_NOSUB, and initialise pmatch entries to -1 on match after releasing internal->lock.  Move the large pool-exhaustion test into its own binary so regex_basic_test keeps headroom in the 1 MiB hermetic heap.

Compliance: Henry Spencer spencer_tests.txt 268/456 Bool/Err (+0) and 84/456 Full Pos (+0); AT&T testregex 399/400 ERE Bool/Err (+0), 401/473 All Bool/Err (+0), and 18/465 Full Pos (+0); zero regressions.

Assisted-by: Automated tooling, human reviewed.

>From 69c9c72142a3627d42bc256394a0c4f72f0c78b0 Mon Sep 17 00:00:00 2001
From: Jeff Bailey <jbailey at raspberryginger.com>
Date: Wed, 18 Nov 2026 13:00:56 +0000
Subject: [PATCH] [libc][regex] Harden ExprPool, nullable, and pmatch

Evaluating nullable() recursively can blow small stacks on embedded and
GPU targets when a pattern contains a long chain of anchors.  Store a
4-bit anchor truth table inside Expr (keeping it at 16 bytes) so
nullable() runs in constant time with no recursion.

ExprPool also used an unseeded hash table with linear probing, letting
crafted patterns cause long collision chains.  Mix heap and stack
addresses into a per-pool seed during initialisation and switch to
triangular probing.  Narrowing node_count to ExprId frees 4 bytes for
the seed, keeping ExprPool at 72 bytes.

In NDEBUG builds, stripping assertions left invalid ExprIds and ByteSet
indices unchecked.  Add runtime bounds checks across ExprPool and the
matcher, and reject unknown anchor bits before interning.

In regexec, a match previously left caller-provided pmatch arrays
unchecked and uninitialised.  Check pmatch for null when nmatch is
positive without REG_NOSUB, and initialise pmatch entries to -1 on
match after releasing internal->lock.  Move the large pool-exhaustion
test into its own binary so regex_basic_test keeps headroom in the 1 MiB
hermetic heap.

Compliance: Henry Spencer spencer_tests.txt 268/456 Bool/Err (+0) and
84/456 Full Pos (+0); AT&T testregex 399/400 ERE Bool/Err (+0), 401/473
All Bool/Err (+0), and 18/465 Full Pos (+0); zero regressions.

Assisted-by: Automated tooling, human reviewed.
---
 libc/src/__support/regex/CMakeLists.txt       |  1 +
 libc/src/__support/regex/regex_ast.h          | 80 ++++++++++++-------
 libc/src/__support/regex/regex_expr_pool.cpp  | 77 +++++++++++-------
 libc/src/__support/regex/regex_expr_pool.h    | 38 +++++++--
 libc/src/__support/regex/regex_matcher.cpp    | 30 +------
 libc/src/__support/regex/regex_matcher.h      |  7 +-
 libc/src/regex/CMakeLists.txt                 |  1 +
 libc/src/regex/regexec.cpp                    | 29 +++++--
 libc/test/src/__support/regex/CMakeLists.txt  |  1 +
 libc/test/src/__support/regex/expr_test.cpp   | 61 ++++++++++++++
 .../test/src/__support/regex/matcher_test.cpp | 42 ++++++++++
 libc/test/src/regex/CMakeLists.txt            | 33 ++++++++
 libc/test/src/regex/regex_basic_test.cpp      | 24 ------
 libc/test/src/regex/regex_limits_test.cpp     | 52 ++++++++++++
 libc/test/src/regex/regex_submatch_test.cpp   | 71 ++++++++++++++++
 15 files changed, 427 insertions(+), 120 deletions(-)
 create mode 100644 libc/test/src/regex/regex_limits_test.cpp
 create mode 100644 libc/test/src/regex/regex_submatch_test.cpp

diff --git a/libc/src/__support/regex/CMakeLists.txt b/libc/src/__support/regex/CMakeLists.txt
index a7c7dd66f5824b..542f61faa91603 100644
--- a/libc/src/__support/regex/CMakeLists.txt
+++ b/libc/src/__support/regex/CMakeLists.txt
@@ -22,6 +22,7 @@ add_object_library(
     libc.src.__support.error_or
     libc.src.__support.hash
     libc.src.__support.libc_assert
+    libc.src.__support.macros.optimization
 )
 
 add_header_library(
diff --git a/libc/src/__support/regex/regex_ast.h b/libc/src/__support/regex/regex_ast.h
index a7d9847efcbbee..d2b2874d5f665b 100644
--- a/libc/src/__support/regex/regex_ast.h
+++ b/libc/src/__support/regex/regex_ast.h
@@ -51,6 +51,14 @@ enum AnchorKind : uint8_t {
   ANCHOR_EOL = 1 << 1,
 };
 
+/// Mask of all supported AnchorKind flags.
+inline constexpr uint8_t ALL_ANCHORS_MASK = ANCHOR_BOL | ANCHOR_EOL;
+static_assert(ALL_ANCHORS_MASK == 0x3,
+              "4-bit nullable_mask covers exactly 2 anchor bits");
+/// 4-bit nullability truth table masks across anchor_ctx values 0..3.
+inline constexpr uint8_t NULLABLE_NEVER = 0x0;
+inline constexpr uint8_t NULLABLE_ALWAYS = 0xF;
+
 /// Enumeration of Regular Expression AST node types.
 enum class ExprKind : uint8_t {
   /// Represents the empty set (matches nothing).
@@ -91,8 +99,9 @@ struct Expr {
 
   /// The type of this expression node.
   ExprKind kind = ExprKind::EmptySet;
-  /// Whether this expression can match the empty string unconditionally.
-  bool nullable : 1;
+  /// 4-bit truth table of empty-string nullability across anchor_ctx 0..3
+  /// (bit c is 1 iff this node matches empty when active anchors == c).
+  uint8_t nullable_mask : 4;
   /// Whether this expression or any child contains a context-sensitive Anchor.
   bool has_anchors : 1;
   /// Whether this expression or any child contains a Repeat node.
@@ -118,46 +127,58 @@ struct Expr {
 
   /// Default constructor creates an EmptySet node.
   /// Public to allow array allocation in ExprPool::Block.
-  constexpr Expr() : nullable(false), has_anchors(false), has_repeat(false) {}
+  constexpr Expr()
+      : nullable_mask(NULLABLE_NEVER), has_anchors(false), has_repeat(false) {}
 
 private:
-  /// Create a leaf node with a specific nullability (and optional character).
-  constexpr Expr(ExprKind k, bool is_null, char c = '\0')
-      : kind(k), nullable(is_null), has_anchors(false), has_repeat(false),
-        ch(c) {}
+  /// Computes the 4-bit nullability truth table for an Anchor bitmask.
+  static constexpr uint8_t anchor_nullable_mask(uint8_t mask) {
+    uint8_t out = 0;
+    for (uint8_t ctx = 0; ctx < 4; ++ctx)
+      if ((ctx & mask) == mask)
+        out |= static_cast<uint8_t>(1u << ctx);
+    return out;
+  }
+
+  /// Create a leaf node with a specific nullability mask (and optional char).
+  constexpr Expr(ExprKind k, uint8_t null_mask, char c = '\0')
+      : kind(k), nullable_mask(null_mask), has_anchors(false),
+        has_repeat(false), ch(c) {}
   /// Create an Anchor node.
   constexpr Expr(uint8_t mask)
-      : kind(ExprKind::Anchor), nullable(false), has_anchors(true),
-        has_repeat(false), anchor_mask(mask) {}
+      : kind(ExprKind::Anchor), nullable_mask(anchor_nullable_mask(mask)),
+        has_anchors(true), has_repeat(false), anchor_mask(mask) {}
   /// Create a ByteSet node.
   constexpr Expr(uint32_t bs_id)
-      : kind(ExprKind::ByteSet), nullable(false), has_anchors(false),
-        has_repeat(false), byte_set_id(bs_id) {}
+      : kind(ExprKind::ByteSet), nullable_mask(NULLABLE_NEVER),
+        has_anchors(false), has_repeat(false), byte_set_id(bs_id) {}
   /// Create a Star node.
   constexpr Expr(ExprId b, bool anchors, bool repeats, uint16_t exp)
-      : kind(ExprKind::Star), nullable(true), has_anchors(anchors),
-        has_repeat(repeats), rep_expansion(exp), body(b) {}
+      : kind(ExprKind::Star), nullable_mask(NULLABLE_ALWAYS),
+        has_anchors(anchors), has_repeat(repeats), rep_expansion(exp), body(b) {
+  }
   /// Create a Repeat node.
-  constexpr Expr(ExprId b, uint16_t min_rep, uint16_t max_rep, bool is_null,
-                 bool anchors, uint16_t exp)
-      : kind(ExprKind::Repeat), nullable((min_rep == 0) || is_null),
+  constexpr Expr(ExprId b, uint16_t min_rep, uint16_t max_rep,
+                 uint8_t body_null_mask, bool anchors, uint16_t exp)
+      : kind(ExprKind::Repeat),
+        nullable_mask((min_rep == 0) ? NULLABLE_ALWAYS : body_null_mask),
         has_anchors(anchors), has_repeat(true), rep_expansion(exp),
         rep{b, min_rep, max_rep} {}
   /// Create a binary node (Concat or Alt).
-  constexpr Expr(ExprKind k, bool is_null, bool anchors, bool repeats,
+  constexpr Expr(ExprKind k, uint8_t null_mask, bool anchors, bool repeats,
                  uint16_t exp, ExprId l, ExprId r)
-      : kind(k), nullable(is_null), has_anchors(anchors), has_repeat(repeats),
-        rep_expansion(exp), bin{l, r} {}
+      : kind(k), nullable_mask(null_mask), has_anchors(anchors),
+        has_repeat(repeats), rep_expansion(exp), bin{l, r} {}
 
 public:
   static constexpr Expr make_empty_set() {
-    return Expr(ExprKind::EmptySet, false);
+    return Expr(ExprKind::EmptySet, NULLABLE_NEVER);
   }
   static constexpr Expr make_empty_str() {
-    return Expr(ExprKind::EmptyStr, true);
+    return Expr(ExprKind::EmptyStr, NULLABLE_ALWAYS);
   }
   static constexpr Expr make_literal(char c) {
-    return Expr(ExprKind::Literal, false, c);
+    return Expr(ExprKind::Literal, NULLABLE_NEVER, c);
   }
   static constexpr Expr make_anchor(uint8_t mask) { return Expr(mask); }
   static constexpr Expr make_byte_set(uint32_t bs_id) { return Expr(bs_id); }
@@ -166,19 +187,22 @@ struct Expr {
     return Expr(b, anchors, repeats, exp);
   }
   static constexpr Expr make_repeat(ExprId b, uint16_t min_rep,
-                                    uint16_t max_rep, bool is_null = false,
+                                    uint16_t max_rep,
+                                    uint8_t body_null_mask = NULLABLE_NEVER,
                                     bool anchors = false, uint16_t exp = 1) {
-    return Expr(b, min_rep, max_rep, is_null, anchors, exp);
+    return Expr(b, min_rep, max_rep, body_null_mask, anchors, exp);
   }
-  static constexpr Expr make_concat(ExprId l, ExprId r, bool is_null = false,
+  static constexpr Expr make_concat(ExprId l, ExprId r,
+                                    uint8_t null_mask = NULLABLE_NEVER,
                                     bool anchors = false, bool repeats = false,
                                     uint16_t exp = 1) {
-    return Expr(ExprKind::Concat, is_null, anchors, repeats, exp, l, r);
+    return Expr(ExprKind::Concat, null_mask, anchors, repeats, exp, l, r);
   }
-  static constexpr Expr make_alt(ExprId l, ExprId r, bool is_null = false,
+  static constexpr Expr make_alt(ExprId l, ExprId r,
+                                 uint8_t null_mask = NULLABLE_NEVER,
                                  bool anchors = false, bool repeats = false,
                                  uint16_t exp = 1) {
-    return Expr(ExprKind::Alt, is_null, anchors, repeats, exp, l, r);
+    return Expr(ExprKind::Alt, null_mask, anchors, repeats, exp, l, r);
   }
 
   /// Equivalence check for hash-consing.
diff --git a/libc/src/__support/regex/regex_expr_pool.cpp b/libc/src/__support/regex/regex_expr_pool.cpp
index 976d2596cab223..3ccd2d38161471 100644
--- a/libc/src/__support/regex/regex_expr_pool.cpp
+++ b/libc/src/__support/regex/regex_expr_pool.cpp
@@ -13,7 +13,9 @@
 
 #include "src/__support/regex/regex_expr_pool.h"
 #include "hdr/regex_macros.h"
+#include "hdr/stdint_proxy.h"
 #include "src/__support/CPP/algorithm.h"
+#include "src/__support/CPP/array.h"
 #include "src/__support/CPP/optional.h"
 #include "src/__support/CPP/utility.h"
 #include "src/__support/checked_ptr.h"
@@ -25,13 +27,12 @@ namespace regex {
 
 namespace {
 
-// Hash an Expr node for hash-consing.
-uint32_t hash_expr(const Expr e) {
-  // Initialise HashState with a constant seed. The specific value (0x12345678)
-  // is an arbitrary placeholder; HashState immediately mixes this seed with
-  // high-entropy constants (derived from aHash) to produce a strong hash, while
-  // the constant value guarantees deterministic hashing for hash-consing.
-  internal::HashState hasher(0x12345678);
+// Hash an Expr node for hash-consing using the pool's pre-mixed seed.
+uint32_t hash_expr(const Expr e, uint32_t seed) {
+  const uint64_t s = (static_cast<uint64_t>(seed) << 32) | seed;
+  internal::HashState hasher(
+      internal::RANDOMNESS[1][0] ^ s, internal::RANDOMNESS[1][1] ^ s,
+      internal::RANDOMNESS[1][2] ^ s, internal::RANDOMNESS[1][3] ^ s);
   struct HashKey {
     uint64_t kind;
     uint64_t payload;
@@ -67,7 +68,9 @@ uint32_t hash_expr(const Expr e) {
   return static_cast<uint32_t>(h ^ (h >> 32));
 }
 
-// Bounded linear-probing range over a power-of-two open-addressing table.
+// Bounded triangular-probing range over a power-of-two open-addressing table.
+// Triangular numbers k(k+1)/2 mod 2^p visit every bucket exactly once while
+// avoiding linear-probing primary clustering.
 class BucketProber {
   cpp::span<ExprId> table;
   size_t start_idx;
@@ -86,8 +89,8 @@ class BucketProber {
 
     ExprId &operator*() const { return table[idx]; }
     Iterator &operator++() {
-      idx = (idx + 1) & mask();
       ++step;
+      idx = (idx + step) & mask();
       return *this;
     }
     constexpr bool operator!=(Sentinel) const { return step != table.size(); }
@@ -115,6 +118,22 @@ bool ExprPool::ensure_initialized() {
   hashtable = table.take_unique();
   hashtable_capacity = INITIAL_HASH_CAPACITY;
 
+  // Seed per-pool hashing from both heap and stack addresses without syscalls
+  // so baremetal and GPU targets stay self-contained.  Do not XOR this with
+  // blocks.get(): regcomp() allocates RegexInternal on the heap right before
+  // blocks, so both pointers share the same heap ASLR base and XORing them
+  // cancels the randomised upper bits into a constant offset.  Feeding them
+  // separately into HashState alongside a stack address (&ptrs) preserves both
+  // heap and stack ASLR entropy while sequential ExprIds stay deterministic.
+  const cpp::array<uintptr_t, 2> ptrs = {
+      reinterpret_cast<uintptr_t>(blocks.get()),
+      reinterpret_cast<uintptr_t>(&ptrs)};
+  internal::HashState seed_hasher(
+      static_cast<uint64_t>(reinterpret_cast<uintptr_t>(this)));
+  seed_hasher.update(ptrs.data(), sizeof(ptrs));
+  const uint64_t mixed = seed_hasher.finish();
+  hash_seed = static_cast<uint32_t>(mixed ^ (mixed >> 32));
+
   [[maybe_unused]] auto empty_set_id = intern(Expr::make_empty_set());
   [[maybe_unused]] auto empty_str_id = intern(Expr::make_empty_str());
   LIBC_ASSERT(empty_set_id.has_value() && *empty_set_id == EMPTY_SET_ID);
@@ -175,7 +194,7 @@ ErrorOr<ExprId> ExprPool::intern(Expr e) {
     return Error(REG_ESPACE);
 
   // Probe for an existing node with identical content.
-  e.hash = hash_expr(e);
+  e.hash = hash_expr(e, hash_seed);
   ExprId *bucket = &find_bucket(hashtable_slots(), e);
   if (*bucket != INVALID_EXPR_ID)
     return *bucket;
@@ -198,7 +217,7 @@ ErrorOr<ExprId> ExprPool::intern(Expr e) {
 
   // Node Initialisation: Copy the structural definition into the arena.
   ++node_count;
-  ExprId new_id = static_cast<ExprId>(node_count);
+  ExprId new_id = node_count;
   slot_at(new_id) = e;
   *bucket = new_id;
   return new_id;
@@ -218,7 +237,7 @@ ErrorOr<ExprId> ExprPool::make_lit(char c) {
   return intern(Expr::make_literal(c));
 }
 ErrorOr<ExprId> ExprPool::make_anchor(uint8_t mask) {
-  if (mask == 0)
+  if (mask == 0 || (mask & ~ALL_ANCHORS_MASK) != 0)
     return Error(REG_BADPAT);
   return intern(Expr::make_anchor(mask));
 }
@@ -282,7 +301,7 @@ constexpr uint16_t scale_exp(uint16_t base, uint16_t factor) {
 } // namespace
 
 ErrorOr<ExprId> ExprPool::make_star(ExprId body) {
-  if (body == INVALID_EXPR_ID)
+  if (!is_valid_input(body))
     return Error(REG_BADPAT);
   // Ø* = ε and ε* = ε
   if (body == EMPTY_SET_ID || body == EMPTY_STR_ID)
@@ -299,7 +318,7 @@ ErrorOr<ExprId> ExprPool::make_star(ExprId body) {
 }
 
 ErrorOr<ExprId> ExprPool::make_repeat(ExprId body, uint16_t min, uint16_t max) {
-  if (body == INVALID_EXPR_ID || min > max || min == REPEAT_INF)
+  if (!is_valid_input(body) || min > max || min == REPEAT_INF)
     return Error(REG_BADPAT);
   // Normalize R{0,0} = ε, ε{m,n} = ε, Ø{m,n}, R{1,1} = R, and
   // R{0,REPEAT_INF} = R*.
@@ -318,12 +337,13 @@ ErrorOr<ExprId> ExprPool::make_repeat(ExprId body, uint16_t min, uint16_t max) {
       be.rep.max == REPEAT_INF)
     return make_repeat(be.rep.body, min, REPEAT_INF);
   uint16_t factor = (max == REPEAT_INF) ? min : max;
-  return intern(Expr::make_repeat(body, min, max, be.nullable, be.has_anchors,
+  return intern(Expr::make_repeat(body, min, max, be.nullable_mask,
+                                  be.has_anchors,
                                   scale_exp(be.rep_expansion, factor)));
 }
 
 ErrorOr<ExprId> ExprPool::make_concat(ExprId l, ExprId r) {
-  if (l == INVALID_EXPR_ID || r == INVALID_EXPR_ID)
+  if (!is_valid_input(l) || !is_valid_input(r))
     return Error(REG_BADPAT);
   // Apply basic algebraic identities for concatenation:
   // Ø · R = R · Ø = Ø (Identity: null set)
@@ -345,8 +365,8 @@ ErrorOr<ExprId> ExprPool::make_concat(ExprId l, ExprId r) {
   }
   const Expr re = get(r);
   return intern(Expr::make_concat(
-      l, r, le.nullable && re.nullable, le.has_anchors || re.has_anchors,
-      le.has_repeat || re.has_repeat,
+      l, r, static_cast<uint8_t>(le.nullable_mask & re.nullable_mask),
+      le.has_anchors || re.has_anchors, le.has_repeat || re.has_repeat,
       cpp::max(le.rep_expansion, re.rep_expansion)));
 }
 
@@ -473,7 +493,7 @@ ErrorOr<ExprId> coalesce_item_into_spine(ExprId item, ExprId spine,
 } // namespace
 
 ErrorOr<ExprId> ExprPool::make_alt(ExprId l, ExprId r) {
-  if (l == INVALID_EXPR_ID || r == INVALID_EXPR_ID)
+  if (!is_valid_input(l) || !is_valid_input(r))
     return Error(REG_BADPAT);
   // Apply basic algebraic identities for alternation:
   // Ø | R = R | Ø = R (Identity: null set) and R | R = R (Idempotency)
@@ -491,10 +511,10 @@ ErrorOr<ExprId> ExprPool::make_alt(ExprId l, ExprId r) {
       return coalesced;
     if (l > r)
       cpp::swap(l, r);
-    return intern(Expr::make_alt(l, r, le.nullable || re.nullable,
-                                 le.has_anchors || re.has_anchors,
-                                 le.has_repeat || re.has_repeat,
-                                 cpp::max(le.rep_expansion, re.rep_expansion)));
+    return intern(Expr::make_alt(
+        l, r, static_cast<uint8_t>(le.nullable_mask | re.nullable_mask),
+        le.has_anchors || re.has_anchors, le.has_repeat || re.has_repeat,
+        cpp::max(le.rep_expansion, re.rep_expansion)));
   }
 
   if (le.has_repeat || re.has_repeat) {
@@ -541,11 +561,12 @@ ErrorOr<ExprId> ExprPool::make_alt(ExprId l, ExprId r) {
   ExprId rest_head = (re_rest.kind == ExprKind::Alt) ? re_rest.bin.left : *rest;
   if (head >= rest_head)
     return make_alt(head, *rest);
-  return intern(
-      Expr::make_alt(head, *rest, he.nullable || re_rest.nullable,
-                     he.has_anchors || re_rest.has_anchors,
-                     he.has_repeat || re_rest.has_repeat,
-                     cpp::max(he.rep_expansion, re_rest.rep_expansion)));
+  return intern(Expr::make_alt(
+      head, *rest,
+      static_cast<uint8_t>(he.nullable_mask | re_rest.nullable_mask),
+      he.has_anchors || re_rest.has_anchors,
+      he.has_repeat || re_rest.has_repeat,
+      cpp::max(he.rep_expansion, re_rest.rep_expansion)));
 }
 
 } // namespace regex
diff --git a/libc/src/__support/regex/regex_expr_pool.h b/libc/src/__support/regex/regex_expr_pool.h
index 2bb2dfe0067874..f04a6ac60dd141 100644
--- a/libc/src/__support/regex/regex_expr_pool.h
+++ b/libc/src/__support/regex/regex_expr_pool.h
@@ -14,6 +14,7 @@
 #ifndef LLVM_LIBC_SRC___SUPPORT_REGEX_REGEX_EXPR_POOL_H
 #define LLVM_LIBC_SRC___SUPPORT_REGEX_REGEX_EXPR_POOL_H
 
+#include "hdr/stdint_proxy.h"
 #include "hdr/types/size_t.h"
 #include "src/__support/CPP/array.h"
 #include "src/__support/CPP/span.h"
@@ -21,6 +22,7 @@
 #include "src/__support/error_or.h"
 #include "src/__support/libc_assert.h"
 #include "src/__support/macros/config.h"
+#include "src/__support/macros/optimization.h"
 #include "src/__support/regex/regex_ast.h"
 
 namespace LIBC_NAMESPACE_DECL {
@@ -58,7 +60,7 @@ class ExprPool {
   /// Scaling factor used when growing dynamic pool arrays and hash tables.
   static constexpr size_t GROWTH_FACTOR = 2;
   /// Grow the hash table when occupancy reaches 70% (7 / 10) to keep
-  /// linear-probing chains short without floating-point arithmetic.
+  /// triangular-probing chains short without floating-point arithmetic.
   static constexpr size_t MAX_LOAD_NUMERATOR = 7;
   static constexpr size_t MAX_LOAD_DENOMINATOR = 10;
 
@@ -67,7 +69,9 @@ class ExprPool {
   size_t block_capacity = 0;
   size_t block_count = 0;
   /// Total number of nodes allocated across all blocks.
-  size_t node_count = 0;
+  ExprId node_count = 0;
+  /// Per-pool hash seed mixed once at initialisation to deter hash clustering.
+  uint32_t hash_seed = 0;
 
   /// Lazily allocated array of deduplicated 256-bit character sets.
   cpp::unique_ptr<ByteSet[]> byte_sets;
@@ -128,17 +132,41 @@ class ExprPool {
   ExprPool(ExprPool &&) = delete;
   ExprPool &operator=(ExprPool &&) = delete;
 
+  /// Returns true iff id refers to an interned node in this pool.
+  constexpr bool is_valid(ExprId id) const {
+    return id != INVALID_EXPR_ID && id <= node_count;
+  }
+
+  /// Returns true iff id is an interned node or one of the two constant empty
+  /// sentinels (EMPTY_SET_ID / EMPTY_STR_ID) usable before lazy init.
+  constexpr bool is_valid_input(ExprId id) const {
+    return is_valid(id) || id == EMPTY_SET_ID || id == EMPTY_STR_ID;
+  }
+
   /// Resolves an ExprId to a value copy of its 16-byte Expr node.
-  Expr get(ExprId id) const { return slot_at(id); }
+  Expr get(ExprId id) const {
+    if (LIBC_LIKELY(is_valid(id)))
+      return slot_at(id);
+    if (id == EMPTY_STR_ID)
+      return Expr::make_empty_str();
+    LIBC_ASSERT(id == EMPTY_SET_ID);
+    return Expr::make_empty_set();
+  }
 
   /// Resolves a ByteSet index to its 256-bit character set.
   const ByteSet &get_byte_set(uint32_t id) const {
-    LIBC_ASSERT(id < byte_set_count);
+    if (LIBC_UNLIKELY(id >= byte_set_count)) {
+      LIBC_ASSERT(false);
+      static constexpr ByteSet EMPTY_BYTE_SET{};
+      return EMPTY_BYTE_SET;
+    }
     return byte_sets[id];
   }
 
   /// O(1) unconditional nullability query for a valid ExprId.
-  bool is_nullable(ExprId id) const { return get(id).nullable; }
+  bool is_nullable(ExprId id) const {
+    return (get(id).nullable_mask & 1u) != 0;
+  }
 
   /// O(1) query indicating whether the subtree at id contains an Anchor node.
   bool has_anchors(ExprId id) const { return get(id).has_anchors; }
diff --git a/libc/src/__support/regex/regex_matcher.cpp b/libc/src/__support/regex/regex_matcher.cpp
index 4809e93154eb75..a4025ed2e427fc 100644
--- a/libc/src/__support/regex/regex_matcher.cpp
+++ b/libc/src/__support/regex/regex_matcher.cpp
@@ -42,34 +42,10 @@ uint8_t ctx_at(cpp::string_view input, size_t pos, int cflags, int eflags) {
 
 } // namespace
 
-bool nullable(ExprId id, uint8_t anchor_ctx, const ExprPool &pool) {
-  const Expr e = pool.get(id);
-  if (e.nullable || !e.has_anchors || anchor_ctx == 0)
-    return e.nullable;
-  switch (e.kind) {
-  case ExprKind::Anchor:
-    return (anchor_ctx & e.anchor_mask) == e.anchor_mask;
-  case ExprKind::Concat:
-    return nullable(e.bin.left, anchor_ctx, pool) &&
-           nullable(e.bin.right, anchor_ctx, pool);
-  case ExprKind::Alt:
-    return nullable(e.bin.left, anchor_ctx, pool) ||
-           nullable(e.bin.right, anchor_ctx, pool);
-  case ExprKind::Repeat:
-    return nullable(e.rep.body, anchor_ctx, pool);
-  case ExprKind::EmptySet:
-  case ExprKind::EmptyStr:
-  case ExprKind::Literal:
-  case ExprKind::ByteSet:
-  case ExprKind::Star:
-    break;
-  }
-  LIBC_ASSERT(false);
-  __builtin_unreachable();
-}
-
 ErrorOr<ExprId> derivative(ExprId id, char c, ExprPool &pool,
                            uint8_t ctx_before) {
+  if (!pool.is_valid_input(id))
+    return Error(REG_BADPAT);
   const Expr e = pool.get(id);
   switch (e.kind) {
   case ExprKind::EmptySet:
@@ -141,6 +117,8 @@ ErrorOr<ExprId> derivative(ExprId id, char c, ExprPool &pool,
 
 MatchResult match(ExprPool &pool, const ExprId pattern, cpp::string_view input,
                   int cflags, int eflags) {
+  if (!pool.is_valid_input(pattern) || pattern == EMPTY_SET_ID)
+    return MatchResult::NoMatch;
   uint8_t ctx = ctx_at(input, 0, cflags, eflags);
   if (nullable(pattern, ctx, pool))
     return MatchResult::Match;
diff --git a/libc/src/__support/regex/regex_matcher.h b/libc/src/__support/regex/regex_matcher.h
index 100c4c9dda44a7..06c15115eb7368 100644
--- a/libc/src/__support/regex/regex_matcher.h
+++ b/libc/src/__support/regex/regex_matcher.h
@@ -33,8 +33,11 @@ enum class MatchResult {
 };
 
 /// Evaluates whether id can match the empty string at a fencepost with the
-/// given active AnchorKind bitmask.
-bool nullable(ExprId id, uint8_t anchor_ctx, const ExprPool &pool);
+/// given active AnchorKind bitmask in O(1) via the precomputed 4-bit mask.
+LIBC_INLINE bool nullable(ExprId id, uint8_t anchor_ctx, const ExprPool &pool) {
+  return ((pool.get(id).nullable_mask >> (anchor_ctx & ALL_ANCHORS_MASK)) &
+          1u) != 0;
+}
 
 /// Computes the Brzozowski derivative D_c(id) with respect to character c
 /// when stepping across c from a fencepost with active anchor mask ctx_before.
diff --git a/libc/src/regex/CMakeLists.txt b/libc/src/regex/CMakeLists.txt
index 99ba22ff954655..4525b344bd8e6f 100644
--- a/libc/src/regex/CMakeLists.txt
+++ b/libc/src/regex/CMakeLists.txt
@@ -29,6 +29,7 @@ add_entrypoint_object(
     libc.hdr.types.size_t
     libc.src.__support.CPP.mutex
     libc.src.__support.CPP.string_view
+    libc.src.__support.libc_assert
     libc.src.__support.macros.null_check
     libc.src.__support.regex.regex_internal
     libc.src.__support.regex.regex_matcher
diff --git a/libc/src/regex/regexec.cpp b/libc/src/regex/regexec.cpp
index c9d06837d329ae..e8e9cab759b8f1 100644
--- a/libc/src/regex/regexec.cpp
+++ b/libc/src/regex/regexec.cpp
@@ -17,6 +17,7 @@
 #include "src/__support/CPP/mutex.h"
 #include "src/__support/CPP/string_view.h"
 #include "src/__support/common.h"
+#include "src/__support/libc_assert.h"
 #include "src/__support/macros/config.h"
 #include "src/__support/macros/null_check.h"
 #include "src/__support/regex/regex_internal.h"
@@ -31,10 +32,6 @@ LLVM_LIBC_FUNCTION(int, regexec,
   LIBC_CRASH_ON_NULLPTR(preg);
   LIBC_CRASH_ON_NULLPTR(string);
 
-  // TODO: Submatch extraction (nmatch/pmatch) and REG_STARTEND will be wired
-  // in subsequent patches.
-  (void)nmatch;
-  (void)pmatch;
   if ((eflags & ~(REG_NOTBOL | REG_NOTEOL)) != 0)
     return REG_BADPAT;
 
@@ -43,18 +40,36 @@ LLVM_LIBC_FUNCTION(int, regexec,
   if (!internal)
     return REG_NOMATCH;
 
+  const bool want_pmatch = nmatch > 0 && !(internal->cflags & REG_NOSUB);
+  if (want_pmatch)
+    LIBC_CRASH_ON_NULLPTR(pmatch);
+
   // POSIX requires regexec to be thread-safe across concurrent calls sharing a
   // const regex_t*. Serialise access to internal->pool during lazy derivative
-  // evaluation.
-  cpp::lock_guard guard(internal->lock);
-  switch (regex::match(*internal, cpp::string_view(string), eflags)) {
+  // evaluation, then release the lock before writing caller-owned pmatch.
+  regex::MatchResult res = regex::MatchResult::NoMatch;
+  {
+    cpp::lock_guard guard(internal->lock);
+    res = regex::match(*internal, cpp::string_view(string), eflags);
+  }
+  switch (res) {
   case regex::MatchResult::Match:
+    // TODO: Populate leftmost-longest match offsets in subsequent patches.
+    // Initialise pmatch to {-1, -1} so callers never observe uninitialised
+    // stack memory.
+    if (want_pmatch) {
+      for (size_t i = 0; i < nmatch; ++i) {
+        pmatch[i].rm_so = -1;
+        pmatch[i].rm_eo = -1;
+      }
+    }
     return 0;
   case regex::MatchResult::NoMatch:
     return REG_NOMATCH;
   case regex::MatchResult::OutOfMemory:
     return REG_ESPACE;
   }
+  LIBC_ASSERT(false);
   __builtin_unreachable();
 }
 
diff --git a/libc/test/src/__support/regex/CMakeLists.txt b/libc/test/src/__support/regex/CMakeLists.txt
index 156b99c761901c..1795f3559ec099 100644
--- a/libc/test/src/__support/regex/CMakeLists.txt
+++ b/libc/test/src/__support/regex/CMakeLists.txt
@@ -20,6 +20,7 @@ add_libc_test(
     libc.src.__support.CPP.string_view
     libc.src.__support.error_or
     libc.src.__support.regex.regex_expr_pool
+    libc.src.__support.regex.regex_internal
     libc.src.__support.regex.regex_matcher
     libc.src.__support.regex.regex_parser
 )
diff --git a/libc/test/src/__support/regex/expr_test.cpp b/libc/test/src/__support/regex/expr_test.cpp
index 33a40b91416588..97b26f7cf85751 100644
--- a/libc/test/src/__support/regex/expr_test.cpp
+++ b/libc/test/src/__support/regex/expr_test.cpp
@@ -380,3 +380,64 @@ TEST(LlvmLibcRegexExprTest, MemoryLimits) {
   EXPECT_EQ(bs_fail.error(), REG_ESPACE);
   EXPECT_EQ(pool.num_byte_sets(), size_t(0));
 }
+
+TEST(LlvmLibcRegexExprTest, BoundsGuardsAndNullableMask) {
+  // Uninitialised pool safely resolves constant sentinels and rejects invalid
+  // or out-of-range ExprIds.
+  {
+    ExprPool fresh;
+    EXPECT_FALSE(fresh.is_valid(EMPTY_SET_ID));
+    EXPECT_TRUE(fresh.is_valid_input(EMPTY_SET_ID));
+    EXPECT_TRUE(fresh.is_valid_input(EMPTY_STR_ID));
+    EXPECT_FALSE(fresh.is_valid_input(INVALID_EXPR_ID));
+    EXPECT_EQ(fresh.get(EMPTY_SET_ID).kind, ExprKind::EmptySet);
+    EXPECT_EQ(fresh.get(EMPTY_STR_ID).kind, ExprKind::EmptyStr);
+    EXPECT_FALSE(fresh.is_nullable(EMPTY_SET_ID));
+    EXPECT_TRUE(fresh.is_nullable(EMPTY_STR_ID));
+    EXPECT_EQ(fresh.allocated_bytes(), size_t(0));
+    auto expect_badpat = [](const auto &res) {
+      ASSERT_FALSE(res.has_value());
+      EXPECT_EQ(res.error(), REG_BADPAT);
+    };
+    expect_badpat(fresh.make_star(999));
+    expect_badpat(fresh.make_repeat(999, 1, 2));
+    expect_badpat(fresh.make_concat(999, EMPTY_STR_ID));
+    expect_badpat(fresh.make_alt(EMPTY_SET_ID, 999));
+    expect_badpat(fresh.make_anchor(0x04));
+    expect_badpat(fresh.make_anchor(ANCHOR_BOL | 0x04));
+    expect_badpat(fresh.make_anchor(0xFF));
+  }
+
+  ExprPool pool;
+  auto bol = pool.make_anchor(ANCHOR_BOL);
+  auto eol = pool.make_anchor(ANCHOR_EOL);
+  auto both = pool.make_anchor(ANCHOR_BOL | ANCHOR_EOL);
+  auto lit_a = pool.make_lit('a');
+  ASSERT_TRUE(bol.has_value());
+  ASSERT_TRUE(eol.has_value());
+  ASSERT_TRUE(both.has_value());
+  ASSERT_TRUE(lit_a.has_value());
+  auto bol_eol = pool.make_concat(*bol, *eol);
+  auto bol_or_eol = pool.make_alt(*bol, *eol);
+  auto bol_or_a = pool.make_alt(*bol, *lit_a);
+  ASSERT_TRUE(bol_eol.has_value());
+  ASSERT_TRUE(bol_or_eol.has_value());
+  ASSERT_TRUE(bol_or_a.has_value());
+  auto rep_bol = pool.make_repeat(*bol, 2, 3);
+  auto rep_bol_0 = pool.make_repeat(*bol, 0, 3);
+  auto star_bol = pool.make_star(*bol);
+  auto rep_bol_or_a = pool.make_repeat(*bol_or_a, 2, 3);
+  ASSERT_TRUE(rep_bol.has_value());
+  ASSERT_TRUE(rep_bol_0.has_value());
+  ASSERT_TRUE(star_bol.has_value());
+  ASSERT_TRUE(rep_bol_or_a.has_value());
+  EXPECT_EQ(pool.get(*bol).nullable_mask, uint8_t(0b1010));
+  EXPECT_EQ(pool.get(*eol).nullable_mask, uint8_t(0b1100));
+  EXPECT_EQ(pool.get(*both).nullable_mask, uint8_t(0b1000));
+  EXPECT_EQ(pool.get(*bol_eol).nullable_mask, uint8_t(0b1000));
+  EXPECT_EQ(pool.get(*bol_or_eol).nullable_mask, uint8_t(0b1110));
+  EXPECT_EQ(pool.get(*rep_bol).nullable_mask, uint8_t(0b1010));
+  EXPECT_EQ(pool.get(*rep_bol_0).nullable_mask, uint8_t(0b1111));
+  EXPECT_EQ(pool.get(*star_bol).nullable_mask, uint8_t(0b1111));
+  EXPECT_EQ(pool.get(*rep_bol_or_a).nullable_mask, uint8_t(0b1010));
+}
diff --git a/libc/test/src/__support/regex/matcher_test.cpp b/libc/test/src/__support/regex/matcher_test.cpp
index 42ab4f0eba842d..f1493a58f9fb89 100644
--- a/libc/test/src/__support/regex/matcher_test.cpp
+++ b/libc/test/src/__support/regex/matcher_test.cpp
@@ -16,20 +16,26 @@
 #include "src/__support/error_or.h"
 #include "src/__support/regex/regex_ast.h"
 #include "src/__support/regex/regex_expr_pool.h"
+#include "src/__support/regex/regex_internal.h"
 #include "src/__support/regex/regex_matcher.h"
 #include "src/__support/regex/regex_parser.h"
 #include "test/UnitTest/Test.h"
 
 using LIBC_NAMESPACE::ErrorOr;
 using LIBC_NAMESPACE::cpp::string_view;
+using LIBC_NAMESPACE::regex::ANCHOR_BOL;
+using LIBC_NAMESPACE::regex::ANCHOR_EOL;
 using LIBC_NAMESPACE::regex::derivative;
 using LIBC_NAMESPACE::regex::EMPTY_SET_ID;
 using LIBC_NAMESPACE::regex::EMPTY_STR_ID;
 using LIBC_NAMESPACE::regex::ExprId;
 using LIBC_NAMESPACE::regex::ExprPool;
+using LIBC_NAMESPACE::regex::INVALID_EXPR_ID;
 using LIBC_NAMESPACE::regex::match;
 using LIBC_NAMESPACE::regex::MatchResult;
+using LIBC_NAMESPACE::regex::nullable;
 using LIBC_NAMESPACE::regex::parse_ere;
+using LIBC_NAMESPACE::regex::RegexInternal;
 
 TEST(LlvmLibcRegexMatcherTest, DerivativeBaseCases) {
   ExprPool pool;
@@ -778,3 +784,39 @@ TEST(LlvmLibcRegexMatcherTest, RepeatStabilizationAndRfc2822Grammar) {
   for (string_view addr : BAD_ADDRS)
     EXPECT_EQ(match(rfc_pool, *addr_spec, addr), MatchResult::NoMatch);
 }
+
+TEST(LlvmLibcRegexMatcherTest, AnchorNullabilityMaskAndInvalidIds) {
+  // Default RegexInternal (root == INVALID_EXPR_ID) and uninitialised pool
+  // queries fail safely without dereferencing null blocks.
+  {
+    RegexInternal empty_internal;
+    EXPECT_EQ(match(empty_internal, "abc"), MatchResult::NoMatch);
+  }
+  {
+    ExprPool fresh;
+    EXPECT_EQ(match(fresh, EMPTY_STR_ID, "abc"), MatchResult::Match);
+    EXPECT_EQ(match(fresh, EMPTY_SET_ID, "abc"), MatchResult::NoMatch);
+    auto bad_d0 = derivative(INVALID_EXPR_ID, 'a', fresh);
+    auto bad_d1 = derivative(999, 'a', fresh);
+    ASSERT_FALSE(bad_d0.has_value());
+    ASSERT_FALSE(bad_d1.has_value());
+    EXPECT_EQ(bad_d0.error(), REG_BADPAT);
+    EXPECT_EQ(bad_d1.error(), REG_BADPAT);
+  }
+
+  // Deep 9,996-anchor chain evaluates nullable() in O(1) via the 4-bit mask
+  // with zero call-stack recursion.
+  ExprPool pool;
+  auto bol = pool.make_anchor(ANCHOR_BOL);
+  ASSERT_TRUE(bol.has_value());
+  ExprId chain = *bol;
+  for (size_t i = 0; i < 9995; ++i) {
+    auto next = pool.make_concat(*bol, chain);
+    ASSERT_TRUE(next.has_value());
+    chain = *next;
+  }
+  EXPECT_FALSE(nullable(chain, 0, pool));
+  EXPECT_TRUE(nullable(chain, ANCHOR_BOL, pool));
+  EXPECT_FALSE(nullable(chain, ANCHOR_EOL, pool));
+  EXPECT_TRUE(nullable(chain, ANCHOR_BOL | ANCHOR_EOL, pool));
+}
diff --git a/libc/test/src/regex/CMakeLists.txt b/libc/test/src/regex/CMakeLists.txt
index 804006d6900d48..a27683716e54d2 100644
--- a/libc/test/src/regex/CMakeLists.txt
+++ b/libc/test/src/regex/CMakeLists.txt
@@ -26,4 +26,37 @@ if(LLVM_LIBC_FULL_BUILD AND LLVM_LIBC_ENABLE_EXPERIMENTAL_ENTRYPOINTS)
       libc.src.regex.regexec
       libc.src.regex.regfree
   )
+
+  add_libc_test(
+    regex_limits_test
+    SUITE
+      libc-regex-tests
+    SRCS
+      regex_limits_test.cpp
+    DEPENDS
+      libc.hdr.regex_macros
+      libc.hdr.types.regex_t
+      libc.hdr.types.size_t
+      libc.src.__support.macros.attributes
+      libc.src.regex.regcomp
+      libc.src.regex.regexec
+      libc.src.regex.regfree
+  )
+
+  add_libc_test(
+    regex_submatch_test
+    SUITE
+      libc-regex-tests
+    SRCS
+      regex_submatch_test.cpp
+    DEPENDS
+      libc.hdr.regex_macros
+      libc.hdr.types.regex_t
+      libc.hdr.types.regmatch_t
+      libc.hdr.types.regoff_t
+      libc.src.__support.CPP.scope
+      libc.src.regex.regcomp
+      libc.src.regex.regexec
+      libc.src.regex.regfree
+  )
 endif()
diff --git a/libc/test/src/regex/regex_basic_test.cpp b/libc/test/src/regex/regex_basic_test.cpp
index 6eeb79f75bcab3..7c7d86c6b935bb 100644
--- a/libc/test/src/regex/regex_basic_test.cpp
+++ b/libc/test/src/regex/regex_basic_test.cpp
@@ -91,30 +91,6 @@ TEST(LlvmLibcRegexTest, OverlappingPrefixAndPostFreeSafety) {
             REG_NOMATCH);
 }
 
-TEST(LlvmLibcRegexTest, PoolExhaustionReturnsEspace) {
-  // 9998 'a' bytes plus EmptySet (1) and EmptyStr (2) fill all 10000 ExprPool
-  // slots during regcomp; regexec then hits MAX_NODE_LIMIT when interning the
-  // first derivative Alt state.
-  char pattern[10000];
-  for (size_t i = 0; i < 9998; ++i)
-    pattern[i] = 'a';
-  pattern[9998] = '\0';
-
-  regex_t preg;
-  ASSERT_EQ(LIBC_NAMESPACE::regcomp(&preg, pattern, REG_EXTENDED | REG_NOSUB),
-            0);
-  EXPECT_EQ(LIBC_NAMESPACE::regexec(&preg, "a", 0, nullptr, 0), REG_ESPACE);
-  LIBC_NAMESPACE::regfree(&preg);
-
-  // One additional byte (9999 'a's) hits MAX_NODE_LIMIT during regcomp;
-  // calling regfree afterwards must be a safe no-op.
-  pattern[9998] = 'a';
-  pattern[9999] = '\0';
-  EXPECT_EQ(LIBC_NAMESPACE::regcomp(&preg, pattern, REG_EXTENDED | REG_NOSUB),
-            REG_ESPACE);
-  LIBC_NAMESPACE::regfree(&preg);
-}
-
 TEST(LlvmLibcRegexTest, WildcardDot) {
   regex_t preg;
   ASSERT_EQ(LIBC_NAMESPACE::regcomp(&preg, "a.c", REG_EXTENDED | REG_NOSUB), 0);
diff --git a/libc/test/src/regex/regex_limits_test.cpp b/libc/test/src/regex/regex_limits_test.cpp
new file mode 100644
index 00000000000000..095e67103f1aa8
--- /dev/null
+++ b/libc/test/src/regex/regex_limits_test.cpp
@@ -0,0 +1,52 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+///
+/// \file
+/// Large pool-exhaustion and resource-limit tests for POSIX regex functions.
+///
+/// These tests intentionally drive ExprPool up to MAX_NODE_LIMIT and allocate
+/// hundreds of kilobytes of heap storage.  They live in their own test binary
+/// because LLVM libc's hermetic test allocator uses a fixed 1 MiB bump heap
+/// where free() is a no-op, so keeping them separate preserves headroom for
+/// regular functional tests in regex_basic_test.
+///
+//===----------------------------------------------------------------------===//
+
+#include "hdr/regex_macros.h"
+#include "hdr/types/regex_t.h"
+#include "hdr/types/size_t.h"
+#include "src/__support/macros/attributes.h"
+#include "src/regex/regcomp.h"
+#include "src/regex/regexec.h"
+#include "src/regex/regfree.h"
+#include "test/UnitTest/Test.h"
+
+TEST(LlvmLibcRegexLimitsTest, PoolExhaustionReturnsEspace) {
+  // 9998 'a' bytes plus EmptySet (1) and EmptyStr (2) fill all 10000 ExprPool
+  // slots during regcomp; regexec then hits MAX_NODE_LIMIT when interning the
+  // first derivative Alt state.
+  // 'static' to avoid exhausting the stack on GPU targets.
+  LIBC_CONSTINIT static char pattern[10000]{};
+  for (size_t i = 0; i < 9998; ++i)
+    pattern[i] = 'a';
+  pattern[9998] = '\0';
+
+  regex_t preg{};
+  ASSERT_EQ(LIBC_NAMESPACE::regcomp(&preg, pattern, REG_EXTENDED | REG_NOSUB),
+            0);
+  EXPECT_EQ(LIBC_NAMESPACE::regexec(&preg, "a", 0, nullptr, 0), REG_ESPACE);
+  LIBC_NAMESPACE::regfree(&preg);
+
+  // One additional byte (9999 'a's) hits MAX_NODE_LIMIT during regcomp;
+  // calling regfree afterwards must be a safe no-op.
+  pattern[9998] = 'a';
+  pattern[9999] = '\0';
+  EXPECT_EQ(LIBC_NAMESPACE::regcomp(&preg, pattern, REG_EXTENDED | REG_NOSUB),
+            REG_ESPACE);
+  LIBC_NAMESPACE::regfree(&preg);
+}
diff --git a/libc/test/src/regex/regex_submatch_test.cpp b/libc/test/src/regex/regex_submatch_test.cpp
new file mode 100644
index 00000000000000..abf49803a4659f
--- /dev/null
+++ b/libc/test/src/regex/regex_submatch_test.cpp
@@ -0,0 +1,71 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+///
+/// \file
+/// Submatch and pmatch contract tests for POSIX regexec.
+///
+//===----------------------------------------------------------------------===//
+
+#include "hdr/regex_macros.h"
+#include "hdr/types/regex_t.h"
+#include "hdr/types/regmatch_t.h"
+#include "hdr/types/regoff_t.h"
+#include "src/__support/CPP/scope.h"
+#include "src/regex/regcomp.h"
+#include "src/regex/regexec.h"
+#include "src/regex/regfree.h"
+#include "test/UnitTest/Test.h"
+
+using LIBC_NAMESPACE::cpp::scope_exit;
+
+TEST(LlvmLibcRegexSubmatchTest, PmatchInitialisedOnMatchAndPreservedOnNoMatch) {
+  regex_t preg{};
+  ASSERT_EQ(LIBC_NAMESPACE::regcomp(&preg, "hello", REG_EXTENDED), 0);
+  scope_exit free_guard([&preg] { LIBC_NAMESPACE::regfree(&preg); });
+
+  regmatch_t pm[2] = {{42, 99}, {77, 88}};
+  EXPECT_EQ(LIBC_NAMESPACE::regexec(&preg, "goodbye", 2, pm, 0), REG_NOMATCH);
+  EXPECT_EQ(pm[0].rm_so, regoff_t(42));
+  EXPECT_EQ(pm[0].rm_eo, regoff_t(99));
+  EXPECT_EQ(pm[1].rm_so, regoff_t(77));
+  EXPECT_EQ(pm[1].rm_eo, regoff_t(88));
+
+  EXPECT_EQ(LIBC_NAMESPACE::regexec(&preg, "say hello", 2, pm, 0), 0);
+  EXPECT_EQ(pm[0].rm_so, regoff_t(-1));
+  EXPECT_EQ(pm[0].rm_eo, regoff_t(-1));
+  EXPECT_EQ(pm[1].rm_so, regoff_t(-1));
+  EXPECT_EQ(pm[1].rm_eo, regoff_t(-1));
+
+  // nmatch == 0 allows pmatch == nullptr even without REG_NOSUB.
+  EXPECT_EQ(LIBC_NAMESPACE::regexec(&preg, "say hello", 0, nullptr, 0), 0);
+
+  // REG_NOSUB ignores nmatch and pmatch: nullptr succeeds and non-null pmatch
+  // is left untouched on match.
+  regex_t nosub{};
+  ASSERT_EQ(LIBC_NAMESPACE::regcomp(&nosub, "hello", REG_EXTENDED | REG_NOSUB),
+            0);
+  scope_exit free_nosub([&nosub] { LIBC_NAMESPACE::regfree(&nosub); });
+  EXPECT_EQ(LIBC_NAMESPACE::regexec(&nosub, "say hello", 2, nullptr, 0), 0);
+  regmatch_t untouched[1] = {{11, 22}};
+  EXPECT_EQ(LIBC_NAMESPACE::regexec(&nosub, "say hello", 1, untouched, 0), 0);
+  EXPECT_EQ(untouched[0].rm_so, regoff_t(11));
+  EXPECT_EQ(untouched[0].rm_eo, regoff_t(22));
+}
+
+#if defined(LIBC_ADD_NULL_CHECKS)
+TEST(LlvmLibcRegexSubmatchTest, PmatchNullPointerCrash) {
+  regex_t preg{};
+  ASSERT_EQ(LIBC_NAMESPACE::regcomp(&preg, "a", REG_EXTENDED), 0);
+  scope_exit free_guard([&preg] { LIBC_NAMESPACE::regfree(&preg); });
+  ASSERT_DEATH([&preg] { LIBC_NAMESPACE::regexec(&preg, "a", 1, nullptr, 0); },
+               WITH_SIGNAL(-1));
+  // Null check must trigger before matching even on a non-matching input.
+  ASSERT_DEATH([&preg] { LIBC_NAMESPACE::regexec(&preg, "b", 1, nullptr, 0); },
+               WITH_SIGNAL(-1));
+}
+#endif // defined(LIBC_ADD_NULL_CHECKS)



More information about the libc-commits mailing list