Skip to content

Commit 9effa00

Browse files
ondrejmirtesclaude
andcommitted
Serve a parse error from the autoload trap where OPcache would keep its empty script
AutoloadSourceLocator locates a class not yet loaded by running the autoloaders under FileReadTrapStreamWrapper, which records the file an autoloader includes and serves an empty script in its place. With OPcache active that empty script is compiled and cached under the path the include was given; the locator invalidates the trapped files afterwards, but on PHP < 8.1 opcache_invalidate() fails for the path of any stream wrapper other than file:// - zend_accel_invalidate() resolves the path first and php_resolve_path() refuses such URLs (8.1 falls back to the name as given). The poisoned entry then answers every later real include of the same path, the class is never declared, and its first cold use dies with "Class not found". PHPStan's own classes that preload.php leaves to the autoloader (the turbo-shadowed ones, TrinaryLogic among them) are exactly such files when running from the phar - autoloaded as phar://.../vendor/composer/../../src/TrinaryLogic.php by the phar's Composer classmap - and analysing code that references them triggers the trap. Spawned workers on PHP 7.4 and 8.0 started running with OPcache in the previous commit, which is how the extension test suites hit it. Where the invalidation cannot work, the trap now serves a parse error instead: it compiles to nothing, so OPcache stores nothing, and the locator catches the ParseError - the file was recorded before the include compiled it. Everywhere else the empty script stays, so autoloaders that require several files in a row keep being captured in full. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VdGL6QPGhAzYmN2zU4gwhH
1 parent 100834a commit 9effa00

3 files changed

Lines changed: 103 additions & 1 deletion

File tree

‎src/Reflection/BetterReflection/SourceLocator/AutoloadSourceLocator.php‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
namespace PHPStan\Reflection\BetterReflection\SourceLocator;
44

55
use Override;
6+
use ParseError;
67
use PhpParser\Node\Arg;
78
use PhpParser\Node\Expr\FuncCall;
89
use PhpParser\Node\Name;
@@ -343,7 +344,13 @@ static function () use ($className): ?array {
343344
}
344345

