Skip to content

Commit a027f78

Browse files
ondrejmirtesclaude
andcommitted
Read scanned files through PHP's stream layer in the native symbol finder
The twin reads each file with php_strip_whitespace(), i.e. the engine's include-style stream open: stream wrappers (phar:// is a supported scan case), the include path, Windows' UTF-8 paths. The native finder used a raw open(), so a phar:// or file:// path found no symbols, and on Windows _open() took the UTF-8 path as ANSI. Open through php_stream_open_wrapper_ex() with the same flags instead, and stop on an exception a user stream wrapper throws. Also mirror the rest of the twin's loop: key the result with zend_symtable_update() like `$result[$file] = ...` (a numeric-string path becomes an int key), throw findSymbolsInFile()'s TypeError for a non-string entry instead of skipping it, and php_strip_whitespace()'s ValueError for a path with a NUL byte. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018Fdg8n3eEi4ZoXa4dA2k4A
1 parent 20d1886 commit a027f78

2 files changed

Lines changed: 148 additions & 43 deletions

File tree

‎turbo-ext/src/SymbolFinderInFiles.cpp‎

Lines changed: 35 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -25,14 +25,6 @@ namespace sigs = ptdecl::SymbolFinderInFiles::sig;
2525
#include "zv.h"
2626
#include "SymbolScan.h"
2727

28-
#ifdef PHP_WIN32
29-
#include <io.h>
30-
#include <fcntl.h>
31-
#else
32-
#include <fcntl.h>
33-
#include <sys/stat.h>
34-
#include <unistd.h>
35-
#endif
3628

3729
static zend_class_entry *pt_ce_symbol_finder = nullptr;
3830

@@ -55,55 +47,39 @@ class SymbolFinderInFiles
5547
std::string cleaned;
5648
Symbols symbols;
5749

58-
bool readFile(const char *path, size_t pathLen);
50+
bool readFile(zend_string *path);
5951
void scan(bool supportsEnums);
6052
static void symbolsToArray(const Symbols &symbols, zval *out);
6153
};
6254

6355
/*
64-
* The twin reaches the file through php_strip_whitespace(), which goes past
65-
* the stream wrappers; the locators only ever pass real paths from their own
66-
* directory walk, so a plain open() is enough — and an unreadable file has to
67-
* behave like the twin's suppressed warning, i.e. produce no symbols.
56+
* The twin reaches the file through php_strip_whitespace(), which opens it
57+
* the way the engine opens an included file: PHP's stream layer with the
58+
* include path, the include-only checks (a non-regular file is refused,
59+
* allow_url_include applies) and every stream wrapper — a phar:// path is a
60+
* supported scan case. The same call here keeps all of that, and Windows'
61+
* UTF-8 paths, identical. A file that cannot be opened behaves like the
62+
* twin's suppressed warning: no symbols.
6863
*/
69-
bool SymbolFinderInFiles::readFile(const char *path, size_t pathLen)
64+
bool SymbolFinderInFiles::readFile(zend_string *path)
7065
{
7166
source.clear();
7267

73-
if (pathLen == 0 || memchr(path, '\0', pathLen) != NULL) return false;
74-
75-
#ifdef PHP_WIN32
76-
int fd = _open(path, _O_RDONLY | _O_BINARY);
77-
#else
78-
int fd = open(path, O_RDONLY);
79-
#endif
80-
if (fd < 0) return false;
68+
php_stream *stream = php_stream_open_wrapper_ex(ZSTR_VAL(path), "rb", USE_PATH | STREAM_OPEN_FOR_INCLUDE, NULL, NULL);
69+
if (stream == NULL) return false;
8170

8271
char chunk[65536];
8372
for (;;) {
84-
#ifdef PHP_WIN32
85-
int got = _read(fd, chunk, sizeof(chunk));
86-
#else
87-
ssize_t got = read(fd, chunk, sizeof(chunk));
88-
#endif
73+
ssize_t got = php_stream_read(stream, chunk, sizeof(chunk));
8974
if (got < 0) {
90-
#ifdef PHP_WIN32
91-
_close(fd);
92-
#else
93-
close(fd);
94-
#endif
75+
php_stream_close(stream);
9576
source.clear();
9677
return false;
9778
}
9879
if (got == 0) break;
9980
source.append(chunk, (size_t) got);
10081
}
101-
102-
#ifdef PHP_WIN32
103-
_close(fd);
104-
#else
105-
close(fd);
106-
#endif
82+
php_stream_close(stream);
10783

10884
return true;
10985
}
@@ -151,28 +127,42 @@ zv::Val SymbolFinderInFiles::findSymbols(HashTable *files, bool supportsEnums)
151127
{
152128
zval result;
153129
array_init_size(&result, zend_hash_num_elements(files));
130+
zv::Val owned = zv::Val::adopt(result);
154131

155132
for (zv::ArrayEntry file : zv::TableRef(files)) {
156133
zv::Ref value = file.value().deref();
157-
if (!value.isString()) continue;
134+
/* findSymbolsInFile(string $file, ...) under strict_types */
135+
if (!value.isString()) {
136+
zend_type_error("%s::findSymbolsInFile(): Argument #1 ($file) must be of type string, %s given", ZSTR_VAL(pt_ce_symbol_finder->name), zend_zval_value_name(value.raw()));
137+
return zv::Val();
138+
}
158139

159140
zend_string *path = value.asString();
160-
if (readFile(ZSTR_VAL(path), ZSTR_LEN(path))) {
141+
/* php_strip_whitespace()'s Z_PARAM_PATH_STR */
142+
if (UNEXPECTED(ZSTR_LEN(path) != strlen(ZSTR_VAL(path)))) {
143+
zend_value_error("php_strip_whitespace(): Argument #1 ($filename) must not contain any null bytes");
144+
return zv::Val();
145+
}
146+
bool read = readFile(path);
147+
/* a user stream wrapper threw: the twin's @ does not catch that */
148+
if (UNEXPECTED(EG(exception))) return zv::Val();
149+
if (read) {
161150
scan(supportsEnums);
162151
} else {
163152
symbols.clear();
164153
}
165154

155+
/* $result[$file] = ...: a numeric-string path becomes an int key */
166156
zval triple;
167157
symbolsToArray(symbols, &triple);
168-
zend_hash_update(Z_ARRVAL(result), path, &triple);
158+
zend_symtable_update(Z_ARRVAL_P(owned.raw()), path, &triple);
169159

170160
if (source.capacity() > BUFFER_RETENTION_LIMIT) {
171161
std::string().swap(source);
172162
}
173163
}
174164

175-
return zv::Val::adopt(result);
165+
return owned;
176166
}
177167

178168
} // namespace phpstanturbo
@@ -202,7 +192,9 @@ void pt_register_symbol_finder_in_files()
202192
if (!zp::parse<zp::Ht, zp::Bool>(execute_data, files, supportsEnums)) RETURN_THROWS();
203193

