Skip to content

Commit

Permalink
Fix phpGH-13071: Copying large files using mmap-able source streams m…
Browse files Browse the repository at this point in the history
…ay exhaust available memory and fail

Commit 5cbe5a5 disabled chunking for all writes to streams. However,
user streams have a callback where code is executed on data that is
subject to the memory limit. Therefore, when using large writes or
stream_copy_to_stream/copy the memory limit can easily be hit with large
enough data.

To solve this, we reintroduce chunking for userspace streams.
Users have control over the chunk size, which is neat because
they can improve the performance by setting the chunk size if
that turns out to be a bottleneck.

In an ideal world, we add an option so we can "ask" the stream whether
it "prefers" chunked writes, similar to how we have
php_stream_mmap_supported & friends. However, that cannot be done on
stable branches.
  • Loading branch information
nielsdos committed Jan 12, 2024
1 parent 5a988d5 commit 28f575c
Show file tree
Hide file tree
Showing 4 changed files with 17 additions and 4 deletions.
3 changes: 2 additions & 1 deletion ext/standard/tests/file/userstreams_006.phpt
Expand Up @@ -34,5 +34,6 @@ bool(true)
option: 3, 2, 50
int(-1)
int(8192)
size: 70
size: 42
size: 28
int(70)
1 change: 1 addition & 0 deletions ext/standard/tests/streams/set_file_buffer.phpt
Expand Up @@ -39,4 +39,5 @@ option: %d, %d, %d
int(%i)
int(%d)
size: %d
size: 28
int(%d)
8 changes: 6 additions & 2 deletions ext/standard/tests/streams/stream_set_chunk_size.phpt
Expand Up @@ -69,7 +69,9 @@ should be read without buffer ($count == 10000)
read with size: 10000
int(10000)
should have no effect on writes
write with size: 3
write with size: 1
write with size: 1
write with size: 1
int(3)
should return previous chunk size (1)
int(1)
Expand All @@ -82,7 +84,9 @@ int(50)
should elicit no read because there is sufficient cached data
int(50)
should have no effect on writes
write with size: 250
write with size: 100
write with size: 100
write with size: 50
int(3)

error conditions
Expand Down
9 changes: 8 additions & 1 deletion main/streams/streams.c
Expand Up @@ -1133,8 +1133,15 @@ static ssize_t _php_stream_write_buffer(php_stream *stream, const char *buf, siz
stream->ops->seek(stream, stream->position, SEEK_SET, &stream->position);
}

/* See GH-13071: userspace stream is subject to the memory limit. */
size_t chunk_size = count;
if (php_stream_is(stream, PHP_STREAM_IS_USERSPACE)) {
/* If the stream is unbuffered, we can only write one byte at a time. */
chunk_size = stream->chunk_size;
}

while (count > 0) {
ssize_t justwrote = stream->ops->write(stream, buf, count);
ssize_t justwrote = stream->ops->write(stream, buf, MIN(chunk_size, count));
if (justwrote <= 0) {
/* If we already successfully wrote some bytes and a write error occurred
* later, report the successfully written bytes. */
Expand Down

0 comments on commit 28f575c

Please sign in to comment.