345346
foreach ($functions as $preExistingAutoloader) {
346-
$preExistingAutoloader($className);
347+
try {
348+
$preExistingAutoloader($className);
349+
} catch (ParseError) {
350+
// the trap served a parse error instead of the empty
351+
// script, see FileReadTrapStreamWrapper::stream_read();
352+
// the file was recorded before the include compiled it
353+
}
347354

348355
/**
349356
* This static variable is populated by the side-effect of the stream wrapper
@@ -367,6 +374,9 @@ static function () use ($className): ?array {
367374
return $result;
368375
}
369376

377+
// the trap's empty script got compiled - and cached, with OPcache
378+
// active. Where this call cannot reach the entry, the trap served a
379+
// parse error instead, see FileReadTrapStreamWrapper::stream_read()
370380
foreach ($result[0] as $file) {
371381
opcache_invalidate($file, true);
372382
}

‎src/Reflection/BetterReflection/SourceLocator/FileReadTrapStreamWrapper.php‎

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,17 @@
33
namespace PHPStan\Reflection\BetterReflection\SourceLocator;
44

55
use PHPStan\ShouldNotHappenException;
6+
use function function_exists;
67
use function is_dir;
78
use function is_file;
9+
use function opcache_get_status;
810
use function stat;
911
use function stream_resolve_include_path;
1012
use function stream_wrapper_register;
1113
use function stream_wrapper_restore;
1214
use function stream_wrapper_unregister;
15+
use function strpos;
16+
use const PHP_VERSION_ID;
1317
use const SEEK_CUR;
1418
use const SEEK_END;
1519
use const SEEK_SET;
@@ -40,10 +44,22 @@ final class FileReadTrapStreamWrapper
4044
/** @var string[] */
4145
public static array $autoloadLocatedFiles = [];
4246

47+
/**
48+
* Served instead of the empty script where OPcache would keep that empty
49+
* script, see servesParseError(). A parse error compiles to nothing, so
50+
* OPcache stores nothing, and it reaches AutoloadSourceLocator as the
51+
* ParseError it catches.
52+
*/
53+
private const PARSE_ERROR_SCRIPT = "<?php\n// PHPStan's autoload trap: deliberately not valid PHP, see FileReadTrapStreamWrapper\n}\n";
54+
55+
private static ?bool $opcacheEnabled = null;
56+
4357
private bool $readFromFile = false;
4458

4559
private int $seekPosition = 0;
4660

61+
private string $path = '';
62+
4763
/**
4864
* @param string[] $streamWrapperProtocols
4965
*
@@ -102,6 +118,7 @@ public function stream_open($path, $mode, $options, &$openedPath): bool
102118
if ($exists) {
103119
self::$autoloadLocatedFiles[] = $path;
104120
}
121+
$this->path = $path;
105122
$this->readFromFile = false;
106123
$this->seekPosition = 0;
107124

@@ -119,12 +136,55 @@ public function stream_read($count): string
119136
{
120137
$this->readFromFile = true;
121138

139+
if (self::servesParseError($this->path)) {
140+
return self::PARSE_ERROR_SCRIPT;
141+
}
142+
122143
// Dummy return value that is also valid PHP for require(). We'll read
123144
// and process the file elsewhere, so it's OK to provide dummy data for
124145
// this read.
125146
return '';
126147
}
127148

149+
/**
150+
* Whether the empty script served for this path would stay in OPcache and
151+
* shadow the real file for the rest of the process.
152+
*
153+
* OPcache caches what an include compiles under the path the include was
154+
* given - the empty script this wrapper serves too. AutoloadSourceLocator
155+
* undoes that with opcache_invalidate() on the trapped files, except that
156+
* on PHP < 8.1 the call fails for the path of any stream wrapper other
157+
* than file://: zend_accel_invalidate() resolves the path first, and
158+
* php_resolve_path() refuses such URLs (PHP >= 8.1 falls back to the name
159+
* as given). The poisoned entry then serves the empty script to every
160+
* later include of the same path, so a class in that file is never
161+
* declared - "Class not found" on its first cold use. PHPStan's own
162+
* classes that preload.php leaves to the autoloader are exactly such
163+
* files when running from the phar, autoloaded as
164+
* phar://.../vendor/composer/../../src/....
165+
*/
166+
private static function servesParseError(string $path): bool
167+
{
168+
if (self::$opcacheEnabled === null) {
169+
self::$opcacheEnabled = false;
170+
if (function_exists('opcache_get_status')) {
171+
$status = opcache_get_status(false);
172+
self::$opcacheEnabled = $status !== false && ($status['opcache_enabled'] ?? false) === true;
173+
}
174+
}
175+
176+
return self::resolveServesParseError(PHP_VERSION_ID, self::$opcacheEnabled, $path);
177+
}
178+
179+
public static function resolveServesParseError(int $phpVersionId, bool $opcacheEnabled, string $path): bool
180+
{
181+
if (!$opcacheEnabled || $phpVersionId >= 80100) {
182+
return false;
183+
}
184+
185+
return strpos($path, '://') !== false && strpos($path, 'file://') !== 0;
186+
}
187+
128188
/**
129189
* Since we allowed the open to succeed, we should allow the close to occur
130190
* as well.
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace PHPStan\Reflection\BetterReflection\SourceLocator;
4+
5+
use PHPUnit\Framework\Attributes\DataProvider;
6+
use PHPUnit\Framework\TestCase;
7+
8+
final class FileReadTrapStreamWrapperTest extends TestCase
9+
{
10+
11+
/**
12+
* @return iterable<string, array{int, bool, string, bool}>
13+
*/
14+
public static function dataResolveServesParseError(): iterable
15+
{
16+
$pharPath = 'phar:///project/vendor/phpstan/phpstan/phpstan.phar/vendor/composer/../../src/TrinaryLogic.php';
17+
yield 'phar path, OPcache, PHP 7.4' => [70433, true, $pharPath, true];
18+
yield 'phar path, OPcache, PHP 8.0' => [80030, true, $pharPath, true];
19+
yield 'phar path, OPcache, PHP 8.1 invalidates by name' => [80100, true, $pharPath, false];
20+
yield 'phar path, no OPcache' => [70433, false, $pharPath, false];
21+
yield 'plain path, OPcache, PHP 7.4' => [70433, true, '/project/src/Foo.php', false];
22+
yield 'file:// path, OPcache, PHP 7.4' => [70433, true, 'file:///project/src/Foo.php', false];
23+
yield 'other wrapper, OPcache, PHP 7.4' => [70433, true, 'vfs://project/src/Foo.php', true];
24+
}
25+
26+
#[DataProvider('dataResolveServesParseError')]
27+
public function testResolveServesParseError(int $phpVersionId, bool $opcacheEnabled, string $path, bool $expected): void
28+
{
29+
$this->assertSame($expected, FileReadTrapStreamWrapper::resolveServesParseError($phpVersionId, $opcacheEnabled, $path));
30+
}
31+
32+
}

0 commit comments

Comments
 (0)