Skip to content

Commit de2756d

Browse files
ondrejmirtesclaude
andcommitted
Treat variables holding an object with a destructor as used
A destructor observes the value when the variable releases it - overwritten, unset or going out of scope - so assigning such an object to a variable that is never read keeps it alive on purpose (a scope guard). VariableFlowBuilder::targetWrite() escapes the variable when the written value may be an object whose class has __destruct, which leaves all of its writes untracked, including `$guard = null;` that releases the object early. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Bm4YbtwnyY5UMgp64hK1ff
1 parent d29b7e1 commit de2756d

6 files changed

Lines changed: 172 additions & 8 deletions

File tree

‎src/Analyser/VariableFlowBuilder.php‎

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
use PHPStan\Node\Variable\VariableWrite;
88
use PHPStan\Turbo\ShadowedByTurboExtension;
99
use PHPStan\Type\Type;
10+
use PHPStan\Type\TypeCombinator;
1011
use function in_array;
1112
use function is_string;
1213
use function spl_object_id;
@@ -134,7 +135,37 @@ public static function targetWrite(Expr $target, int $kind, MutatingScope $scope
134135
return VariableFlow::sequence(...$writes);
135136
}
136137
$write = self::writeSite($target, $kind, $scope, $storage);
137-
return $write !== null ? VariableFlow::write($write, $redundant) : null;
138+
if ($write === null) {
139+
return null;
140+
}
141+
$flow = VariableFlow::write($write, $redundant);
142+
$name = $write->getVariableName();
143+
if (
144+
!$write->isOffsetWrite()
145+
&& !$scope->hasVariableType($name)->no()
146+
&& self::holdsDestructibleObject($scope->getVariableType($name))
147+
) {
148+
// the destructor observes the value when the variable releases it -
149+
// overwritten, unset or going out of scope - so a variable holding
150+
// the object keeps it alive on purpose (a scope guard)
151+
return VariableFlow::sequence($flow, VariableFlow::escape($name));
152+
}
153+
154+
return $flow;
155+
}
156+
157+
private static function holdsDestructibleObject(Type $type): bool
158+
{
159+
if ($type->isObject()->no()) {
160+
return false;
161+
}
162+
foreach (TypeCombinator::removeNull($type)->getObjectClassReflections() as $classReflection) {
163+
if ($classReflection->hasNativeMethod('__destruct')) {
164+
return true;
165+
}
166+
}
167+
168+
return false;
138169
}
139170

140171
/** @param VariableWrite::KIND_* $kind */

‎tests/PHPStan/Rules/DeadCode/UnusedVariableRuleTest.php‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -441,9 +441,15 @@ public function testUnsetCallsDestructor(): void
441441
{
442442
$this->analyse([__DIR__ . '/data/unused-variable-destructor.php'], [
443443
['Variable $unused is never read.', 33],
444+
['Variable $object is never read.', 75],
444445
]);
445446
}
446447

