From 34b352d121051a1ba582916be48e2e36f8ddf0e7 Mon Sep 17 00:00:00 2001 From: Go Kudo Date: Sun, 24 Jul 2022 03:09:14 +0900 Subject: [PATCH] Fix memory leak on Randomizer::__construct() call twice (#9091) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When Radomizer::__construct() was called with no arguments, Randomizer\Engine\Secure was implicitly instantiate and memory was leaking. Co-authored-by: Tim Düsterhus --- NEWS | 2 + ext/random/randomizer.c | 5 +++ .../tests/03_randomizer/construct_twice.phpt | 40 +++++++++++++++++++ 3 files changed, 47 insertions(+) create mode 100644 ext/random/tests/03_randomizer/construct_twice.phpt diff --git a/NEWS b/NEWS index e13f36ce622..8fbb3ffa95c 100644 --- a/NEWS +++ b/NEWS @@ -24,6 +24,8 @@ PHP NEWS . Fixed bug GH-9083 (undefined behavior during shifting). (timwolla) . Fixed bug GH-9088, GH-9056 (incorrect expansion of bytes when generating uniform integers within a given range). (timwolla) + . Fixed bug GH-9089 (Fix memory leak on Randomizer::__construct() + call twice) (zeriyoshi) 21 Jul 2022, PHP 8.2.0beta1 diff --git a/ext/random/randomizer.c b/ext/random/randomizer.c index 722fbd0b5c4..d5f4b46b2b2 100644 --- a/ext/random/randomizer.c +++ b/ext/random/randomizer.c @@ -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); diff --git a/ext/random/tests/03_randomizer/construct_twice.phpt b/ext/random/tests/03_randomizer/construct_twice.phpt new file mode 100644 index 00000000000..ccb831dfd4a --- /dev/null +++ b/ext/random/tests/03_randomizer/construct_twice.phpt @@ -0,0 +1,40 @@ +--TEST-- +Random: Randomizer: Disallow manually calling __construct +--FILE-- +__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