[COMMITTED 2.41] posix: Fix double free after allocation failure in regcomp and regexec (BZ 34991, CVE-2026-100290)

Aurelien Jarno aurelien@aurel32.net
Sun Nov 15 19:18:12 GMT 2026


From: Adhemerval Zanella <adhemerval.zanella@linaro.org>

The re_dfa_add_node and build_range_exp grow paired arrays with consecutive
reallocs and store the results only after all of them succeed.  If a
later realloc fails, the structure keeps pointers to freed blocks, and
the cleanup frees them again (BZ 31935).  Store each result as soon as
its realloc succeeds, as gnulib commit 9db7e04d15 did for
re_dfa_add_node.

Also, the match_ctx_add_entry frees bkref_ents when growing it fails but
keeps thepointer, so match_ctx_free frees it again.  Keep the old array
instead.

The tst-regcomp-bracket-free now also covers the re_dfa_add_node and
build_range_exp paths.

Checked on x86_64-linux-gnu and i686-linux-gnu.

(cherry picked from commit 2a605083deb2c26e93b3be9943f5139e932c9f96)
---
 posix/Makefile                   |   1 +
 posix/regcomp.c                  |  18 +--
 posix/regex_internal.c           |  22 ++--
 posix/regexec.c                  |   5 +-
 posix/tst-regcomp-bracket-free.c | 215 +++++++++++++++++++++++++++----
 5 files changed, 208 insertions(+), 53 deletions(-)

diff --git a/posix/Makefile b/posix/Makefile
index 5358a3f8c1..7238bee174 100644
--- a/posix/Makefile
+++ b/posix/Makefile
@@ -557,6 +557,7 @@ $(objpfx)tst-regexloc.out: $(gen-locales)
 $(objpfx)tst-rxspencer.out: $(gen-locales)
 $(objpfx)tst-rxspencer-no-utf8.out: $(gen-locales)
 $(objpfx)tst-regcomp-truncated.out: $(gen-locales)
+$(objpfx)tst-regcomp-bracket-free.out: $(gen-locales)
 endif
 
 # If we will use the generic uname implementation, we must figure out what
diff --git a/posix/regcomp.c b/posix/regcomp.c
index 5c486cee56..76c26e5889 100644
--- a/posix/regcomp.c
+++ b/posix/regcomp.c
@@ -2758,19 +2758,17 @@ build_range_exp (const reg_syntax_t syntax,
 	       are NULL if *range_alloc == 0.  */
 	    new_array_start = re_realloc (mbcset->range_starts, wchar_t,
 					  new_nranges);
+	    if (new_array_start != NULL)
+	      mbcset->range_starts = new_array_start;
 	    new_array_end = re_realloc (mbcset->range_ends, wchar_t,
 					new_nranges);
+	    if (new_array_end != NULL)
+	      mbcset->range_ends = new_array_end;
 
 	    if (__glibc_unlikely (new_array_start == NULL
 				  || new_array_end == NULL))
-	      {
-		re_free (new_array_start);
-		re_free (new_array_end);
-		return REG_ESPACE;
-	      }
+	      return REG_ESPACE;
 
-	    mbcset->range_starts = new_array_start;
-	    mbcset->range_ends = new_array_end;
 	    *range_alloc = new_nranges;
 	  }
 
@@ -2990,15 +2988,17 @@ build_range_exp (bitset_t sbcset, re_charset_t *mbcset, Idx *range_alloc,
 	  new_nranges = 2 * mbcset->nranges + 1;
 	  new_array_start = re_realloc (mbcset->range_starts, uint32_t,
 					new_nranges);
+	  if (new_array_start != NULL)
+	    mbcset->range_starts = new_array_start;
 	  new_array_end = re_realloc (mbcset->range_ends, uint32_t,
 				      new_nranges);
+	  if (new_array_end != NULL)
+	    mbcset->range_ends = new_array_end;
 
           if (__glibc_unlikely (new_array_start == NULL
                                 || new_array_end == NULL))
 	    return REG_ESPACE;
 
-	  mbcset->range_starts = new_array_start;
-	  mbcset->range_ends = new_array_end;
 	  *range_alloc = new_nranges;
 	}
 
diff --git a/posix/regex_internal.c b/posix/regex_internal.c
index b3b2b7d58a..6463a676af 100644
--- a/posix/regex_internal.c
+++ b/posix/regex_internal.c
@@ -1430,24 +1430,22 @@ re_dfa_add_node (re_dfa_t *dfa, re_token_t token)
       if (__glibc_unlikely (new_nodes == NULL))
 	return -1;
       dfa->nodes = new_nodes;
