Commit 0fa37f1c93d for php

commit 0fa37f1c93d6736fd591352adcc4037fee61de6e
Author: hohphu8 <kodoku169@gmail.com>
Date:   Sun Nov 29 20:07:31 2026 +0700

    ext/intl: Fix UAF in MessageFormatter::format() on re-entrant setPattern()

    In umsg_format_helper() (ext/intl/msgformat/msgformat_helpers.cpp), local
    pointers mf (mfo->mf_data.umsgf) and types (mfo->mf_data.arg_types) are
    cached before iterating over arguments. If an argument's __toString() calls
    $mf->setPattern(), msgfmt_set_pattern() destroys both mfo->mf_data.umsgf and
    mfo->mf_data.arg_types (and resets tz_set), causing a use-after-free on the
    next iteration ("ht is already destroyed" assertion failure in debug builds)
    and when calling mf->format() (even with a single argument). Exceptions
    thrown from __toString() were also not checked before continuing argument
    processing or returning from msgfmt_do_format().

    Return cached mfo->mf_data.arg_types directly in umsg_get_types(), re-fetch
    types per iteration, reload mfo->mf_data.umsgf and run umsg_set_timezone()
    after the loop, and bail out when EG(exception) is set (including
    RETURN_THROWS() in msgfmt_do_format()).

    Added a regression test covering single-argument (mf UAF) and
    multi-argument (types + mf UAF) re-entrant setPattern(), incompatible
    pattern mutation, and exceptions thrown from __toString().

    Co-authored-by: David Carlier <devnexen@gmail.com>

    Close GH-25900

diff --git a/NEWS b/NEWS
index ef185000e3e..a785efaa530 100644
--- a/NEWS
+++ b/NEWS
@@ -125,6 +125,9 @@ PHP                                                                        NEWS
   . Fixed NULL pointer dereference in Locale::parseLocale() and
     Locale::getAllVariants() with delimiter-only private or variant subtags.
     (Ho Hoang Phu)
+  . Fixed use-after-free in MessageFormatter::format() when the __toString()
+    of an argument calls MessageFormatter::setPattern(). (Ho Hoang Phu,
+    David Carlier)

 - JSON:
   . Fixed json_decode() and json_validate() error messages. (lacatoire)
diff --git a/ext/intl/msgformat/msgformat.c b/ext/intl/msgformat/msgformat.c
index 51643d86d45..8b6bc97daad 100644
--- a/ext/intl/msgformat/msgformat.c
+++ b/ext/intl/msgformat/msgformat.c
@@ -70,20 +70,25 @@ static int msgfmt_ctor(INTERNAL_FUNCTION_PARAMETERS, zend_error_handling *error_
 	}
 #endif

-	if ((mfo)->mf_data.orig_format) {
-		msgformat_data_free(&mfo->mf_data);
-	}
-
-	(mfo)->mf_data.orig_format = estrndup(pattern, pattern_len);
-	(mfo)->mf_data.orig_format_len = pattern_len;
-
 	/* Create an ICU message formatter. */
-	MSG_FORMAT_OBJECT(mfo) = umsg_open(spattern, spattern_len, locale, &parse_error, &INTL_DATA_ERROR_CODE(mfo));
+	UMessageFormat *umsgf = umsg_open(spattern, spattern_len, locale, &parse_error, &INTL_DATA_ERROR_CODE(mfo));

 	if(spattern) {
 		efree(spattern);
 	}

