Skip to content
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
1 change: 1 addition & 0 deletions lib/VM/CycleCollector.php
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ public static function collect(Context $ctx): int
if (isset($marked[$object->id])) {
continue;
}
ObjectLifetime::invokeDestructorBeforeGcRelease($object);
ObjectRegistry::release($object);
++$collected;
}
Expand Down
9 changes: 9 additions & 0 deletions lib/VM/ObjectLifetime.php
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,15 @@ public static function releaseDirectObject(Variable $var): void
*
* @see https://github.com/php/php-src/blob/master/Zend/zend_objects.c zend_objects_destroy_object
*/
/** Invoke __destruct before gc_collect_cycles() frees an unreachable object (#6519, zend_gc.c). */
public static function invokeDestructorBeforeGcRelease(ObjectEntry $object): void
{
$vm = self::$vm;
if (null !== $vm && !$object->destructorInvoked) {
$vm->invokeUserDestructor($object);
}
}

public static function invokeUnsetDestructor(VM $vm, Variable $var): void
{
$var = $var->resolveIndirect();
Expand Down
19 changes: 19 additions & 0 deletions test/compliance/cases/runtime/gc_collect_cycles_destruct.phpt
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
--TEST--
runtime gc_collect_cycles() — cyclic objects invoke __destruct (#6519)
--FILE--
<?php
#[\AllowDynamicProperties]
class Node {
public function __destruct() {
echo "dtor\n";
}
}
$a = new Node();
$b = new Node();
$a->next = $b;
$b->next = $a;
unset($a, $b);
gc_collect_cycles();
--EXPECT--
dtor
dtor
36 changes: 36 additions & 0 deletions test/unit/GcCollectCyclesDestructTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<?php

declare(strict_types=1);

namespace PHPCompiler;

use PHPUnit\Framework\TestCase;

/** gc_collect_cycles() invokes __destruct on cyclic graphs (#6519). */
final class GcCollectCyclesDestructTest extends TestCase
{
public function testVmGcCollectCyclesInvokesDestructorsOnCycle(): void
{
$code = <<<'PHP'
<?php
#[\AllowDynamicProperties]
class Node {
public function __destruct()
{
echo "dtor\n";
}
}
$a = new Node();
$b = new Node();
$a->next = $b;
$b->next = $a;
unset($a, $b);
gc_collect_cycles();
PHP;
$rt = new Runtime();
$block = $rt->parseAndCompile($code, 'gc_cycle_destruct.php');
ob_start();
$rt->run($block);
$this->assertSame("dtor\ndtor\n", ob_get_clean());
}
}