+      dfa->nodes_alloc = new_nodes_alloc;
       new_nexts = re_realloc (dfa->nexts, Idx, new_nodes_alloc);
+      if (new_nexts != NULL)
+	dfa->nexts = new_nexts;
       new_indices = re_realloc (dfa->org_indices, Idx, new_nodes_alloc);
+      if (new_indices != NULL)
+	dfa->org_indices = new_indices;
       new_edests = re_realloc (dfa->edests, re_node_set, new_nodes_alloc);
+      if (new_edests != NULL)
+	dfa->edests = new_edests;
       new_eclosures = re_realloc (dfa->eclosures, re_node_set, new_nodes_alloc);
+      if (new_eclosures != NULL)
+	dfa->eclosures = new_eclosures;
       if (__glibc_unlikely (new_nexts == NULL || new_indices == NULL
 			    || new_edests == NULL || new_eclosures == NULL))
-	{
-	   re_free (new_nexts);
-	   re_free (new_indices);
-	   re_free (new_edests);
-	   re_free (new_eclosures);
-	   return -1;
-	}
-      dfa->nexts = new_nexts;
-      dfa->org_indices = new_indices;
-      dfa->edests = new_edests;
-      dfa->eclosures = new_eclosures;
-      dfa->nodes_alloc = new_nodes_alloc;
+	return -1;
     }
   dfa->nodes[dfa->nodes_len] = token;
   dfa->nodes[dfa->nodes_len].constraint = 0;
diff --git a/posix/regexec.c b/posix/regexec.c
index fc1310025f..ecff734788 100644
--- a/posix/regexec.c
+++ b/posix/regexec.c
@@ -4142,10 +4142,7 @@ match_ctx_add_entry (re_match_context_t *mctx, Idx node, Idx str_idx, Idx from,
       new_entry = re_realloc (mctx->bkref_ents, struct re_backref_cache_entry,
 			      mctx->abkref_ents * 2);
       if (__glibc_unlikely (new_entry == NULL))
-	{
-	  re_free (mctx->bkref_ents);
-	  return REG_ESPACE;
-	}
+	return REG_ESPACE;
       mctx->bkref_ents = new_entry;
       memset (mctx->bkref_ents + mctx->nbkref_ents, '\0',
 	      sizeof (struct re_backref_cache_entry) * mctx->abkref_ents);
diff --git a/posix/tst-regcomp-bracket-free.c b/posix/tst-regcomp-bracket-free.c
index 3c091d8c44..1feb6cb3b9 100644
--- a/posix/tst-regcomp-bracket-free.c
+++ b/posix/tst-regcomp-bracket-free.c
@@ -1,4 +1,4 @@
-/* Test regcomp bracket parsing with injected allocation failures (bug 33185).
+/* Test regcomp parsing with injected allocation failures (bug 33185).
    Copyright (C) 2025 Free Software Foundation, Inc.
    This file is part of the GNU C Library.
 
@@ -19,15 +19,25 @@
 /* This test invokes regcomp multiple times, failing one memory
    allocation in each call.  The function call should fail with
    REG_ESPACE (or succeed if it can recover from the allocation
-   failure).  Previously, there was double-free bug.  */
+   failure).  Previously, there were double-free bugs on the partial
+   allocation-failure paths of parse_bracket_exp (bug 33185),
+   re_dfa_add_node and build_range_exp (bugs 31935 and 34991).
+
+   To detect these deterministically, the allocator is interposed and
+   every pointer it hands out is tracked while a regcomp call is in
+   progress.  */
 
 #include <errno.h>
+#include <locale.h>
 #include <regex.h>
+#include <stdbool.h>
+#include <stddef.h>
 #include <stdio.h>
 #include <string.h>
 #include <support/check.h>
 #include <support/namespace.h>
 #include <support/support.h>
+#include <support/xdlfcn.h>
 
 /* Data structure allocated via MAP_SHARED, so that writes from the
    subprocess are visible.  */
@@ -39,8 +49,12 @@ struct shared_data
   /* If this number is reached, one allocation fails.  */
   volatile unsigned int failing_allocation;
 
-  /* The subprocess stores the expected name here.  */
-  char name[100];
+  /* Incremented by the free interposer when a double free or a free of
+     a stale pointer is detected during a tracked call.  */
+  volatile unsigned int corruption;
+
+  /* Set nonzero if the tracking registry overflows.  */
+  volatile unsigned int overflow;
 };
 
 /* Allocation count in shared mapping.  */