+	if (U_SUCCESS(INTL_DATA_ERROR_CODE(mfo))) {
+		if ((mfo)->mf_data.orig_format) {
+			msgformat_data_free(&mfo->mf_data);
+		}
+		(mfo)->mf_data.orig_format = estrndup(pattern, pattern_len);
+		(mfo)->mf_data.orig_format_len = pattern_len;
+		(mfo)->mf_data.tz_set = 0;
+		MSG_FORMAT_OBJECT(mfo) = umsgf;
+	} else if (umsgf) {
+		umsg_close(umsgf);
+	}
+
 	if (INTL_DATA_ERROR_CODE( mfo ) == U_PATTERN_SYNTAX_ERROR) {
 		char *msg = NULL;
 		smart_str parse_error_str;
diff --git a/ext/intl/msgformat/msgformat_format.c b/ext/intl/msgformat/msgformat_format.c
index 46a364c5d3a..d948c64bc03 100644
--- a/ext/intl/msgformat/msgformat_format.c
+++ b/ext/intl/msgformat/msgformat_format.c
@@ -36,6 +36,13 @@ static void msgfmt_do_format(MessageFormatter_object *mfo, zval *args, zval *ret

 	umsg_format_helper(mfo, Z_ARRVAL_P(args), &formatted, &formatted_len);

+	if (UNEXPECTED(EG(exception))) {
+		if (formatted) {
+			efree(formatted);
+		}
+		RETURN_THROWS();
+	}
+
 	if (U_FAILURE(INTL_DATA_ERROR_CODE(mfo))) {
 		if (formatted) {
 			efree(formatted);
diff --git a/ext/intl/msgformat/msgformat_helpers.cpp b/ext/intl/msgformat/msgformat_helpers.cpp
index 58e2a96bf23..62388dd91f6 100644
--- a/ext/intl/msgformat/msgformat_helpers.cpp
+++ b/ext/intl/msgformat/msgformat_helpers.cpp
@@ -284,7 +284,16 @@ static HashTable *umsg_parse_format(MessageFormatter_object *mfo,
 static HashTable *umsg_get_types(MessageFormatter_object *mfo,
 								 intl_error& err)
 {
+	if (mfo->mf_data.arg_types) {
+		return mfo->mf_data.arg_types;
+	}
+
 	MessageFormat *mf = (MessageFormat *)mfo->mf_data.umsgf;
+	if (!mf) {
+		intl_errors_set(&err, U_INVALID_STATE_ERROR,
+			"MessageFormatter is not initialized", 0);
+		return NULL;
+	}

 	const MessagePattern mp = MessageFormatAdapter::phpGetMessagePattern(mf);

@@ -369,7 +378,7 @@ U_CFUNC void umsg_format_helper(MessageFormatter_object *mfo,
 	int arg_count = zend_hash_num_elements(args);
 	std::vector<Formattable> fargs;
 	std::vector<UnicodeString> farg_names;
-	MessageFormat *mf = (MessageFormat *)mfo->mf_data.umsgf;
+	MessageFormat *mf;
 	HashTable *types;
 	intl_error& err = INTL_DATA_ERROR(mfo);

@@ -377,9 +386,9 @@ U_CFUNC void umsg_format_helper(MessageFormatter_object *mfo,
 		return;
 	}

-	types = umsg_get_types(mfo, err);
-
-	umsg_set_timezone(mfo, err);
+	if (!umsg_get_types(mfo, err)) {
+		return;
+	}

 	fargs.resize(arg_count);
 	farg_names.resize(arg_count);
@@ -397,7 +406,12 @@ U_CFUNC void umsg_format_helper(MessageFormatter_object *mfo,
 		UnicodeString& key = farg_names[argNum];
 		Formattable::Type argType = Formattable::kObject, //unknown
 						  *storedArgType = NULL;
-		if (!U_SUCCESS(err.code)) {
+		if (!U_SUCCESS(err.code) || UNEXPECTED(EG(exception))) {
+			break;
+		}
+		/* Re-fetch types in case a prior argument conversion mutated the formatter */
+		types = umsg_get_types(mfo, err);
+		if (!types) {
 			break;
 		}
 		/* Process key and retrieve type */
@@ -448,6 +462,10 @@ U_CFUNC void umsg_format_helper(MessageFormatter_object *mfo,
 					 * as a result of that.
 					 */
 					str = zval_get_tmp_string(elem, &tmp_str);
+					if (UNEXPECTED(EG(exception))) {
+						zend_tmp_string_release(tmp_str);
+						break;
+					}

 					UnicodeString *text = new UnicodeString();
 					intl_stringFromChar(*text,
@@ -590,10 +608,22 @@ U_CFUNC void umsg_format_helper(MessageFormatter_object *mfo,
 		argNum++;
 	} ZEND_HASH_FOREACH_END(); // visiting each argument

+	if (U_FAILURE(err.code) || UNEXPECTED(EG(exception))) {
+		return;
+	}
+
+	umsg_set_timezone(mfo, err);
 	if (U_FAILURE(err.code)) {
 		return;
 	}

+	mf = (MessageFormat *)mfo->mf_data.umsgf;
+	if (!mf) {
+		intl_errors_set(&err, U_INVALID_STATE_ERROR,
+			"MessageFormatter is not initialized", 0);
+		return;
+	}
+
 	UnicodeString resultStr;
 	FieldPosition fieldPosition(0);

diff --git a/ext/intl/tests/msgfmt_ctor_reinit_failure.phpt b/ext/intl/tests/msgfmt_ctor_reinit_failure.phpt
new file mode 100644
index 00000000000..31aa586892e
--- /dev/null
+++ b/ext/intl/tests/msgfmt_ctor_reinit_failure.phpt
@@ -0,0 +1,42 @@
+--TEST--
+MessageFormatter::__construct() failure on an existing object keeps a usable state
+--EXTENSIONS--
+intl
+--INI--
+date.timezone=Asia/Tokyo
+--FILE--
+<?php
+
+$mf = new MessageFormatter('en_US', '{0}');
+try {
+    $mf->__construct('en_US', '{0');
+} catch (Throwable $e) {
+    echo $e::class, PHP_EOL;
+}
+var_dump($mf->getPattern());
+var_dump($mf->format(['x']));
+
+$mf = (new ReflectionClass(MessageFormatter::class))->newInstanceWithoutConstructor();
+try {
+    $mf->__construct('en_US', '{0');
+} catch (Throwable $e) {
+    echo $e::class, PHP_EOL;
+}
+try {
+    $mf->format(['x']);
+} catch (Throwable $e) {
+    echo $e::class, ': ', $e->getMessage(), PHP_EOL;
+}
+
+$mf = new MessageFormatter('en_US', '{0,time,long}');
+$first = $mf->format([0]);
+$mf->__construct('en_US', '[{0,time,long}]');
+var_dump($mf->format([0]) === '[' . $first . ']');
+?>
+--EXPECT--
+IntlException
+string(3) "{0}"
+string(1) "x"
+IntlException
+Error: Found unconstructed MessageFormatter
+bool(true)
diff --git a/ext/intl/tests/msgfmt_format_reentrant_setpattern.phpt b/ext/intl/tests/msgfmt_format_reentrant_setpattern.phpt
new file mode 100644
index 00000000000..e42bbeb9ba2
--- /dev/null
+++ b/ext/intl/tests/msgfmt_format_reentrant_setpattern.phpt
@@ -0,0 +1,64 @@
+--TEST--
+MessageFormatter::format() handles re-entrant setPattern() and exceptions in __toString()
+--EXTENSIONS--
+intl
+--FILE--
+<?php
+
+// Case 1: single argument - __toString() frees mf via setPattern() before mf->format()
+$mf0 = new MessageFormatter('en_US', '{0}');
+$o0 = new class($mf0) {
+    public function __construct(private MessageFormatter $mf) {}
+    public function __toString(): string {
+        $this->mf->setPattern('[{0}]');
+        return 'solo';
+    }
+};
+var_dump($mf0->format([$o0]));
+
+// Case 2: multiple arguments - __toString() destroys cached types and mf via setPattern()
+$mf = new MessageFormatter('en_US', '{0} {1}');
+$o1 = new class($mf) {
+    public function __construct(private MessageFormatter $mf) {}
+    public function __toString(): string {
+        $this->mf->setPattern('{0} - {1}');
+        return 'hello';
+    }
+};
+var_dump($mf->format([$o1, 'world']));
+
+// Case 3: __toString() mutates pattern to incompatible arg type
+$mf2 = new MessageFormatter('en_US', '{0} {1}');
+$o2 = new class($mf2) {
+    public function __construct(private MessageFormatter $mf) {}
+    public function __toString(): string {
+        $this->mf->setPattern('{0,number} {1}');
+        return 'hi';
+    }
+};
+var_dump($mf2->format([$o2, 'world']));
+
+// Case 4: __toString() throws an exception (stops processing remaining args)
+$mf3 = new MessageFormatter('en_US', '{0} {1}');
+$o3a = new class {
+    public function __toString(): string {
+        throw new RuntimeException('boom');
+    }
+};
+$o3b = new class {
+    public function __toString(): string {
+        echo "should not run\n";
+        return 'later';
+    }
+};
+try {
+    $mf3->format([$o3a, $o3b]);
+} catch (RuntimeException $e) {
+    echo "caught: " . $e->getMessage() . "\n";
+}
+?>
+--EXPECT--
+string(6) "[solo]"
+string(13) "hello - world"
+bool(false)
+caught: boom