Skip to content

Fix memory leak on Randomizer::__construct() call twice #9091

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 12 commits into from
Jul 23, 2022
Merged
5 changes: 5 additions & 0 deletions ext/random/randomizer.c
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,11 @@ PHP_METHOD(Random_Randomizer, __construct)
Z_PARAM_OBJ_OF_CLASS_OR_NULL(engine_object, random_ce_Random_Engine);
ZEND_PARSE_PARAMETERS_END();

if (randomizer->algo) {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot call constructor twice");
RETURN_THROWS();
}

/* Create default RNG instance */
if (!engine_object) {
engine_object = random_ce_Random_Engine_Secure->create_object(random_ce_Random_Engine_Secure);
Expand Down
40 changes: 40 additions & 0 deletions ext/random/tests/03_randomizer/construct_twice.phpt
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
--TEST--
Random: Randomizer: Disallow manually calling __construct
--FILE--
<?php

final class UserEngine implements \Random\Engine
{
public function generate(): string
{
return \random_byte(4); /* 32-bit */
}
}

try {
(new \Random\Randomizer())->__construct();
} catch (\BadMethodCallException $e) {
echo $e->getMessage() . PHP_EOL;
}

try {
$r = new \Random\Randomizer(new \Random\Engine\Xoshiro256StarStar());
$r->__construct(new \Random\Engine\PcgOneseq128XslRr64());
} catch (\BadMethodCallException $e) {
echo $e->getMessage() . PHP_EOL;
}

try {
$r = new \Random\Randomizer(new \UserEngine());
$r->__construct(new \UserEngine());
} catch (\BadMethodCallException $e) {
echo $e->getMessage() . PHP_EOL;
}

die('success');
?>
--EXPECT--
Cannot call constructor twice
Cannot call constructor twice
Cannot call constructor twice
success