@@ -60,7 +74,81 @@ fail_this_allocation (void)
     return false;
 }
 
-/* Failure-injecting wrappers for allocation functions used by glibc.  */
+/* While TRACKING is set, every pointer returned by the allocator is recorded,
+   and free is validated against the recorded set.  The registry itself never
+   allocates.  */
+enum { HEAP_MAX = 8192 };
+static void *heap_ptr[HEAP_MAX];
+static bool heap_live[HEAP_MAX];
+static size_t heap_count;
+static bool tracking;
+
+static void *(*real_malloc) (size_t);
+static void *(*real_calloc) (size_t, size_t);
+static void *(*real_realloc) (void *, size_t);
+static void (*real_free) (void *);
+
+static void __attribute__ ((constructor))
+resolve_allocator (void)
+{
+  real_malloc = xdlsym (RTLD_NEXT, "malloc");
+  real_calloc = xdlsym (RTLD_NEXT, "calloc");
+  real_realloc = xdlsym (RTLD_NEXT, "realloc");
+  real_free = xdlsym (RTLD_NEXT, "free");
+}
+
+static void
+heap_track_reset (void)
+{
+  heap_count = 0;
+}
+
+static void
+heap_record_alloc (void *p)
+{
+  if (p == NULL)
+    return;
+  for (size_t i = 0; i < heap_count; ++i)
+    if (heap_ptr[i] == p)
+      {
+	heap_live[i] = true;
+	return;
+      }
+  if (heap_count < HEAP_MAX)
+    {
+      heap_ptr[heap_count] = p;
+      heap_live[heap_count] = true;
+      ++heap_count;
+    }
+  else if (shared != NULL)
+    shared->overflow = shared->overflow + 1;
+}
+
+/* Result of validating a free against the tracking registry.  */
+enum heap_free_status
+{
+  HEAP_FREE_OK,		/* P was live and is now marked released.  */
+  HEAP_FREE_DOUBLE,	/* P was already released (double or stale free).  */
+  HEAP_FREE_UNTRACKED,	/* P is not tracked (allocated before tracking).  */
+};
+
+/* Mark P as released and report whether the free is valid.  */
+static enum heap_free_status
+heap_record_free (void *p)
+{
+  for (size_t i = 0; i < heap_count; ++i)
+    if (heap_ptr[i] == p)
+      {
+	if (!heap_live[i])
+	  return HEAP_FREE_DOUBLE;
+	heap_live[i] = false;
+	return HEAP_FREE_OK;
+      }
+  return HEAP_FREE_UNTRACKED;
+}
+
+/* Failure-injecting, tracking wrappers for the allocation functions
+   used by glibc.  */
 
 void *
 malloc (size_t size)
@@ -70,8 +158,10 @@ malloc (size_t size)
       errno = ENOMEM;
       return NULL;
     }
-  extern __typeof (malloc) __libc_malloc;
-  return __libc_malloc (size);
+  void *p = real_malloc (size);
+  if (tracking)
+    heap_record_alloc (p);
+  return p;
 }
 
 void *
@@ -82,8 +172,10 @@ calloc (size_t a, size_t b)
       errno = ENOMEM;
       return NULL;
     }
-  extern __typeof (calloc) __libc_calloc;
-  return __libc_calloc (a, b);
+  void *p = real_calloc (a, b);
+  if (tracking)
+    heap_record_alloc (p);
+  return p;
 }
 
 void *
@@ -94,8 +186,33 @@ realloc (void *ptr, size_t size)
       errno = ENOMEM;
       return NULL;
     }
-  extern __typeof (realloc) __libc_realloc;
-  return __libc_realloc (ptr, size);
+  void *p = real_realloc (ptr, size);
+  if (tracking && p != NULL)
+    {
+      if (ptr != NULL && p != ptr)
+	heap_record_free (ptr);
+      heap_record_alloc (p);
+    }
+  return p;
+}
+
+void
+free (void *ptr)
+{
+  if (ptr == NULL)
+    return;
+  if (tracking)
+    {
+      if (heap_record_free (ptr) == HEAP_FREE_DOUBLE)
+	{
+	  /* Record it and drop the free so the heap is not corrupted
+	     further.  */
+	  if (shared != NULL)
+	    shared->corruption = shared->corruption + 1;
+	  return;
+	}
+    }
+  real_free (ptr);
 }
 
 /* No-op subprocess to verify that support_isolate_in_subprocess does
@@ -105,6 +222,27 @@ no_op (void *ignored)
 {
 }
 
+/* regcomp flags for the pattern under test.  */
+static int test_cflags;
+
+static int
+compile_tracked (const char *regexp)
+{
+  regex_t reg;
+  heap_track_reset ();
+  shared->corruption = 0;
+  shared->overflow = 0;
+  tracking = true;
+  int ret = regcomp (&reg, regexp, test_cflags);
+  tracking = false;
+  if (ret == 0)
+    regfree (&reg);
+  TEST_COMPARE (shared->corruption, 0);
+  /* A registry overflow means tracking was incomplete.  */
+  TEST_COMPARE (shared->overflow, 0);
+  return ret;
+}
+
 /* Perform a regcomp call in a subprocess.  Used to count its
    allocations.  */
 static void
