Skip to content

PHPLIB-345: Fix PHP shutdown error with dangling writable streams #779

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Sep 1, 2020
Merged
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
12 changes: 12 additions & 0 deletions src/GridFS/StreamWrapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,14 @@ class StreamWrapper
/** @var ReadableStream|WritableStream|null */
private $stream;

public function __destruct()
{
/* This destructor is a workaround for PHP trying to use the stream well
* after all objects have been destructed. This can cause autoloading
* issues and possibly segmentation faults during PHP shutdown. */
$this->stream = null;
}

/**
* Return the stream's file document.
*
Expand Down Expand Up @@ -88,6 +96,10 @@ public static function register($protocol = 'gridfs')
*/
public function stream_close()
{
if (! $this->stream) {
return;
}

$this->stream->close();
}

Expand Down
28 changes: 28 additions & 0 deletions tests/GridFS/BucketFunctionalTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,17 +18,22 @@
use function array_merge;
use function call_user_func;
use function current;
use function exec;
use function fclose;
use function fread;
use function fwrite;
use function hash_init;
use function implode;
use function is_callable;
use function min;
use function sprintf;
use function str_repeat;
use function stream_get_contents;
use function strlen;
use function strncasecmp;
use function substr;
use const PHP_EOL;
use const PHP_OS;

/**
* Functional tests for the Bucket class.
Expand Down Expand Up @@ -708,6 +713,29 @@ public function testExistingIndexIsReused()
$this->assertIndexNotExists($this->chunksCollection->getCollectionName(), 'files_id_1_n_1');
}

public function testDanglingOpenWritableStream()
{
if (! strncasecmp(PHP_OS, 'WIN', 3)) {
$this->markTestSkipped('Test does not apply to Windows');
}

$path = __DIR__ . '/../../vendor/autoload.php';
$command = <<<CMD
php -r "require '$path'; \\\$stream = (new MongoDB\Client)->test->selectGridFSBucket()->openUploadStream('filename', ['disableMD5' => true]);" 2>&1
CMD;

@exec(
$command,
$output,
$return
);

$this->assertSame(0, $return);
$output = implode(PHP_EOL, $output);

$this->assertSame('', $output);
}

/**
* Asserts that a collection with the given name does not exist on the
* server.
Expand Down