Skip to content

Commit

Permalink
Fixed bug #76803 ftruncate changes file pointer
Browse files Browse the repository at this point in the history
  • Loading branch information
weltling committed Aug 28, 2018
1 parent 441b6a6 commit 7728160
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
38 changes: 38 additions & 0 deletions ext/standard/tests/file/ftruncate_bug76803.phpt
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
--TEST--
Bug #76803 ftruncate changes file pointer
--FILE--
<?php

$fn = dirname(__FILE__) . DIRECTORY_SEPARATOR . "test76803";

$f = fopen($fn, "w");
fwrite($f, "Hello");
ftruncate($f, 2);
fwrite($f, "World");
fclose($f);
var_dump(addslashes(file_get_contents($fn)));

$f = fopen($fn, "w");
fwrite($f, "Hello");
ftruncate($f, 2);
fclose($f);
var_dump(addslashes(file_get_contents($fn)));

$f = fopen('php://memory', 'w+');
fwrite($f, 'Hello');
ftruncate($f, 2); // in 7.3 changes file pointer to 2
fwrite($f, 'World');
rewind($f);
var_dump(addslashes(stream_get_contents($f)));
fclose($f);

?>
--CLEAN--
<?php
$fn = dirname(__FILE__) . DIRECTORY_SEPARATOR . "test76803";
unlink($fn);
?>
--EXPECT--
string(13) "He\0\0\0World"
string(2) "He"
string(7) "HeWorld"
9 changes: 9 additions & 0 deletions main/streams/plain_wrapper.c
Original file line number Diff line number Diff line change
Expand Up @@ -857,6 +857,12 @@ static int php_stdiop_set_option(php_stream *stream, int option, int value, void
if (INVALID_HANDLE_VALUE == h) {
return PHP_STREAM_OPTION_RETURN_ERR;
}

LARGE_INTEGER old_sz;
if (!GetFileSizeEx(h, &old_sz)) {
return PHP_STREAM_OPTION_RETURN_ERR;
}

LARGE_INTEGER sz;
#if defined(_WIN64)
sz.HighPart = (new_size >> 32);
Expand All @@ -871,6 +877,9 @@ static int php_stdiop_set_option(php_stream *stream, int option, int value, void
if (0 == SetEndOfFile(h)) {
return PHP_STREAM_OPTION_RETURN_ERR;
}
if (INVALID_SET_FILE_POINTER == SetFilePointerEx(h, old_sz, NULL, FILE_BEGIN) && NO_ERROR != GetLastError()) {
return PHP_STREAM_OPTION_RETURN_ERR;
}
return PHP_STREAM_OPTION_RETURN_OK;
#else
return ftruncate(fd, new_size) == 0 ? PHP_STREAM_OPTION_RETURN_OK : PHP_STREAM_OPTION_RETURN_ERR;
Expand Down

0 comments on commit 7728160

Please sign in to comment.