forked from ircmaxell/php-compiler
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVM.php
More file actions
executable file
·7990 lines (7501 loc) · 334 KB
/
VM.php
File metadata and controls
executable file
·7990 lines (7501 loc) · 334 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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/*
* This file is part of PHP-Compiler, a PHP CFG Compiler for PHP code
*
* @copyright 2015 Anthony Ferrara. All rights reserved
* @license MIT See LICENSE at the root of the project for more info
*/
namespace PHPCompiler;
require_once __DIR__.'/OpCodeNames.php';
use PHPCompiler\Compiler\AttributeNames;
use PHPCompiler\Compiler\NoDiscardMetadata;
use PHPCompiler\Func;
use PHPCompiler\ext\standard\VmEval;
use PHPCompiler\ext\standard\VmForwardStaticCall;
use PHPCompiler\VM\Context;
use PHPCompiler\VM\CastSupport;
use PHPCompiler\VM\ClassEntry;
use PHPCompiler\VM\DnfCheck;
use PHPCompiler\VM\ClosureState;
use PHPCompiler\VM\EnumCaseEntry;
use PHPCompiler\VM\EnumCaseSupport;
use PHPCompiler\VM\ErrorReporter;
use PHPCompiler\VM\FiberState;
use PHPCompiler\VM\GeneratorState;
use PHPCompiler\VM\HashTable;
use PHPCompiler\VM\IterableCheck;
use PHPCompiler\VM\NamedArgs;
use PHPCompiler\VM\ObjectEntry;
use PHPCompiler\VM\ObjectLifetime;
use PHPCompiler\VM\ObjectPropertyIterator;
use PHPCompiler\VM\ReferencableCheck;
use PHPCompiler\VM\ScriptExit;
use PHPCompiler\VM\TypeCheck;
use PHPCompiler\VM\TypedPropertyReadSignal;
use PHPCompiler\VM\WeakRefRegistry;
use PHPCompiler\VM\Variable;
use PHPCompiler\Web\Superglobals;
class VM {
const SUCCESS = 1;
const FAILURE = 2;
private static ?self $running = null;
/** @internal Active VM during runFrames (#3429 typed property errors). */
public static function running(): ?self
{
return self::$running;
}
/** Generator body suspended at `yield` (issue #167). */
const GENERATOR_YIELD = 3;
/** Fiber callback suspended at Fiber::suspend() (issue #3130). */
const FIBER_SUSPEND = 4;
public Context $context;
public function __construct(Context $context) {
$this->context = $context;
}
public function run(Block $block): int {
ObjectLifetime::setVm($this);
try {
if (!is_null($block->handler)) {
$frame = $block->getFrame($this->context);
$this->seedScriptPath($frame);
$block->handler->execute($frame);
return self::SUCCESS;
}
$frame = $block->getFrame($this->context);
$this->seedScriptPath($frame);
$this->context->push($frame);
$result = $this->runFrames();
if ('' !== $frame->scriptPath) {
$this->context->scriptStack->pop();
}
return $result;
} finally {
ObjectLifetime::runShutdownDestructors();
ObjectLifetime::clearVm();
}
}
/**
* Invoke a user-defined PHP function from a VM builtin (isolated run stack).
*/
public function invokePhpFunction(Func\PHP $func, Variable ...$args): Variable
{
if ($this->context->coercingObjectToString) {
return $this->invokePhpFunctionForCoercion($func, ...$args);
}
return $this->invokePhpFunctionOnStack($func, ...$args);
}
/**
* @param Variable ...$args
*/
private function invokePhpFunctionOnStack(Func\PHP $func, ...$args): Variable
{
if ($func->block->isGenerator) {
$state = new GeneratorState($this, $func, [...$args]);
$out = new Variable();
$out->object($state->wrapObject());
return $out;
}
$child = $func->getFrame($this->context, null);
$child->calledArgs = $args;
if (
[] !== $args
&& null !== $func->block->func
&& null !== $func->block->func->class
) {
$thisIdx = $func->block->slotIndexForVariableName('this');
if (null !== $thisIdx) {
$child->scope[$thisIdx] = $args[0];
}
}
$out = new Variable();
$child->returnVar = $out;
$this->context->push($child);
$result = $this->runFrames();
if (self::SUCCESS !== $result) {
throw new \LogicException('User function invocation failed in this compiler build');
}
if ($this->context->magicMethodThrowHandled) {
$this->context->magicMethodThrowHandled = false;
throw new VM\MagicMethodInvocationAborted();
}
return $out->resolveIndirect();
}
/**
* Isolated __toString / coercion invoke — must not run the caller script in nested runFrames (#4284).
*
* @param Variable ...$args
*/
private function invokePhpFunctionForCoercion(Func\PHP $func, ...$args): Variable
{
$savedStack = $this->context->swapRunStack(null);
try {
$result = $this->invokePhpFunctionOnStack($func, ...$args);
$this->context->swapRunStack($savedStack);
return $result;
} catch (\Throwable $native) {
$this->context->swapRunStack($savedStack);
if (null !== $savedStack) {
$thrown = $native instanceof \Error
? VM\BuiltinExceptionSupport::materializeError($this->context, $native->getMessage())
: $this->makeEngineError($native->getMessage(), 'Exception');
$catchFrame = $this->findCatchFrameForThrow($savedStack->frame, $thrown);
if (null !== $catchFrame) {
$this->context->swapRunStack($savedStack);
$catchStack = $this->context->swapRunStack(null);
$this->context->push($catchFrame);
$catchResult = $this->runFrames();
$this->context->swapRunStack($catchStack);
$this->clearTryCatchUnwindState();
if (self::SUCCESS !== $catchResult) {
throw new \LogicException('Coercion catch handler failed in this compiler build');
}
throw new VM\MagicMethodInvocationAborted();
}
}
throw $native;
} catch (VM\MagicMethodInvocationAborted $aborted) {
if (!$this->context->hasRunStack()) {
$this->context->swapRunStack($savedStack);
}
throw $aborted;
} catch (\Throwable $e) {
if (!$this->context->hasRunStack()) {
$this->context->swapRunStack($savedStack);
}
throw $e;
}
}
/**
* Invoke a static method in the caller's late-static scope (forward_static_call, #3197).
*/
public function invokeStaticWithCalledScope(
string $calledScopeClass,
string $methodName,
Variable ...$args
): Variable {
$func = VmForwardStaticCall::resolveStaticMethod($this->context, $calledScopeClass, $methodName);
$savedStack = $this->context->swapRunStack(null);
try {
$child = $func->getFrame($this->context, null);
$child->calledClass = $calledScopeClass;
$child->calledArgs = $args;
$out = new Variable();
$child->returnVar = $out;
$this->context->push($child);
$result = $this->runFrames();
if (self::SUCCESS !== $result) {
throw new \LogicException('Static method invocation failed in this compiler build');
}
return $out->resolveIndirect();
} finally {
$this->context->swapRunStack($savedStack);
}
}
/**
* Walk inheritance for an instance method (Zend zend_object_handlers parity, #3259).
*
* @return array{0: ClassEntry, 1: string}
*/
public function resolveInstanceMethod(ClassEntry $class, string $methodLc): array
{
$methodLc = strtolower($methodLc);
$lcClass = strtolower($class->name);
$visited = [];
$abstractDecl = null;
while (!isset($visited[$lcClass])) {
$visited[$lcClass] = true;
if (!isset($this->context->classes[$lcClass])) {
break;
}
$entry = $this->context->classes[$lcClass];
if (isset($entry->methods[$methodLc])) {
return [$entry, $methodLc];
}
if (isset($entry->abstractMethods[$methodLc])) {
$abstractDecl ??= $entry;
}
if (null === $entry->parentLc) {
break;
}
$lcClass = $entry->parentLc;
}
if (null !== $abstractDecl) {
$declName = $abstractDecl->methodNames[$methodLc] ?? $methodLc;
throw new \LogicException("Cannot call abstract method {$abstractDecl->name}::{$declName}()");
}
$declName = $class->methodNames[$methodLc] ?? $methodLc;
throw new \LogicException("Call to undefined method {$class->name}::{$declName}()");
}
public function hasInstanceMethod(ClassEntry $class, string $methodLc): bool
{
$methodLc = strtolower($methodLc);
$lcClass = strtolower($class->name);
$visited = [];
while (!isset($visited[$lcClass])) {
$visited[$lcClass] = true;
if (!isset($this->context->classes[$lcClass])) {
return false;
}
$entry = $this->context->classes[$lcClass];
if (isset($entry->methods[$methodLc])) {
return true;
}
if (null === $entry->parentLc) {
return false;
}
$lcClass = $entry->parentLc;
}
return false;
}
/** Coerce a VM value to string, invoking __toString on objects when defined (issue #3296). */
public function coerceVariableToString(Variable $var, ?Frame $frame = null): string
{
$var = $var->resolveIndirect();
if (Variable::TYPE_OBJECT !== $var->type) {
return $var->toString($this, $frame);
}
$object = $var->toObject();
if (EnumCaseSupport::isEnumCase($object)) {
throw new \Error("Object of class {$object->class->name} could not be converted to string");
}
if (!$this->hasInstanceMethod($object->class, '__tostring')) {
return 'Object';
}
$this->context->coercingObjectToString = true;
try {
$result = $this->invokeInstanceMethod($object, '__toString')->resolveIndirect();
} finally {
$this->context->coercingObjectToString = false;
}
return $result->toString($this, $frame);
}
/** Invoke a user instance method from VM internals (e.g. __debugInfo, #3259). */
public function invokeInstanceMethod(ObjectEntry $object, string $methodName, Variable ...$extraArgs): Variable
{
$methodLc = strtolower($methodName);
[$declaring] = $this->resolveInstanceMethod($object->class, $methodLc);
$func = $declaring->methods[$methodLc];
if (!$func instanceof Func\PHP) {
throw new \LogicException("{$declaring->name}::{$methodName}() is not a user method in this compiler build");
}
$thisVar = new Variable();
$thisVar->object($object);
return $this->invokePhpFunction($func, $thisVar, ...$extraArgs);
}
public function objectImplementsArrayAccess(ObjectEntry $object): bool
{
return VM\InterfaceCheck::entryImplements($object->class, 'arrayaccess', $this->context);
}
public function invokeArrayAccessOffsetGet(ObjectEntry $object, Variable $key): Variable
{
return $this->invokeInstanceMethod($object, 'offsetGet', $key);
}
public function invokeArrayAccessOffsetSet(ObjectEntry $object, Variable $key, Variable $value): void
{
$this->invokeInstanceMethod($object, 'offsetSet', $key, $value);
}
public function invokeArrayAccessOffsetExists(ObjectEntry $object, Variable $key): bool
{
return $this->invokeInstanceMethod($object, 'offsetExists', $key)->toBool();
}
public function invokeArrayAccessOffsetUnset(ObjectEntry $object, Variable $key): void
{
$this->invokeInstanceMethod($object, 'offsetUnset', $key);
}
/**
* isset($obj->prop) — Zend zend_std_has_property / __isset parity (#3298, #4586).
*/
public function objectPropertyIsSet(ObjectEntry $object, string $propName, ?Frame $frame = null): bool
{
if (null !== $frame) {
$meta = $this->classPropertyMeta($object, $propName);
$getLc = $meta?->getHookMethodLc
?? strtolower(SourcePreprocessor\PropertyHooks::getHookMethodName($propName));
if (isset($object->class->methods[$getLc])) {
// unset() clears backing storage; isset must not invoke get on uninitialized slot (#5191).
if (null !== $meta && null !== $meta->setHookMethodLc) {
$props = $object->getRawProperties();
if (isset($props[$propName])
&& VM\TypedPropertyCheck::isUninitialized($props[$propName])) {
return false;
}
}
$hookValue = $this->fetchPropertyWithHooks($object, $propName, $frame);
if (null !== $hookValue) {
$value = $hookValue->resolveIndirect();
return !$value->isUndefined() && Variable::TYPE_NULL !== $value->type;
}
}
}
$props = $object->getRawProperties();
if (isset($props[$propName])) {
$value = $props[$propName]->resolveIndirect();
if (!$value->isUndefined() && Variable::TYPE_NULL !== $value->type) {
return true;
}
return false;
}
if ($this->hasInstanceMethod($object->class, '__isset')) {
$key = new Variable();
$key->string($propName);
$result = $this->invokeInstanceMethod($object, '__isset', $key)->resolveIndirect();
return $result->toBool();
}
return false;
}
/**
* unset($obj->prop) — Zend zend_std_unset_property / __unset parity (#3298).
*/
public function unsetObjectProperty(ObjectEntry $object, string $propName): void
{
$props = $object->getRawProperties();
if (isset($props[$propName])) {
$object->unsetProperty($propName);
return;
}
if ($this->hasInstanceMethod($object->class, '__unset')) {
$key = new Variable();
$key->string($propName);
$this->invokeInstanceMethod($object, '__unset', $key);
}
}
/**
* True when $slot is an indirect binding shared with another local (Zend ref chain).
* Used by (unset) cast: only break references, not ordinary locals (#3517).
*
* @param array<int, Variable> $scope
*/
private function slotIsReferenceBinding(Variable $slot, array $scope): bool
{
if (Variable::TYPE_INDIRECT !== $slot->type) {
return false;
}
$target = $slot->resolveIndirect();
foreach ($scope as $other) {
if ($other === $slot) {
continue;
}
if ($other === $target || $other->resolveIndirect() === $target) {
return true;
}
}
return false;
}
/** (string) cast on objects — invoke __toString (Zend zend_operators.c, issue #3421). */
public function castObjectToString(ObjectEntry $object): string
{
if (EnumCaseSupport::isEnumCase($object)) {
throw new \Error(
'Object of class '.$object->class->name.' could not be converted to string'
);
}
$typeString = VM\ReflectionTypeSupport::tryObjectTypeString($object);
if (null !== $typeString) {
return $typeString;
}
if (!$this->hasInstanceMethod($object->class, '__tostring')) {
throw new \Error(
'Object of class '.$object->class->name.' could not be converted to string'
);
}
$this->context->coercingObjectToString = true;
try {
$result = $this->invokeInstanceMethod($object, '__toString')->resolveIndirect();
} finally {
$this->context->coercingObjectToString = false;
}
return $result->toString();
}
/**
* Convert a value to string for echo/print (Zend zend_print_variable parity, #3564).
*
* php-src: Zend/zend_operators.c — cast to string via __toString when defined.
*/
public function valueToPrintString(Variable $var, ?Frame $frame = null): string
{
$var = $var->resolveIndirect();
if (Variable::TYPE_ENUM_CASE === $var->type) {
throw new \Error(
'Object of class '.$var->toEnumCase()->enumClass->name.' could not be converted to string'
);
}
if (Variable::TYPE_OBJECT !== $var->type) {
return $var->toString($this, $frame);
}
$object = $var->toObject();
if (EnumCaseSupport::isEnumCase($object)) {
throw new \Error("Object of class {$object->class->name} could not be converted to string");
}
if (!$this->hasInstanceMethod($object->class, '__tostring')) {
throw new \Error("Object of class {$object->class->name} could not be converted to string");
}
$this->context->coercingObjectToString = true;
try {
$result = $this->invokeInstanceMethod($object, '__toString')->resolveIndirect();
} finally {
$this->context->coercingObjectToString = false;
}
return $result->toString($this, $frame);
}
/**
* Invoke Iterator protocol methods during foreach (Zend zend_iterators.c parity, #3234).
*/
public function invokeForeachInstanceMethod(Frame $_parentFrame, Variable $receiver, string $methodName): Variable
{
$methodLc = strtolower($methodName);
$object = $receiver->toObject();
$class = $object->class;
if (!isset($class->methods[$methodLc])) {
throw new \LogicException("Call to undefined method {$class->name}::{$methodLc}()");
}
$recv = new Variable();
$recv->copyFrom($receiver);
return $this->invokePhpFunction($class->methods[$methodLc], $recv);
}
/**
* Properties for var_dump / print_r when __debugInfo is defined (Zend parity, #3259).
*
* @return array<string, Variable>
*/
public function getObjectDebugProperties(ObjectEntry $object): array
{
if ($this->hasInstanceMethod($object->class, '__debuginfo')) {
$result = $this->invokeInstanceMethod($object, '__debugInfo')->resolveIndirect();
if (Variable::TYPE_ARRAY !== $result->type) {
$given = Variable::TYPE_OBJECT === $result->type
? $result->toObject()->class->name
: TypeCheck::typeNameForConstraint($result->type);
throw new \TypeError(
"{$object->class->name}::__debugInfo(): Return value must be of type array, {$given} returned"
);
}
$props = [];
foreach ($result->toArray()->iterateKeyed(true) as [$key, $value]) {
$name = Variable::TYPE_STRING === $key->type
? $key->toString()
: (string) $key->toInt();
$copy = new Variable();
$copy->copyFrom($value->resolveIndirect());
$props[$name] = $copy;
}
return $props;
}
return $object->class->getProperties($object->getRawProperties(), ClassEntry::PROP_PURPOSE_DEBUG);
}
/**
* Zend zend_check_clone: private/protected __clone() rejects external-scope clone (#5077).
*
* @return null when clone is allowed, or a catch frame when Error was dispatched
*/
protected function enforceCloneVisibility(ObjectEntry $object, Frame $frame): ?Frame
{
if (!$this->hasInstanceMethod($object->class, '__clone')) {
return null;
}
try {
[$declaringClass, $methodLc] = $this->resolveInstanceMethod($object->class, '__clone');
$vis = $declaringClass->methodVisibility[$methodLc] ?? \PHPCfg\Func::FLAG_PUBLIC;
$callerClassLc = $this->callerClassLc($frame);
$callerDisplay = null;
if (null !== $callerClassLc && isset($this->context->classes[$callerClassLc])) {
$callerDisplay = $this->context->classes[$callerClassLc]->name;
}
MethodVisibility::assertCallable(
$vis,
$callerClassLc,
strtolower($declaringClass->name),
$declaringClass->name,
'__clone',
false,
fn (string $classLc, string $ancestorLc): bool => $this->isClassSameOrSubclassOf($classLc, $ancestorLc),
$callerDisplay
);
} catch (\LogicException $e) {
$message = 'Trying to clone an uncloneable object of class '.$object->class->name;
return $this->dispatchVmError($message, $frame);
}
return null;
}
/**
* Zend object construction: private/protected inherited __construct() rejects external scope (#5382).
*
* @return null when construction may proceed, or a catch frame when Error was dispatched
*/
protected function enforceNewConstructorVisibility(ClassEntry $class, Frame $frame): ?Frame
{
if (null === $class->constructor && !$this->hasInstanceMethod($class, '__construct')) {
return null;
}
try {
[$declaringClass, $methodLc] = $this->resolveInstanceMethod($class, '__construct');
$vis = $declaringClass->methodVisibility[$methodLc] ?? \PHPCfg\Func::FLAG_PUBLIC;
$callerClassLc = $this->callerClassLc($frame);
$callerDisplay = null;
if (null !== $callerClassLc && isset($this->context->classes[$callerClassLc])) {
$callerDisplay = $this->context->classes[$callerClassLc]->name;
}
MethodVisibility::assertConstructorCallable(
$vis,
$callerClassLc,
strtolower($declaringClass->name),
$declaringClass->name,
false,
fn (string $classLc, string $ancestorLc): bool => $this->isClassSameOrSubclassOf($classLc, $ancestorLc),
$callerDisplay
);
} catch (\LogicException $e) {
return $this->dispatchVmError($e->getMessage(), $frame);
}
return null;
}
/**
* Zend zend_std_clone_object: shallow copy then user __clone() when defined (#3170).
*/
protected function invokeCloneMagicMethod(ObjectEntry $object): void
{
$class = $object->class;
if (!isset($class->methods['__clone'])) {
return;
}
$thisVar = new Variable(Variable::TYPE_OBJECT);
$thisVar->object($object);
$this->invokePhpFunction($class->methods['__clone'], $thisVar);
}
/**
* Zend zend_std_read_property / __get slow path (#146).
*/
protected function invokeMagicGet(ObjectEntry $object, string $name): Variable
{
if (!$this->hasInstanceMethod($object->class, '__get')) {
throw new \LogicException('Undefined property access');
}
$nameVar = new Variable(Variable::TYPE_STRING);
$nameVar->string($name);
return $this->invokeInstanceMethod($object, '__get', $nameVar);
}
/**
* Zend zend_std_write_property / __set slow path (#146).
*/
protected function invokeMagicSet(ObjectEntry $object, string $name, Variable $value): void
{
if (!$this->hasInstanceMethod($object->class, '__set')) {
throw new \LogicException('Undefined property access');
}
$nameVar = new Variable(Variable::TYPE_STRING);
$nameVar->string($name);
$valueCopy = new Variable();
$valueCopy->copyFrom($value);
$this->invokeInstanceMethod($object, '__set', $nameVar, $valueCopy);
}
/**
* True when zend_std_read_property must invoke __get (undeclared slot or inaccessible declared prop).
*/
protected function propertyReadUsesMagicGet(ObjectEntry $object, string $name, Frame $frame): bool
{
if (!$this->hasInstanceMethod($object->class, '__get')) {
return false;
}
$meta = $this->classPropertyMeta($object, $name);
if (null === $meta) {
return true;
}
$declaringDisplay = $this->context->classes[$meta->declaringClassLc]->name
?? $meta->declaringClassLc;
try {
PropertyVisibility::assertAccessible(
$meta->visibility,
$this->callerClassLc($frame),
$meta->declaringClassLc,
$declaringDisplay,
$name,
strtolower($object->class->name),
fn (string $classLc, string $ancestorLc): bool => $this->isClassSameOrSubclassOf($classLc, $ancestorLc)
);
return false;
} catch (\LogicException $e) {
return true;
}
}
/**
* Copy __get return into $result and mark for indirect-modify detection (#4673).
*/
protected function deliverMagicGetRead(Variable $result, ObjectEntry $object, string $name): void
{
$result->copyFrom($this->invokeMagicGet($object, $name));
$result->magicGetOverloadedTarget = $object;
$result->magicGetOverloadedName = $name;
}
/**
* Reject []= / dim-write on a value produced by __get (#4673).
*/
protected function rejectMagicGetIndirectModify(Variable $containerSlot, bool $forWrite, Frame $frame): ?Frame
{
if (!$forWrite) {
return null;
}
if (null === $containerSlot->magicGetOverloadedTarget || null === $containerSlot->magicGetOverloadedName) {
return null;
}
$class = $containerSlot->magicGetOverloadedTarget->class->name;
$prop = $containerSlot->magicGetOverloadedName;
return $this->dispatchVmError(sprintf(
'Indirect modification of overloaded property %s::$%s has no effect',
$class,
$prop
), $frame);
}
/**
* Resolve an instance property write lvalue, including __set / dynamic properties (#146).
*/
protected function fetchObjectPropertyWriteLvalue(ObjectEntry $object, string $name, Frame $frame): Variable
{
if ($object->hasProperty($name)) {
return $object->getProperty($name);
}
if ($object->class->readonly && !$this->hasInstanceMethod($object->class, '__set')) {
$thrown = VM\BuiltinExceptionSupport::materializeError(
$this->context,
sprintf('Cannot create dynamic property %s::$%s', $object->class->name, $name)
);
$this->raiseUncaughtException($thrown);
}
if ($this->hasInstanceMethod($object->class, '__set')) {
$proxy = new Variable();
$proxy->magicSetTarget = $object;
$proxy->magicSetName = $name;
return $proxy;
}
if ($this->instanceMethodReturnsByRef($object, '__get')) {
return $this->invokeMagicGet($object, $name);
}
if (!$object->class->allowsDynamicProperties) {
$scriptPath = $frame->scriptPath;
$this->context->errors->deprecatedDynamicProperty(
$object->class->name,
$name,
'' !== $scriptPath && '-' !== $scriptPath ? $scriptPath : null,
$this->context,
$frame
);
}
return $object->allocateProperty($name);
}
/**
* Invoke a closure from a VM builtin (isolated run stack; issue #72).
*/
public function invokeClosure(ClosureState $closureState, Variable ...$args): Variable
{
return $this->invokeClosureFrom(null, $closureState, true, ...$args);
}
/**
* Invoke a closure; when $isolated is false, run on the active stack (#4927 Closure::call).
*/
public function invokeClosureFrom(
?Frame $runParent,
ClosureState $closureState,
bool $isolated,
Variable ...$args
): Variable {
$savedStack = $isolated ? $this->context->swapRunStack(null) : null;
try {
$init = new Frame(null, $closureState->func->block, $runParent);
$init->vmContext = $this->context;
$this->initClosureCall($init, $closureState);
if (null === $init->call) {
throw new \LogicException('Closure invocation failed in this compiler build');
}
$parentForCallee = $runParent ?? (!empty($init->callArgs) ? $init : null);
$child = $init->call->getFrame($this->context, $parentForCallee);
$this->applyClosureBinding($child, $closureState);
$child->calledArgs = $args;
$out = new Variable();
$child->returnVar = $out;
if ($child->hasHandler()) {
$child->vmContext = $this->context;
$child->handler->execute($child);
return $out->resolveIndirect();
}
$this->context->push($child);
$result = $this->runFrames();
if (self::SUCCESS !== $result) {
throw new \LogicException('Closure invocation failed in this compiler build');
}
return $out->resolveIndirect();
} finally {
if ($isolated) {
$this->context->swapRunStack($savedStack);
}
}
}
/**
* Execute dynamically compiled eval() code in the caller variable scope (#3358).
*/
public function executeEvalBlock(Block $block, Frame $caller): Variable
{
$out = new Variable();
$child = $block->getFrame($this->context, $caller);
$child->ephemeral = true;
// Scope comes from getFrame($caller); parent must stay null so nested runFrames exits.
$child->parent = null;
$child->returnVar = $out;
$child->scriptPath = VmEval::EVAL_FILENAME;
$this->context->scriptStack->push($child->scriptPath);
try {
$this->context->push($child);
$result = $this->runFrames();
if (self::SUCCESS !== $result) {
throw new \LogicException('eval() execution failed in this compiler build');
}
} finally {
$this->context->scriptStack->pop();
}
return $out->resolveIndirect();
}
/**
* Start a new fiber (issue #3130).
*
* @param list<Variable> $startArgs
*/
public function startFiber(FiberState $fiber, Variable ...$startArgs): Variable
{
if (FiberState::STATUS_INIT !== $fiber->status) {
throw new VM\NativeFiberError('Cannot start a fiber that has already been started');
}
$fiber->resumeArgument->null();
$child = $fiber->callback->func->getFrame($this->context, null);
$this->bindClosureCallCaptures($child, $fiber->callback);
$child->calledArgs = $startArgs;
$child->fiberState = $fiber;
$returnSlot = new Variable();
$child->returnVar = $returnSlot;
$fiber->frame = $child;
$fiber->status = FiberState::STATUS_RUNNING;
return $this->runFiberExecution($fiber, $returnSlot);
}
/**
* Resume a suspended fiber (issue #3130).
*
* @param list<Variable> $resumeArgs
*/
public function resumeFiber(FiberState $fiber, Variable ...$resumeArgs): Variable
{
if (FiberState::STATUS_TERMINATED === $fiber->status) {
throw new VM\NativeFiberError('Cannot resume a fiber that is terminated');
}
if (FiberState::STATUS_SUSPENDED !== $fiber->status) {
throw new VM\NativeFiberError('Cannot resume a fiber that is not suspended');
}
if ([] !== $resumeArgs) {
$fiber->resumeArgument->copyFrom($resumeArgs[0]->resolveIndirect());
} else {
$fiber->resumeArgument->null();
}
if (null !== $fiber->pendingSuspendReturnVar) {
$fiber->pendingSuspendReturnVar->copyFrom($fiber->resumeArgument);
$fiber->pendingSuspendReturnVar = null;
}
$child = $fiber->frame;
if (null === $child) {
throw new \LogicException('Fiber resume missing suspended frame');
}
$fiber->status = FiberState::STATUS_RUNNING;
$returnSlot = new Variable();
$savedReturn = $child->returnVar;
$child->returnVar = $returnSlot;
try {
return $this->runFiberExecution($fiber, $returnSlot);
} finally {
$child->returnVar = $savedReturn;
}
}
/**
* Throw into a suspended fiber (Fiber->throw()) (Zend/zend_fibers.c parity, #4481).
*/
public function throwFiber(FiberState $fiber, Variable $exception): Variable
{
if (FiberState::STATUS_TERMINATED === $fiber->status) {
throw new VM\NativeFiberError('Cannot throw into a fiber that is terminated');
}
if (FiberState::STATUS_SUSPENDED !== $fiber->status) {
throw new VM\NativeFiberError('Cannot throw into a fiber that is not suspended');
}
$fiber->pendingThrow->copyFrom($exception->resolveIndirect());
$fiber->hasPendingThrow = true;
$fiber->resumeArgument->null();
$returnSlot = new Variable();
return $this->runFiberExecution($fiber, $returnSlot);
}
private function runFiberExecution(FiberState $fiber, Variable $returnSlot): Variable
{
$child = $fiber->frame;
if (null === $child) {
throw new \LogicException('Fiber execution missing frame');
}
$savedFiber = $this->context->currentFiber;
$this->context->currentFiber = $fiber;
$savedStack = $this->context->swapRunStack(null);
try {
$this->applyFiberPendingThrow($fiber);
$child = $fiber->frame;
if (null === $child) {
throw new \LogicException('Fiber execution missing frame after throw dispatch');
}
$this->context->push($child);
try {
$result = $this->runFrames();
} catch (\Throwable $e) {
$fiber->status = FiberState::STATUS_TERMINATED;
$fiber->frame = null;
$fiber->pendingSuspendReturnVar = null;
throw $e;
}
} finally {
$this->context->swapRunStack($savedStack);
$this->context->currentFiber = $savedFiber;
}
if (self::FIBER_SUSPEND === $result) {
$fiber->status = FiberState::STATUS_SUSPENDED;
$out = new Variable();
$out->copyFrom($fiber->suspendReturn);
return $out;
}
if (self::SUCCESS === $result) {
$fiber->status = FiberState::STATUS_TERMINATED;
$fiber->frame = null;
$out = new Variable();
$out->copyFrom($returnSlot->resolveIndirect());
return $out;
}
throw new \LogicException('Fiber execution failed in this compiler build');
}
private function findFiberState(Frame $frame): ?FiberState
{
while (null !== $frame) {
if (null !== $frame->fiberState) {
return $frame->fiberState;
}
$frame = $frame->parent;
}
return null;
}
private function applyFiberPendingThrow(FiberState $fiber): void
{
if (!$fiber->hasPendingThrow) {
return;
}
$thrown = new Variable();
$thrown->copyFrom($fiber->pendingThrow);
$fiber->hasPendingThrow = false;
$fiber->pendingThrow->null();
$frame = $fiber->frame;
if (null === $frame) {
$fiber->status = FiberState::STATUS_TERMINATED;
$this->raiseUncaughtException($thrown);
}
$this->context->pendingException = $thrown;
for ($handler = $frame; null !== $handler; $handler = $handler->parent) {
if ($handler->fiberState !== $fiber && $this->findFiberState($handler) !== $fiber) {
break;
}
$catchFrame = $this->dispatchCatchForHandlerFrame($handler);
if (null !== $catchFrame) {
$catchFrame->fiberState = $fiber;
$fiber->frame = $catchFrame;
return;
}