@@ -114,8 +252,7 @@ initialize (void *regexp1)
 
   shared->allocation_count = 0;
 
-  regex_t reg;
-  TEST_COMPARE (regcomp (&reg, regexp, 0), 0);
+  TEST_COMPARE (compile_tracked (regexp), 0);
 }
 
 /* Perform regcomp in a subprocess with fault injection.  */
@@ -125,8 +262,7 @@ test_in_subprocess (void *regexp1)
   const char *regexp = regexp1;
   unsigned int inject_at = shared->failing_allocation;
 
-  regex_t reg;
-  int ret = regcomp (&reg, regexp, 0);
+  int ret = compile_tracked (regexp);
 
   if (ret != 0)
     {
@@ -137,27 +273,25 @@ test_in_subprocess (void *regexp1)
     }
 }
 
-static int
-do_test (void)
+static void
+run_pattern (const char *regexp, int cflags, const char *locale)
 {
-  char regexp[] = "[:alpha:]";
-
-  shared = support_shared_allocate (sizeof (*shared));
+  test_cflags = cflags;
 
-  /* Disable fault injection.  */
+  /* Disable fault injection before switching locale, setlocale must not
+     see an injected failure.  */
   shared->failing_allocation = ~0U;
+  xsetlocale (LC_ALL, locale == NULL ? "C" : locale);
 
-  support_isolate_in_subprocess (no_op, NULL);
-  TEST_COMPARE (shared->allocation_count, 0);
-
-  support_isolate_in_subprocess (initialize, regexp);
+  /* Count the allocations of a successful call.  */
+  support_isolate_in_subprocess (initialize, (void *) regexp);
 
   /* The number of allocations in the successful case, plus some
      slack.  Once the number of expected allocations is exceeded,
      injecting further failures does not make a difference.  */
   unsigned int maximum_allocation_count = shared->allocation_count;
-  printf ("info: successful call performs %u allocations\n",
-          maximum_allocation_count);
+  printf ("info: pattern \"%s\" (locale %s) performs %u allocations\n",
+	  regexp, locale == NULL ? "C" : locale, maximum_allocation_count);
   maximum_allocation_count += 10;
 
   for (unsigned int inject_at = 0; inject_at <= maximum_allocation_count;
@@ -165,8 +299,33 @@ do_test (void)
     {
       shared->allocation_count = 0;
       shared->failing_allocation = inject_at;
-      support_isolate_in_subprocess (test_in_subprocess, regexp);
+      support_isolate_in_subprocess (test_in_subprocess, (void *) regexp);
     }
+}
+
+static int
+do_test (void)
+{
+  shared = support_shared_allocate (sizeof (*shared));
+
+  /* Disable fault injection.  */
+  shared->failing_allocation = ~0U;
+
+  support_isolate_in_subprocess (no_op, NULL);
+  TEST_COMPARE (shared->allocation_count, 0);
+
+  /* Bracket expression parsing (parse_bracket_exp, bug 33185).  */
+  run_pattern ("[:alpha:]", 0, NULL);
+
+  /* NFA node array growth in re_dfa_add_node (bug 34991).  The initial
+     nodes_alloc is the pattern length + 1; the interval duplicates the
+     'a' node 64 times, so the node arrays are grown several times.  */
+  run_pattern ("a{64}", REG_EXTENDED, NULL);
+
+  /* Range array growth in build_range_exp (bugs 31935 and 34991).  A
+     multibyte locale stores the ranges in the mbcset arrays, and
+     multiple ranges force the growth realloc.  */
+  run_pattern ("[a-bc-de-fg-hi-jk-lm-no-pq-rs-t]", 0, "en_US.UTF-8");
 
   support_shared_free (shared);
 
-- 
2.53.0



More information about the Libc-stable mailing list