Skip to content

Commit e73cccd

Browse files
committed
Merge branch 'PHP-8.1'
* PHP-8.1: Fix #81659: stream_get_contents() may unnecessarily overallocate
2 parents ee38e3a + b082343 commit e73cccd

File tree

2 files changed

+26
-2
lines changed

2 files changed

+26
-2
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
--TEST--
2+
Bug #81659 (stream_get_contents() may unnecessarily overallocate)
3+
--FILE--
4+
<?php
5+
$stream = fopen(__DIR__ . "/81659.txt", "w+");
6+
7+
for ($i = 0; $i < 1024; $i++) {
8+
fwrite($stream, str_repeat("*", 1024));
9+
}
10+
11+
fseek($stream, 1023 * 1024);
12+
13+
$m0 = memory_get_peak_usage();
14+
var_dump(strlen(stream_get_contents($stream)));
15+
$m1 = memory_get_peak_usage();
16+
var_dump($m1 < $m0 + 512 * 1024);
17+
?>
18+
--CLEAN--
19+
<?php
20+
@unlink(__DIR__ . "/81659.txt");
21+
?>
22+
--EXPECT--
23+
int(1024)
24+
bool(true)

main/streams/streams.c

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1506,9 +1506,9 @@ PHPAPI zend_string *_php_stream_copy_to_mem(php_stream *src, size_t maxlen, int
15061506
* result may be inaccurate, as the filter may inflate or deflate the
15071507
* number of bytes that we can read. In order to avoid an upsize followed
15081508
* by a downsize of the buffer, overestimate by the step size (which is
1509-
* 2K). */
1509+
* 8K). */
15101510
if (php_stream_stat(src, &ssbuf) == 0 && ssbuf.sb.st_size > 0) {
1511-
max_len = ssbuf.sb.st_size + step;
1511+
max_len = MAX(ssbuf.sb.st_size - src->position, 0) + step;
15121512
} else {
15131513
max_len = step;
15141514
}

0 commit comments

Comments
 (0)