Fix GH-17650: realloc with size 0 in user_filters.c

If the returned buffer string is of length 0, then a realloc can happen
with length 0. However, the behaviour is implementation-defined.
From 7.20.3.1 of C11 spec:

> If the size of the space requested is zero, the behavior is
> implementation-defined: either a null pointer is returned,
> or the behavior is as if the size were some nonzero value,
> except that the returned pointer shall not be used to access an object

This is problematic for the test case on my system as it returns NULL,
causing a memleak and later using it in memcpy causing UB.
The bucket code is not prepared to handle a NULL pointer.
To solve this, we use MAX to clamp the size to 1 at the least.

Closes GH-17656.
This commit is contained in:
Niels Dossche 2025-01-31 20:03:25 +01:00
parent 00d4390ea1
commit fd5d6ad5bd
No known key found for this signature in database
GPG key ID: B8A8AD166DF0E2E5
3 changed files with 39 additions and 1 deletions

3
NEWS
View file

@ -31,6 +31,9 @@ PHP NEWS
. Partially fixed bug GH-17387 (Trivial crash in phpdbg lexer). (nielsdos)
. Fix memory leak in phpdbg calling registered function. (nielsdos)
- Streams:
. Fixed bug GH-17650 (realloc with size 0 in user_filters.c). (nielsdos)
13 Feb 2025, PHP 8.3.17
- Core:

View file

@ -0,0 +1,35 @@
--TEST--
GH-17650 (realloc with size 0 in user_filters.c)
--FILE--
<?php
class testfilter extends php_user_filter {
function filter($in, $out, &$consumed, $closing): int {
while ($bucket = stream_bucket_make_writeable($in)) {
$bucket->data = '';
$consumed += strlen($bucket->data);
stream_bucket_append($out, $bucket);
}
return PSFS_PASS_ON;
}
}
stream_filter_register('testfilter','testfilter');
$text = "Hello There!";
$fp = fopen('php://memory', 'w+');
fwrite($fp, $text);
rewind($fp);
stream_filter_append($fp, 'testfilter', STREAM_FILTER_READ, 'testuserfilter');
while ($x = fgets($fp)) {
var_dump($x);
}
fclose($fp);
echo "Done\n";
?>
--EXPECT--
Done

View file

@ -398,7 +398,7 @@ static void php_stream_bucket_attach(int append, INTERNAL_FUNCTION_PARAMETERS)
bucket = php_stream_bucket_make_writeable(bucket);
}
if (bucket->buflen != Z_STRLEN_P(pzdata)) {
bucket->buf = perealloc(bucket->buf, Z_STRLEN_P(pzdata), bucket->is_persistent);
bucket->buf = perealloc(bucket->buf, MAX(Z_STRLEN_P(pzdata), 1), bucket->is_persistent);
bucket->buflen = Z_STRLEN_P(pzdata);
}
memcpy(bucket->buf, Z_STRVAL_P(pzdata), bucket->buflen);