From a8ec59cf33373b81c62bbb62c6f44c53c1584390 Mon Sep 17 00:00:00 2001 From: Florian Engelhardt Date: Wed, 18 Nov 2026 11:31:10 +0100 Subject: [PATCH 1/2] mbstring: Save the write offset before reallocating the conversion buffer --- ext/mbstring/libmbfl/mbfl/mbfl_encoding.h | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ext/mbstring/libmbfl/mbfl/mbfl_encoding.h b/ext/mbstring/libmbfl/mbfl/mbfl_encoding.h index 594e2f3ebd2a..224fd7b82606 100644 --- a/ext/mbstring/libmbfl/mbfl/mbfl_encoding.h +++ b/ext/mbstring/libmbfl/mbfl/mbfl_encoding.h @@ -168,6 +168,7 @@ static inline zend_result mb_convert_buf_ensure(mb_convert_buf *buf, unsigned ch if ((size_t)(*limit - *out) < needed) { size_t oldsize = *limit - (unsigned char*)ZSTR_VAL((buf)->str); size_t growth = MAX(oldsize >> 1, needed); + size_t out_offset = *out - (unsigned char*)ZSTR_VAL((buf)->str); zend_string *newstr = safe_ferealloc((buf)->str, 1, oldsize, zend_string_safe_offset(1, oldsize, growth), /* fallible */ true); if (!newstr) { /* An earlier growth may have moved the buffer. */ @@ -177,7 +178,7 @@ static inline zend_result mb_convert_buf_ensure(mb_convert_buf *buf, unsigned ch } /* GCC can't see that allocation fails if growth is too large, so make it explicit. */ ZEND_ASSERT(growth <= ZSTR_MAX_LEN); - *out = (unsigned char*)ZSTR_VAL(newstr) + (*out - (unsigned char*)ZSTR_VAL((buf)->str)); + *out = (unsigned char*)ZSTR_VAL(newstr) + out_offset; *limit = (unsigned char*)ZSTR_VAL(newstr) + oldsize + growth; (buf)->str = newstr; } From 745e9bf9f3ba9d8a24e1e3738e710297386240d4 Mon Sep 17 00:00:00 2001 From: Florian Engelhardt Date: Wed, 25 Nov 2026 08:39:45 +0100 Subject: [PATCH 2/2] Comment realloc moving the buffer --- ext/mbstring/libmbfl/mbfl/mbfl_encoding.h | 1 + 1 file changed, 1 insertion(+) diff --git a/ext/mbstring/libmbfl/mbfl/mbfl_encoding.h b/ext/mbstring/libmbfl/mbfl/mbfl_encoding.h index 224fd7b82606..9a2ab1a2d0c5 100644 --- a/ext/mbstring/libmbfl/mbfl/mbfl_encoding.h +++ b/ext/mbstring/libmbfl/mbfl/mbfl_encoding.h @@ -168,6 +168,7 @@ static inline zend_result mb_convert_buf_ensure(mb_convert_buf *buf, unsigned ch if ((size_t)(*limit - *out) < needed) { size_t oldsize = *limit - (unsigned char*)ZSTR_VAL((buf)->str); size_t growth = MAX(oldsize >> 1, needed); + /* Save offset before realloc, which may move the buffer, subtracting invalidated pointers afterwards is UB */ size_t out_offset = *out - (unsigned char*)ZSTR_VAL((buf)->str); zend_string *newstr = safe_ferealloc((buf)->str, 1, oldsize, zend_string_safe_offset(1, oldsize, growth), /* fallible */ true); if (!newstr) {