Skip to content
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

Fix memory leak in ExceptionWrapper #5012

Merged
merged 1 commit into from Aug 23, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
24 changes: 20 additions & 4 deletions src/Framework/ExceptionWrapper.php
Expand Up @@ -9,11 +9,13 @@
*/
namespace PHPUnit\Framework;

use const PHP_VERSION_ID;
use function array_keys;
use function get_class;
use function spl_object_hash;
use PHPUnit\Util\Filter;
use Throwable;
use WeakReference;

/**
* Wraps Exceptions thrown by code under test.
Expand All @@ -38,6 +40,11 @@ final class ExceptionWrapper extends Exception
*/
protected $previous;

/**
* @var null|WeakReference<Throwable>
*/
private $originalException;

public function __construct(Throwable $t)
{
// PDOException::getCode() is a string.
Expand Down Expand Up @@ -109,14 +116,23 @@ public function getOriginalException(): ?Throwable
*/
private function originalException(Throwable $exceptionToStore = null): ?Throwable
{
static $originalExceptions;
// drop once PHP 7.3 support is removed
if (PHP_VERSION_ID < 70400) {
Copy link
Contributor Author

@mvorisek mvorisek Jul 8, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

drop this code when merging to phpunit 10.x, but fix should target 9.5.x at least/latest stable

static $originalExceptions;

$instanceId = spl_object_hash($this);
$instanceId = spl_object_hash($this);

if ($exceptionToStore) {
$originalExceptions[$instanceId] = $exceptionToStore;
}

return $originalExceptions[$instanceId] ?? null;
}

if ($exceptionToStore) {
$originalExceptions[$instanceId] = $exceptionToStore;
$this->originalException = WeakReference::create($exceptionToStore);
}

return $originalExceptions[$instanceId] ?? null;
return $this->originalException !== null ? $this->originalException->get() : null;
}
}