Skip to content

Fix string offset assignments far beyond the memory limit killing the process - #25786

Open
marc-mabe wants to merge 1 commit into
php:masterfrom
marc-mabe:fix/string-offset-assign-oom
Open

marc-mabe wants to merge 1 commit into
php:masterfrom
marc-mabe:fix/string-offset-assign-oom

Conversation

@marc-mabe

Copy link
Copy Markdown
Contributor

Assigning to a string offset past the end of the string extends the string up to that offset with a non-fallible allocation. The offset is user controlled, so it can ask for any size. Since #25626, such an assignment kills the process once the size exceeds twice memory_limit, without running shutdown functions:

// memory_limit=100M
register_shutdown_function(fn() => print "Shutdown function executed\n");
$s = 'a';
$s[300 << 20] = 'b';

Before

Hard memory limit of 209715200 bytes exhausted (tried to allocate 314576896 bytes) in ... on line 4
(killed, exit code 137; shutdown function not run)

This PR

Fatal error: Allowed memory size of 104857600 bytes exhausted (tried to allocate 314576896 bytes) in ... on line 4
Shutdown function executed

This uses zend_string_fextend() with fallible = true in zend_assign_to_string_offset() of both the VM and the JIT helper. It's the same approach str_repeat() and str_pad() already use for their user controlled sizes. If the memory limit doesn't allow the new size, the string is left untouched and the regular delayed out of memory error is raised.

… process

Assigning to a string offset past the end of the string extends it to the
offset with a non-fallible allocation. As the offset is user controlled,
it can ask for any size, and once that size exceeds the hard memory limit
(twice memory_limit), the process gets killed right away, without running
shutdown functions.

Extend the string with a fallible allocation instead, like str_repeat()
and str_pad() do for their user controlled sizes. If the memory limit
doesn't allow the new size, the string is left untouched and the regular
"Allowed memory size exhausted" fatal error is raised, so shutdown
functions run as usual. This applies to the VM and the JIT helper alike.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant