Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 58 additions & 0 deletions ext/standard/tests/streams/memory_stream_seek_int_min.phpt
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
--TEST--
php://memory and php://temp stream seek with PHP_INT_MIN does not trigger undefined behavior
--FILE--
<?php
foreach (['php://memory', 'php://temp'] as $wrapper) {
echo "=== $wrapper ===\n";

$stream = fopen($wrapper, 'r+');
fwrite($stream, 'hello');

// SEEK_CUR with PHP_INT_MIN from middle of stream
fseek($stream, 2, SEEK_SET);
var_dump(fseek($stream, PHP_INT_MIN, SEEK_CUR));

// SEEK_CUR with PHP_INT_MIN from beginning of stream
fseek($stream, 0, SEEK_SET);
var_dump(fseek($stream, PHP_INT_MIN, SEEK_CUR));

// SEEK_END with PHP_INT_MIN
var_dump(fseek($stream, PHP_INT_MIN, SEEK_END));

// Normal negative SEEK_CUR that should succeed
fseek($stream, 4, SEEK_SET);
var_dump(fseek($stream, -2, SEEK_CUR));
var_dump(ftell($stream));

// Normal negative SEEK_END that should succeed
var_dump(fseek($stream, -3, SEEK_END));
var_dump(ftell($stream));

// Verify stream still works after all edge-case seeks
fseek($stream, 0, SEEK_SET);
var_dump(fread($stream, 5));

fclose($stream);
}
echo "Done\n";
?>
--EXPECT--
=== php://memory ===
int(-1)
int(-1)
int(-1)
int(0)
int(2)
int(0)
int(2)
string(5) "hello"
=== php://temp ===
int(-1)
int(-1)
int(-1)
int(0)
int(2)
int(0)
int(2)
string(5) "hello"
Done
4 changes: 2 additions & 2 deletions main/streams/memory.c
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ static int php_stream_memory_seek(php_stream *stream, zend_off_t offset, int whe
switch(whence) {
case SEEK_CUR:
if (offset < 0) {
if (ms->fpos < (size_t)(-offset)) {
if (ms->fpos < (size_t)0 - (size_t)offset) {
ms->fpos = 0;
*newoffs = -1;
return -1;
Expand Down Expand Up @@ -165,7 +165,7 @@ static int php_stream_memory_seek(php_stream *stream, zend_off_t offset, int whe
stream->eof = 0;
stream->fatal_error = 0;
return 0;
} else if (ZSTR_LEN(ms->data) < (size_t)(-offset)) {
} else if (ZSTR_LEN(ms->data) < (size_t)0 - (size_t)offset) {
ms->fpos = 0;
*newoffs = -1;
return -1;
Expand Down
Loading