Skip to content

Commit 34b352d

Browse files
zeriyoshiTimWolla
andauthored
Fix memory leak on Randomizer::__construct() call twice (#9091)
When Radomizer::__construct() was called with no arguments, Randomizer\Engine\Secure was implicitly instantiate and memory was leaking. Co-authored-by: Tim Düsterhus <timwolla@googlemail.com>
1 parent 3c37290 commit 34b352d

File tree

3 files changed

+47
-0
lines changed

3 files changed

+47
-0
lines changed

NEWS

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,8 @@ PHP NEWS
2424
. Fixed bug GH-9083 (undefined behavior during shifting). (timwolla)
2525
. Fixed bug GH-9088, GH-9056 (incorrect expansion of bytes when
2626
generating uniform integers within a given range). (timwolla)
27+
. Fixed bug GH-9089 (Fix memory leak on Randomizer::__construct()
28+
call twice) (zeriyoshi)
2729

2830
21 Jul 2022, PHP 8.2.0beta1
2931

ext/random/randomizer.c

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,11 @@ PHP_METHOD(Random_Randomizer, __construct)
7070
Z_PARAM_OBJ_OF_CLASS_OR_NULL(engine_object, random_ce_Random_Engine);
7171
ZEND_PARSE_PARAMETERS_END();
7272

73+
if (randomizer->algo) {
74+
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot call constructor twice");
75+
RETURN_THROWS();
76+
}
77+
7378
/* Create default RNG instance */
7479
if (!engine_object) {
7580
engine_object = random_ce_Random_Engine_Secure->create_object(random_ce_Random_Engine_Secure);
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
--TEST--
2+
Random: Randomizer: Disallow manually calling __construct
3+
--FILE--
4+
<?php
5+
6+
final class UserEngine implements \Random\Engine
7+
{
8+
public function generate(): string
9+
{
10+
return \random_byte(4); /* 32-bit */
11+
}
12+
}
13+
14+
try {
15+
(new \Random\Randomizer())->__construct();
16+
} catch (\BadMethodCallException $e) {
17+
echo $e->getMessage() . PHP_EOL;
18+
}
19+
20+
try {
21+
$r = new \Random\Randomizer(new \Random\Engine\Xoshiro256StarStar());
22+
$r->__construct(new \Random\Engine\PcgOneseq128XslRr64());
23+
} catch (\BadMethodCallException $e) {
24+
echo $e->getMessage() . PHP_EOL;
25+
}
26+
27+
try {
28+
$r = new \Random\Randomizer(new \UserEngine());
29+
$r->__construct(new \UserEngine());
30+
} catch (\BadMethodCallException $e) {
31+
echo $e->getMessage() . PHP_EOL;
32+
}
33+
34+
die('success');
35+
?>
36+
--EXPECT--
37+
Cannot call constructor twice
38+
Cannot call constructor twice
39+
Cannot call constructor twice
40+
success

0 commit comments

Comments
 (0)