448+
public function testBug15225(): void
449+
{
450+
$this->analyse([__DIR__ . '/data/bug-15225.php'], []);
451+
}
452+
447453
public function testFlowMessages(): void
448454
{
449455
$this->analyse([__DIR__ . '/data/unused-variable-flow-messages.php'], [
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace Bug15225;
4+
5+
final class ScopeGuard
6+
{
7+
public function __construct()
8+
{
9+
echo "enter\n";
10+
}
11+
12+
public function __destruct()
13+
{
14+
echo "leave\n";
15+
}
16+
}
17+
18+
function runWithGuard(): void
19+
{
20+
$guard = new ScopeGuard();
21+
echo "work\n";
22+
}
23+
24+
runWithGuard();

‎tests/PHPStan/Rules/DeadCode/data/unused-variable-destructor.php‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,3 +39,39 @@ function closeStream(string $path): void
3939
$stream = fopen($path, 'r');
4040
unset($stream);
4141
}
42+
43+
class ChildCache extends Cache
44+
{
45+
}
46+
47+
function scopeGuard(): void
48+
{
49+
$guard = new Cache();
50+
echo 'work';
51+
}
52+
53+
function inheritedDestructor(): void
54+
{
55+
$guard = new ChildCache();
56+
echo 'work';
57+
}
58+
59+
function releasedEarly(): void
60+
{
61+
$guard = new Cache();
62+
echo 'work';
63+
$guard = null;
64+
echo 'more work';
65+
}
66+
67+
function maybeDestructible(bool $b): void
68+
{
69+
$guard = $b ? new Cache() : null;
70+
echo 'work';
71+
}
72+
73+
function noDestructor(): void
74+
{
75+
$object = new \stdClass();
76+
echo 'work';
77+
}

‎turbo-ext/src/VariableFlowBuilder.cpp‎

Lines changed: 63 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -374,7 +374,69 @@ class VariableFlowBuilder
374374
zv::Val write = writeSite(target, kind, scope, storage);
375375
if (UNEXPECTED(write.isUndef())) return zv::Val();
376376
if (Z_TYPE_P(write.raw()) == IS_NULL) return zv::Val::null();
377-
return pt_variable_flow_write(write.raw(), redundant);
377+
zv::Val flow = pt_variable_flow_write(write.raw(), redundant);
378+
if (UNEXPECTED(flow.isUndef())) return zv::Val();
379+
/* a write that is not an offset write: writeSite() made it for a
380+
* plain variable target */
381+
if (!instanceof_function(targetObj->ce, classes.variable)) return flow;
382+
zend_string *name = variableName(targetObj);
383+
if (name == NULL) return flow;
384+
zv::Val hasVariableTypeResult = pt_mutating_scope_has_variable_type(Z_OBJ_P(scope), name);
385+
if (UNEXPECTED(hasVariableTypeResult.isUndef())) return zv::Val();
386+
zend_long hasVariableType = pt_type_trinary_value(hasVariableTypeResult.raw());
387+
if (UNEXPECTED(hasVariableType < 0)) return zv::Val();
388+
if (hasVariableType == PT_TRI_NO) return flow;
389+
zv::Val type = pt_mutating_scope_get_variable_type(Z_OBJ_P(scope), name);
390+
if (UNEXPECTED(type.isUndef())) return zv::Val();
391+
bool destructible;
392+
if (UNEXPECTED(!holdsDestructibleObject(type.raw(), destructible))) return zv::Val();
393+
if (!destructible) return flow;
394+
// the destructor observes the value when the variable releases it -
395+
// overwritten, unset or going out of scope - so a variable holding
396+
// the object keeps it alive on purpose (a scope guard)
397+
zv::Val escape = pt_variable_flow_escape(name);
398+
if (UNEXPECTED(escape.isUndef())) return zv::Val();
399+
zv::Args argv{flow.raw(), escape.raw()};
400+
return pt_variable_flow_sequence(2, argv);
401+
}
402+
403+
/* Mirrors holdsDestructibleObject(); false = pending exception. */
404+
[[nodiscard]] static bool holdsDestructibleObject(zval *type, bool &out)
405+
{
406+
out = false;
407+
if (UNEXPECTED(Z_TYPE_P(type) != IS_OBJECT)) {
408+
zend_type_error("phpstan_turbo: expected a Type, got %s", zend_zval_value_name(type));
409+
return false;
410+
}
411+
zend_long isObject = pt_type_call_trinary(Z_OBJ_P(type), PT_LC("isobject"), 0, NULL);
412+
if (UNEXPECTED(isObject < 0)) return false;
413+
if (isObject == PT_TRI_NO) return true;
414+
zv::Val withoutNull = pt_type_combinator_remove_null(type);
415+
if (UNEXPECTED(withoutNull.isUndef())) return false;
416+
if (UNEXPECTED(Z_TYPE_P(withoutNull.raw()) != IS_OBJECT)) {
417+
zend_type_error("phpstan_turbo: expected a Type, got %s", zend_zval_value_name(withoutNull.raw()));
418+
return false;
419+
}
420+
zv::Val reflections = pt_type_op(Z_OBJ_P(withoutNull.raw()), PT_OP_GET_OBJECT_CLASS_REFLECTIONS, 0, NULL);
421+
if (UNEXPECTED(reflections.isUndef())) return false;
422+
if (Z_TYPE_P(reflections.raw()) != IS_ARRAY) return true;
423+
zval destructName;
424+
ZVAL_STRINGL(&destructName, "__destruct", sizeof("__destruct") - 1);
425+
zv::Val destructNameHold = zv::Val::adopt(destructName);
426+
for (auto entry : zv::TableRef(Z_ARRVAL_P(reflections.raw()))) {
427+
zv::Ref classReflection = entry.value().deref();
428+
if (UNEXPECTED(!classReflection.isObject())) {
429+
zend_type_error("phpstan_turbo: expected a ClassReflection");
430+
return false;
431+
}
432+
bool hasDestructor;
433+
if (UNEXPECTED(!pt_type_call_bool(classReflection.asObject(), PT_LC("hasnativemethod"), 1, destructNameHold.raw(), hasDestructor))) return false;
434+
if (hasDestructor) {
435+
out = true;
436+
return true;
437+
}
438+
}
439+
return true;
378440
}
379441

380442
/* Mirrors writeSite(). */

‎turbo-ext/src/generated/VariableFlowBuilder.h‎

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -51,9 +51,11 @@ inline constexpr char strings[] =
5151
"redundant\0" /* 324 */
5252
"PHPStan\\Type\\Type\0" /* 334 */
5353
"targetWrite\0" /* 352 */
54-
"PHPStan\\Node\\Variable\\VariableWrite\0" /* 364 */
55-
"writeSite\0" /* 400 */
56-
"escapeRoot"; /* 410 */
54+
"type\0" /* 364 */
55+
"holdsDestructibleObject\0" /* 369 */
56+
"PHPStan\\Node\\Variable\\VariableWrite\0" /* 393 */
57+
"writeSite\0" /* 429 */
58+
"escapeRoot"; /* 439 */
5759
inline constexpr reg::PackedArg args[] = {
5860
reg::packed(0, 0, 5), /* throws $expr */
5961
reg::packed(25, MAY_BE_ARRAY), /* throws $throwPoints */
@@ -78,11 +80,13 @@ inline constexpr reg::PackedArg args[] = {
7880
reg::packed(148, 0, 156), /* targetWrite $storage */
7981
reg::packed(324, MAY_BE_NULL, 334, false, false, 254), /* targetWrite $redundant */
8082
reg::packed(37, MAY_BE_NULL, 38), /* targetWrite return */
83+
reg::packed(364, 0, 334), /* holdsDestructibleObject $type */
84+
reg::packed(37, MAY_BE_BOOL), /* holdsDestructibleObject return */
8185
reg::packed(233, 0, 5), /* writeSite $target */
8286
reg::packed(282, MAY_BE_LONG), /* writeSite $kind */
8387
reg::packed(287, 0, 293), /* writeSite $scope */
8488
reg::packed(148, 0, 156), /* writeSite $storage */
85-
reg::packed(37, MAY_BE_NULL, 364), /* writeSite return */
89+
reg::packed(37, MAY_BE_NULL, 393), /* writeSite return */
8690
reg::packed(0, 0, 5), /* escapeRoot $expr */
8791
reg::packed(37, MAY_BE_NULL, 38), /* escapeRoot return */
8892
};
@@ -97,8 +101,9 @@ inline constexpr sigtab::Sig child = { { 227 /* child */, 2, 7, 2, 9, ZEND_ACC_P
97101
inline constexpr sigtab::Sig targetRead = { { 259 /* targetRead */, 3, 10, 4, 14, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC } };
98102
inline constexpr sigtab::Sig writes = { { 275 /* writes */, 1, 15, 1, 16, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC } };
99103
inline constexpr sigtab::Sig targetWrite = { { 352 /* targetWrite */, 4, 17, 5, 22, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC } };
100-
inline constexpr sigtab::Sig writeSite = { { 400 /* writeSite */, 4, 23, 4, 27, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC } };
101-
inline constexpr sigtab::Sig escapeRoot = { { 410 /* escapeRoot */, 1, 28, 1, 29, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC } };
104+
inline constexpr sigtab::Sig holdsDestructibleObject = { { 369 /* holdsDestructibleObject */, 1, 23, 1, 24, ZEND_ACC_PRIVATE | ZEND_ACC_STATIC } };
105+
inline constexpr sigtab::Sig writeSite = { { 429 /* writeSite */, 4, 25, 4, 29, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC } };
106+
inline constexpr sigtab::Sig escapeRoot = { { 439 /* escapeRoot */, 1, 30, 1, 31, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC } };
102107
} // namespace sig
103108

104109
} // namespace ptdecl::VariableFlowBuilder

0 commit comments

Comments
 (0)