[php-src] master: Fix mbregex search state after cache invalidation

Matthias Goergens via Yuya Hamada <[email protected]> Sat, 1 Aug 2026 03:02:28 +0000
Newsgroups gmane.comp.php.cvs.general
Message-ID <[email protected]>
Author: Matthias Goergens (matthiasgoergens)
Committer: Yuya Hamada (youkidearitai)
Date: 2026-08-01T12:01:36+09:00

Commit: https://github.com/php/php-src/commit/03a71535c30a441868fcd82256710041b5ce42d2
Raw diff: https://github.com/php/php-src/commit/03a71535c30a441868fcd82256710041b5ce42d2.diff

Fix mbregex search state after cache invalidation

Closes GH-22954

Changed paths:
  A  ext/mbstring/tests/gh21036.phpt
  M  NEWS
  M  ext/mbstring/php_mbregex.c


Diff:

diff --git a/NEWS b/NEWS
index 4364d69650e5..46adc0e74d17 100644
--- a/NEWS
+++ b/NEWS
@@ -91,6 +91,8 @@ PHP                                                                        NEWS
 - MBString:
   . Fixed bug GH-22779 (mb_strrpos() returns the wrong position for a negative
     offset in a non-UTF-8 encoding). (Eyüp Can Akman)
+  . Fixed bug GH-21036 (mb_ereg_search_getregs() crashes after mb_eregi()
+    invalidates the regex cache). (Matthias Goergens)
 
 - Sockets:
   . Fixed socket_set_option() validation error messages for UDP_SEGMENT and
diff --git a/ext/mbstring/php_mbregex.c b/ext/mbstring/php_mbregex.c
index 1043c4a46eb2..47297a9b15cd 100644
--- a/ext/mbstring/php_mbregex.c
+++ b/ext/mbstring/php_mbregex.c
@@ -479,6 +479,10 @@ static php_mb_regex_t *php_mbregex_compile_pattern(const char *pattern, size_t p
 		if (rc == MBREX(search_re)) {
 			/* reuse the new rc? see bug #72399 */
 			MBREX(search_re) = NULL;
+			if (MBREX(search_regs) != NULL) {
+				onig_region_free(MBREX(search_regs), 1);
+				MBREX(search_regs) = NULL;
+			}
 		}
 		zend_hash_str_update_ptr(&MBREX(ht_rc), (char *)pattern, patlen, retval);
 	} else {
diff --git a/ext/mbstring/tests/gh21036.phpt b/ext/mbstring/tests/gh21036.phpt
new file mode 100644
index 000000000000..60c63038510c
--- /dev/null
+++ b/ext/mbstring/tests/gh21036.phpt
@@ -0,0 +1,17 @@
+--TEST--
+GH-21036 (mb_ereg_search_getregs() after regex cache invalidation)
+--EXTENSIONS--
+mbstring
+--FILE--
+<?php
+error_reporting(E_ALL & ~E_DEPRECATED);
+
+$pattern = '(?<name>a)';
+mb_ereg_search_init('a', $pattern);
+mb_ereg_search_pos();
+mb_eregi($pattern, 'a');
+
+var_dump(mb_ereg_search_getregs());
+?>
+--EXPECT--
+bool(false)