204194
phpstanturbo::SymbolFinderInFiles finder;
205-
finder.findSymbols(files, supportsEnums).intoReturnValue(return_value);
195+
zv::Val result = finder.findSymbols(files, supportsEnums);
196+
if (UNEXPECTED(result.isUndef())) RETURN_THROWS();
197+
result.intoReturnValue(return_value);
206198
});
207199

208200
cls.shadow(&pt_ce_symbol_finder);

‎turbo-ext/tests/symbol-finder-corpus.php‎

Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,119 @@
141141
}
142142
@rmdir($dir);
143143

144+
// ---- how the files are reached ----
145+
// The twin reads each file through php_strip_whitespace(), i.e. PHP's stream
146+
// layer: stream-wrapper paths (file://, user wrappers, phar://) are found,
147+
// and the result is keyed like `$result[$file] = ...` (a numeric-string path
148+
// becomes an int key). Anything but a string throws the twin's TypeError, a
149+
// path with a NUL byte php_strip_whitespace()'s ValueError. The twin is the
150+
// real class here, so the messages compare modulo the prefix.
151+
$twin = new PHPStan\Reflection\BetterReflection\SourceLocator\SymbolFinderInFiles(new PHPStan\Reflection\BetterReflection\SourceLocator\PhpFileCleaner());
152+
$observe = static function (object $finder, array $files): array {
153+
try {
154+
return ['result', $finder->findSymbols($files, true)];
155+
} catch (\Throwable $e) {
156+
return [get_class($e), str_replace('PHPStanTurbo\\SymbolFinderInFiles', 'PHPStan\\Reflection\\BetterReflection\\SourceLocator\\SymbolFinderInFiles', preg_replace('~, called in .*$~', '', $e->getMessage()))];
157+
}
158+
};
159+
final class SymbolFinderCorpusStreamWrapper
160+
{
161+
162+
/** @var resource|null */
163+
public $context;
164+
165+
private string $data = '';
166+
167+
private int $position = 0;
168+
169+
public function stream_open(string $path, string $mode, int $options, ?string &$openedPath): bool
170+
{
171+
if (str_contains($path, 'throw')) {
172+
throw new \RuntimeException('the wrapper refuses ' . $path);
173+
}
174+
$this->data = "<?php\nnamespace Wrapped;\nclass ViaWrapper {}\nfunction viaWrapper() {}\n";
175+
return true;
176+
}
177+
178+
public function stream_read(int $count): string
179+
{
180+
$chunk = substr($this->data, $this->position, $count);
181+
$this->position += strlen($chunk);
182+
return $chunk;
183+
}
184+
185+
public function stream_eof(): bool
186+
{
187+
return $this->position >= strlen($this->data);
188+
}
189+
190+
public function stream_stat(): array
191+
{
192+
return ['size' => strlen($this->data), 'mode' => 0100644];
193+
}
194+
195+
public function stream_set_option(int $option, int $arg1, ?int $arg2): bool
196+
{
197+
return false;
198+
}
199+
200+
}
201+
stream_wrapper_register('symbolfindercorpus', SymbolFinderCorpusStreamWrapper::class);
202+
$streamDir = sys_get_temp_dir() . '/phpstan-symbol-finder-streams-' . getmypid();
203+
@mkdir($streamDir);
204+
file_put_contents($streamDir . '/plain.php', "<?php\nclass Plain {}\n");
205+
file_put_contents($streamDir . '/123', "<?php\nclass Numeric {}\n");
206+
// a phar:// path, the case ResultCacheManager scans for (a phar can only be
207+
// written with phar.readonly=0, which is INI_SYSTEM: a child process builds it)
208+
$pharFile = $streamDir . '/lib.phar';
209+
if (extension_loaded('phar')) {
210+
exec(escapeshellarg(PHP_BINARY) . ' -d phar.readonly=0 -r ' . escapeshellarg(sprintf(
211+
'$p = new Phar(%s); $p->addFromString("src/Foo.php", "<?php\\nnamespace Lib;\\nclass Foo {}\\nfunction bar() {}\\n"); $p->setStub("<?php __HALT_COMPILER();");',
212+
var_export($pharFile, true),
213+
)));
214+
}
215+
$previousCwd = getcwd();
216+
chdir($streamDir);
217+
$streamCases = [
218+
'file:// path' => ['file://' . $streamDir . '/plain.php'],
219+
'user stream wrapper' => ['symbolfindercorpus://anything.php'],
220+
'phar:// path' => ['phar://' . $pharFile . '/src/Foo.php'],
221+
'throwing stream wrapper' => ['symbolfindercorpus://throw.php', $streamDir . '/plain.php'],
222+
'numeric-string path' => ['123'],
223+
'relative path' => ['plain.php'],
224+
'missing file' => [$streamDir . '/missing.php'],
225+
'directory' => [$streamDir],
226+
'int entry' => [$streamDir . '/plain.php', 42],
227+
'null entry' => [null],
228+
'NUL byte in the path' => [$streamDir . "/plain.php\0.txt"],
229+
];
230+
$streamResults = [];
231+
foreach ($streamCases as $label => $files) {
232+
$a = $observe($native, $files);
233+
$b = $observe($twin, $files);
234+
$streamResults[$label] = $b;
235+
$checked++;
236+
if ($a !== $b) {
237+
$failures++;
238+
printf("FAIL: %s\n native: %s\n php : %s\n", $label, json_encode($a), json_encode($b));
239+
}
240+
}
241+
chdir($previousCwd);
242+
@unlink($streamDir . '/plain.php');
243+
@unlink($streamDir . '/123');
244+
@unlink($pharFile);
245+
@rmdir($streamDir);
246+
// the cases above must not pass vacuously
247+
$expected = ['result', ['symbolfindercorpus://x.php' => [['wrapped\\viawrapper'], ['wrapped\\viawrapper'], []]]];
248+
if ($observe($twin, ['symbolfindercorpus://x.php']) !== $expected) {
249+
$failures++;
250+
printf("FAIL: the twin reads through the stream wrapper: %s\n", json_encode($observe($twin, ['symbolfindercorpus://x.php'])));
251+
}
252+
if (extension_loaded('phar') && ($streamResults['phar:// path'] ?? null) !== ['result', ['phar://' . $pharFile . '/src/Foo.php' => [['lib\\foo'], ['lib\\bar'], []]]]) {
253+
$failures++;
254+
printf("FAIL: the phar fixture is scanned: %s\n", json_encode($streamResults['phar:// path'] ?? null));
255+
}
256+
144257
// ---- repo corpus ----
145258
$corpusStart = $checked;
146259
$files = [];

0 commit comments

Comments
 (0)