diff --git a/Zend/tests/oom_str_offset_assign.phpt b/Zend/tests/oom_str_offset_assign.phpt new file mode 100644 index 000000000000..41e9d3358ec0 --- /dev/null +++ b/Zend/tests/oom_str_offset_assign.phpt @@ -0,0 +1,20 @@ +--TEST-- +OOM: string offset assignment beyond the memory limit +--INI-- +memory_limit=100M +--FILE-- + +--EXPECTF-- +Fatal error: Allowed memory size of 104857600 bytes exhausted %S(tried to allocate %d bytes) in %s on line 10 +Shutdown function executed diff --git a/Zend/zend_execute.c b/Zend/zend_execute.c index 7d270c3e249d..da85d3f0eaac 100644 --- a/Zend/zend_execute.c +++ b/Zend/zend_execute.c @@ -2169,9 +2169,18 @@ static zend_never_inline void zend_assign_to_string_offset(zval *str, zval *dim, } if ((size_t)offset >= ZSTR_LEN(s)) { - /* Extend string if needed */ + /* Extend string if needed. The offset is user controlled, so allocate + * fallibly: if the memory limit doesn't allow the new size, the string + * is left untouched and an out of memory error is raised. */ zend_long old_len = ZSTR_LEN(s); - ZVAL_NEW_STR(str, zend_string_extend(s, (size_t)offset + 1, 0)); + zend_string *extended = zend_string_fextend(s, (size_t)offset + 1, 0, /* fallible */ true); + if (UNEXPECTED(!extended)) { + if (UNEXPECTED(RETURN_VALUE_USED(opline))) { + ZVAL_UNDEF(EX_VAR(opline->result.var)); + } + return; + } + ZVAL_NEW_STR(str, extended); memset(Z_STRVAL_P(str) + old_len, ' ', offset - old_len); Z_STRVAL_P(str)[offset+1] = 0; } else { diff --git a/ext/opcache/jit/zend_jit_helpers.c b/ext/opcache/jit/zend_jit_helpers.c index d9b91d299f59..c8ccd513a19d 100644 --- a/ext/opcache/jit/zend_jit_helpers.c +++ b/ext/opcache/jit/zend_jit_helpers.c @@ -1474,9 +1474,18 @@ static zend_never_inline void zend_assign_to_string_offset(zval *str, zval *dim, } if ((size_t)offset >= ZSTR_LEN(s)) { - /* Extend string if needed */ + /* Extend string if needed. The offset is user controlled, so allocate + * fallibly: if the memory limit doesn't allow the new size, the string + * is left untouched and an out of memory error is raised. */ zend_long old_len = ZSTR_LEN(s); - ZVAL_NEW_STR(str, zend_string_extend(s, (size_t)offset + 1, 0)); + zend_string *extended = zend_string_fextend(s, (size_t)offset + 1, 0, /* fallible */ true); + if (UNEXPECTED(!extended)) { + if (result) { + ZVAL_UNDEF(result); + } + return; + } + ZVAL_NEW_STR(str, extended); memset(Z_STRVAL_P(str) + old_len, ' ', offset - old_len); Z_STRVAL_P(str)[offset+1] = 0; } else {