Commit f6a14fca02a for php

commit f6a14fca02a30b82b57c3f3f5cee19bd373f353c
Author: lacatoire <la.catoire@gmail.com>
Date:   Fri Nov 27 00:12:05 2026 +0800

    Fix stale string metadata in sodium_add() and sodium_increment() (#25775)

    When these functions update an unshared string in place, clear the
    cached hash and UTF-8 validity flag. Otherwise, array lookups may use
    the hash of the old contents and PCRE may skip UTF-8 validation.

    Closes #25775

diff --git a/NEWS b/NEWS
index 495a49d6aa1..7766b7462cc 100644
--- a/NEWS
+++ b/NEWS
@@ -221,6 +221,10 @@ PHP                                                                        NEWS
     throws an Error instead of returning an object with unresolved values.
     (Ilia Alshanetsky)

+- Sodium:
+  . Fixed sodium_add() and sodium_increment() retaining stale string hashes
+    and UTF-8 validity flags. (lacatoire)
+
 - Standard:
   . Fixed bug GH-25474 (version_compare() treats large numeric parts as equal
     on 64-bit Windows). (lazerg, timwolla)
diff --git a/ext/sodium/libsodium.c b/ext/sodium/libsodium.c
index 7c80de9cbf1..5f1c0f10771 100644
--- a/ext/sodium/libsodium.c
+++ b/ext/sodium/libsodium.c
@@ -151,6 +151,9 @@ static void sodium_separate_string(zval *zv) {
 		zend_string *copy = zend_string_init(Z_STRVAL_P(zv), Z_STRLEN_P(zv), 0);
 		Z_TRY_DELREF_P(zv);
 		ZVAL_STR(zv, copy);
+	} else {
+		/* The caller writes into the string: drop its cached hash and UTF-8 flag */
+		zend_string_forget_hash_val(Z_STR_P(zv));
 	}
 }

diff --git a/ext/sodium/tests/in_place_cached_string_state.phpt b/ext/sodium/tests/in_place_cached_string_state.phpt
new file mode 100644
index 00000000000..1ae014d2758
--- /dev/null
+++ b/ext/sodium/tests/in_place_cached_string_state.phpt
@@ -0,0 +1,35 @@
+--TEST--
+sodium_add() and sodium_increment() reset the cached hash and the UTF-8 flag of the string they write
+--EXTENSIONS--
+sodium
+--FILE--
+<?php
+
+$x = 'c';
+$array = ['abc' => 1, 'bbc' => 2];
+
+foreach (['sodium_add', 'sodium_increment'] as $function) {
+    // The hash of "abc" is cached by the lookup, then the bytes change
+    $string = 'ab' . $x;
+    var_dump(isset($array[$string]));
+    $function === 'sodium_add' ? sodium_add($string, "\x01\x00\x00") : sodium_increment($string);
+    var_dump($string === 'bbc', isset($array[$string]));
+}
+
+// The valid UTF-8 flag is set by the match, then the bytes become invalid
+$string = 'ab' . $x;
+var_dump(preg_match('/./u', $string));
+sodium_add($string, "\x00\x00\x8e");
+var_dump(bin2hex($string), preg_match('/./u', $string));
+
+?>
+--EXPECT--
+bool(true)
+bool(true)
+bool(true)
+bool(true)
+bool(true)
+bool(true)
+int(1)
+string(6) "6162f1"
+bool(false)