Repository navigation
Expand file tree
/
Copy pathbytecode-scan
More file actions
executable file
·454 lines (410 loc) · 14.7 KB
/
Copy pathbytecode-scan
File metadata and controls
executable file
·454 lines (410 loc) · 14.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
#!/usr/bin/env php
<?php
declare(strict_types=1);
/*
* Preflight scanner inspired by the Yakpro study. It does not obfuscate code;
* it reports dynamic PHP constructs that make future symbol rewriting risky
* and are useful diagnostics before bytecode packaging.
*/
function usage(): void
{
fwrite(STDERR, <<<'USAGE'
Usage: bytecode-scan [--json] [--fail-on-warning] [--config <bytecode.json>] [--exclude <glob>]... <source-file-or-dir>...
Scans PHP sources for dynamic constructs that can break source-level symbol
rewriting or make encoded-build debugging harder:
- variable variables
- dynamic function/class/property/method access
- define()/defined()/function_exists()/class_exists()/method_exists()
calls with non-literal names
- call_user_func()/call_user_func_array()/is_callable()
- callable arrays like [SomeClass::class, 'method']
- PDO::FETCH_OBJ
- enums, attributes, readonly classes, anonymous classes, trait adaptations
- eval(), Fiber usage, and other compatibility-sensitive runtime features
USAGE);
}
function fail(string $message, int $code = 1): never
{
fwrite(STDERR, $message . PHP_EOL);
exit($code);
}
function load_bytecode_config(?string $path): array
{
if ($path === null || $path === '') {
$candidate = getcwd() . DIRECTORY_SEPARATOR . 'bytecode.json';
if (!is_file($candidate)) {
return [];
}
$path = $candidate;
}
if (!is_file($path)) {
fail("config file does not exist: {$path}", 2);
}
$decoded = json_decode((string) file_get_contents($path), true);
if (!is_array($decoded)) {
fail("invalid JSON config: {$path}", 2);
}
return $decoded;
}
function config_list(array $config, string $key): array
{
$value = $config[$key] ?? [];
if ($value === null) {
return [];
}
if (!is_array($value)) {
fail("bytecode.json field '{$key}' must be an array", 2);
}
return array_values(array_filter($value, static fn (mixed $item): bool => is_string($item) && $item !== ''));
}
function scanner_config(array $config): array
{
$scanner = $config['scanner'] ?? [];
if ($scanner === null) {
return [];
}
if (!is_array($scanner)) {
fail("bytecode.json field 'scanner' must be an object", 2);
}
return $scanner;
}
function glob_to_regex(string $glob): string
{
$regex = '';
for ($i = 0, $n = strlen($glob); $i < $n; $i++) {
$c = $glob[$i];
$regex .= match ($c) {
'*' => '.*',
'?' => '.',
default => preg_quote($c, '#'),
};
}
return '#\A' . $regex . '\z#';
}
function is_excluded(string $rel, array $excludes): bool
{
foreach ($excludes as $pattern) {
if (preg_match(glob_to_regex($pattern), $rel)) {
return true;
}
}
return false;
}
function normalize_path(string $path): string
{
return str_replace('\\', '/', $path);
}
function collect_php_files(array $sources, array $excludes): array
{
$files = [];
foreach ($sources as $source) {
if (!file_exists($source)) {
fail("source does not exist: {$source}", 2);
}
$root = realpath($source);
if ($root === false) {
fail("cannot resolve source: {$source}", 2);
}
if (is_file($root)) {
if (strtolower(pathinfo($root, PATHINFO_EXTENSION)) === 'php') {
$files[$root] = $root;
}
continue;
}
$base = rtrim($root, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($root, FilesystemIterator::SKIP_DOTS),
);
foreach ($iterator as $entry) {
if (!$entry->isFile()) {
continue;
}
$path = $entry->getPathname();
if (strtolower(pathinfo($path, PATHINFO_EXTENSION)) !== 'php') {
continue;
}
$rel = normalize_path(substr($path, strlen($base)));
if (is_excluded($rel, $excludes)) {
continue;
}
$files[$path] = $path;
}
}
ksort($files);
return array_values($files);
}
function token_line(mixed $token): int
{
return is_array($token) ? $token[2] : 0;
}
function token_text(mixed $token): string
{
return is_array($token) ? $token[1] : $token;
}
function next_significant(array $tokens, int $index): ?array
{
for ($i = $index + 1, $n = count($tokens); $i < $n; $i++) {
$token = $tokens[$i];
if (is_array($token) && in_array($token[0], [T_WHITESPACE, T_COMMENT, T_DOC_COMMENT], true)) {
continue;
}
return [$i, $token];
}
return null;
}
function previous_significant(array $tokens, int $index): ?array
{
for ($i = $index - 1; $i >= 0; $i--) {
$token = $tokens[$i];
if (is_array($token) && in_array($token[0], [T_WHITESPACE, T_COMMENT, T_DOC_COMMENT], true)) {
continue;
}
return [$i, $token];
}
return null;
}
function first_call_arg_tokens(array $tokens, int $openParenIndex): array
{
$depth = 0;
$arg = [];
for ($i = $openParenIndex + 1, $n = count($tokens); $i < $n; $i++) {
$text = token_text($tokens[$i]);
if ($text === '(' || $text === '[' || $text === '{') {
$depth++;
} elseif ($text === ')' || $text === ']' || $text === '}') {
if ($depth === 0) {
break;
}
$depth--;
} elseif ($text === ',' && $depth === 0) {
break;
}
if (is_array($tokens[$i]) && in_array($tokens[$i][0], [T_WHITESPACE, T_COMMENT, T_DOC_COMMENT], true)) {
continue;
}
$arg[] = $tokens[$i];
}
return $arg;
}
function first_arg_is_literal_string(array $tokens, int $openParenIndex): bool
{
$arg = first_call_arg_tokens($tokens, $openParenIndex);
return count($arg) === 1
&& is_array($arg[0])
&& $arg[0][0] === T_CONSTANT_ENCAPSED_STRING;
}
function add_warning(array &$warnings, string $file, int $line, string $code, string $message): void
{
$warnings[] = [
'file' => $file,
'line' => max(1, $line),
'code' => $code,
'message' => $message,
];
}
function filter_warnings(array $warnings, array $ignoreCodes): array
{
if ($ignoreCodes === []) {
return $warnings;
}
$ignore = array_flip($ignoreCodes);
return array_values(array_filter(
$warnings,
static fn (array $warning): bool => !isset($ignore[$warning['code']]),
));
}
function scan_file(string $file): array
{
$source = file_get_contents($file);
if ($source === false) {
fail("cannot read {$file}");
}
$warnings = [];
$tokens = token_get_all($source);
$regexChecks = [
['#\$\s*(?:\$|\{)#', 'variable-variable', 'variable variables depend on runtime names and block safe variable rewriting'],
['#\bnew\s+\$#i', 'dynamic-class', 'dynamic class instantiation depends on runtime class names'],
['#\bnew\s+class\b#i', 'anonymous-class', 'anonymous classes need explicit bytecode loader coverage before production encoding'],
['#\benum\s+[A-Za-z_\x80-\xff][A-Za-z0-9_\x80-\xff]*#', 'enum', 'enum case objects are not yet supported by the loader and should fail closed at dump time'],
['#\breadonly\s+class\b#i', 'readonly-class', 'readonly classes rely on exact property metadata; verify promoted/private properties after encoding'],
['#\#\[\s*[A-Za-z_\\\\]#', 'attribute', 'attributes should be included in compatibility testing for framework reflection paths'],
['#\buse\s+[A-Za-z_\\\\][^;{}]*\{#s', 'trait-adaptation', 'trait adaptations need explicit loader support before production encoding'],
['#\beval\s*\(#i', 'eval', 'eval() compiles source at runtime and cannot be pre-encoded'],
['#\bFiber\s*(?:::|\\()#', 'fiber', 'Fiber control flow should be covered by project-level runtime tests after encoding'],
['#(?:->|::)\s*(?:\$|\{)#', 'dynamic-member', 'dynamic property/method/member access depends on runtime names'],
['#\[\s*[^\\]]*::class\s*,\s*(["\'])#s', 'callable-array', 'callable array contains a literal method name that must stay in sync if methods are renamed'],
['#PDO\s*::\s*FETCH_OBJ#i', 'pdo-fetch-obj', 'PDO::FETCH_OBJ hydrates object properties by name; property rewriting can break it'],
];
foreach ($regexChecks as [$pattern, $code, $message]) {
if (preg_match_all($pattern, $source, $matches, PREG_OFFSET_CAPTURE)) {
foreach ($matches[0] as $match) {
$line = substr_count(substr($source, 0, $match[1]), "\n") + 1;
add_warning($warnings, $file, $line, $code, $message);
}
}
}
$literalNameFunctions = [
'define' => 'define() with non-literal constant name cannot be safely renamed',
'defined' => 'defined() with non-literal constant name cannot be safely renamed',
'function_exists' => 'function_exists() with non-literal function name cannot be safely renamed',
'class_exists' => 'class_exists() with non-literal class name cannot be safely renamed',
'interface_exists' => 'interface_exists() with non-literal interface name cannot be safely renamed',
'trait_exists' => 'trait_exists() with non-literal trait name cannot be safely renamed',
'method_exists' => 'method_exists() with non-literal method name cannot be safely renamed',
'property_exists' => 'property_exists() with non-literal property name cannot be safely renamed',
'constant' => 'constant() with non-literal constant name cannot be safely renamed',
];
$dynamicDispatchFunctions = [
'call_user_func' => 'call_user_func() uses runtime callable names; symbol rewriting needs an explicit policy',
'call_user_func_array' => 'call_user_func_array() uses runtime callable names; symbol rewriting needs an explicit policy',
'is_callable' => 'is_callable() often references runtime callable names; symbol rewriting needs an explicit policy',
];
for ($i = 0, $n = count($tokens); $i < $n; $i++) {
$token = $tokens[$i];
if (is_array($token) && $token[0] === T_VARIABLE) {
$next = next_significant($tokens, $i);
if ($next !== null && token_text($next[1]) === '(') {
$previous = previous_significant($tokens, $i);
$previousKind = is_array($previous[1] ?? null) ? $previous[1][0] : null;
$previousText = $previous === null ? '' : token_text($previous[1]);
if ($previousKind === T_NEW || $previousText === '->' || $previousText === '::') {
continue;
}
add_warning(
$warnings,
$file,
$token[2],
'dynamic-function-call',
'variable function call depends on runtime function names',
);
}
}
if (!is_array($token) || $token[0] !== T_STRING) {
continue;
}
$name = strtolower($token[1]);
$next = next_significant($tokens, $i);
if ($next === null || token_text($next[1]) !== '(') {
continue;
}
$previous = previous_significant($tokens, $i);
if ($previous !== null) {
$prevText = token_text($previous[1]);
if ($prevText === '->' || $prevText === '::' || $prevText === '\\') {
continue;
}
}
if (isset($literalNameFunctions[$name]) && !first_arg_is_literal_string($tokens, $next[0])) {
add_warning($warnings, $file, $token[2], 'nonliteral-symbol-name', $literalNameFunctions[$name]);
}
if (isset($dynamicDispatchFunctions[$name])) {
add_warning($warnings, $file, $token[2], 'dynamic-dispatch', $dynamicDispatchFunctions[$name]);
}
}
usort(
$warnings,
fn (array $a, array $b): int => [$a['file'], $a['line'], $a['code']] <=> [$b['file'], $b['line'], $b['code']],
);
return $warnings;
}
$args = array_slice($argv, 1);
if (isset($args[0]) && in_array($args[0], ['-h', '--help'], true)) {
usage();
exit(0);
}
$json = false;
$failOnWarning = false;
$configPath = null;
$excludes = [];
while ($args) {
$arg = $args[0];
if ($arg === '--json') {
$json = true;
array_shift($args);
continue;
}
if ($arg === '--fail-on-warning') {
$failOnWarning = true;
array_shift($args);
continue;
}
if ($arg === '--config') {
array_shift($args);
if (!$args) {
fail('--config requires a JSON config file', 2);
}
$configPath = array_shift($args);
continue;
}
if (str_starts_with($arg, '--config=')) {
$configPath = substr($arg, strlen('--config='));
array_shift($args);
continue;
}
if ($arg === '--exclude') {
array_shift($args);
if (!$args) {
fail('--exclude requires a glob pattern', 2);
}
$excludes[] = array_shift($args);
continue;
}
if (str_starts_with($arg, '--exclude=')) {
$excludes[] = substr($arg, strlen('--exclude='));
array_shift($args);
continue;
}
if ($arg === '--') {
array_shift($args);
break;
}
if ($arg !== '' && $arg[0] === '-') {
usage();
exit(2);
}
break;
}
if (!$args) {
usage();
exit(2);
}
$config = load_bytecode_config($configPath);
$scanner = scanner_config($config);
$excludes = array_values(array_unique([...config_list($config, 'exclude'), ...$excludes]));
$ignoreCodes = config_list($scanner, 'ignore_codes');
if (($scanner['fail_on_warning'] ?? false) === true) {
$failOnWarning = true;
}
$files = collect_php_files($args, $excludes);
$warnings = [];
foreach ($files as $file) {
array_push($warnings, ...scan_file($file));
}
$warnings = filter_warnings($warnings, $ignoreCodes);
if ($json) {
echo json_encode(
[
'format' => 'bytecode-scan-v1',
'files_scanned' => count($files),
'warning_count' => count($warnings),
'warnings' => $warnings,
],
JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES,
), PHP_EOL;
} else {
foreach ($warnings as $warning) {
fwrite(
STDOUT,
sprintf(
"%s:%d [%s] %s%s",
$warning['file'],
$warning['line'],
$warning['code'],
$warning['message'],
PHP_EOL,
),
);
}
fwrite(STDOUT, sprintf("bytecode-scan: scanned %d file(s), %d warning(s)%s", count($files), count($warnings), PHP_EOL));
}
exit($failOnWarning && $warnings !== [] ? 1 : 0);