This repository was archived by the owner on Jul 3, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 393
Expand file tree
/
Copy pathinterpreter.ts
More file actions
2824 lines (2555 loc) · 97.3 KB
/
Copy pathinterpreter.ts
File metadata and controls
2824 lines (2555 loc) · 97.3 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
/*
* Copyright 2015 Mozilla Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
module Shumway.AVM1 {
import isNumeric = Shumway.isNumeric;
import notImplemented = Shumway.Debug.notImplemented;
import Telemetry = Shumway.Telemetry;
import assert = Shumway.Debug.assert;
declare var Proxy;
declare class Error {
constructor(obj: string);
}
declare class InternalError extends Error {
constructor(obj: string);
}
export var Debugger = {
pause: false,
breakpoints: {}
};
function avm1Warn(message: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any) {
if (avm1ErrorsEnabled.value) {
try {
throw new Error(message); // using throw as a way to break in browsers debugger
} catch (e) { /* ignoring since handled */ }
}
if (avm1WarningsEnabled.value) {
Debug.warning.apply(console, arguments);
}
}
export var MAX_AVM1_HANG_TIMEOUT = 1000;
export var CHECK_AVM1_HANG_EVERY = 1000;
var MAX_AVM1_ERRORS_LIMIT = 1000;
var MAX_AVM1_STACK_LIMIT = 256;
enum AVM1ScopeListItemFlags {
DEFAULT = 0,
TARGET = 1,
REPLACE_TARGET = 2
}
class AVM1ScopeListItem {
flags: AVM1ScopeListItemFlags;
replaceTargetBy: AVM1Object; // Very optional, set when REPLACE_TARGET used
constructor (public scope: AVM1Object, public previousScopeItem: AVM1ScopeListItem) {
this.flags = AVM1ScopeListItemFlags.DEFAULT;
}
}
// Similar to function scope, mostly for 'this'.
class GlobalPropertiesScope extends AVM1Object {
constructor(context: AVM1Context, thisArg: AVM1Object) {
super(context);
this.alSetOwnProperty('this', new AVM1PropertyDescriptor(AVM1PropertyFlags.DATA |
AVM1PropertyFlags.DONT_ENUM |
AVM1PropertyFlags.DONT_DELETE |
AVM1PropertyFlags.READ_ONLY,
thisArg));
this.alSetOwnProperty('_global', new AVM1PropertyDescriptor(AVM1PropertyFlags.DATA |
AVM1PropertyFlags.DONT_ENUM |
AVM1PropertyFlags.DONT_DELETE |
AVM1PropertyFlags.READ_ONLY,
context.globals));
}
}
class AVM1CallFrame {
public inSequence: boolean;
public calleeThis: AVM1Object;
public calleeSuper: AVM1Object; // set if super call was used
public calleeFn: AVM1Function;
public calleeArgs: any[];
constructor(public previousFrame: AVM1CallFrame,
public currentThis: AVM1Object,
public fn: AVM1Function,
public args: any[],
public ectx: ExecutionContext) {
this.inSequence = !previousFrame ? false :
(previousFrame.calleeThis === currentThis && previousFrame.calleeFn === fn);
this.resetCallee();
}
setCallee(thisArg: AVM1Object, superArg: AVM1Object, fn: AVM1Function, args: any[]) {
this.calleeThis = thisArg;
this.calleeSuper = superArg;
this.calleeFn = fn;
if (!release) {
this.calleeArgs = args;
}
}
resetCallee() {
this.calleeThis = null;
this.calleeSuper = null;
this.calleeFn = null;
}
}
class AVM1RuntimeUtilsImpl implements IAVM1RuntimeUtils {
private _context: AVM1Context;
constructor(context: AVM1Context) {
this._context = context;
}
public hasProperty(obj, name): boolean {
return as2HasProperty(this._context, obj, name);
}
public getProperty(obj, name): any {
return as2GetProperty(this._context, obj, name);
}
public setProperty(obj, name, value: any): void {
return as2SetProperty(this._context, obj, name, value);
}
public warn(msg: string): void {
avm1Warn.apply(null, arguments);
}
}
class AVM1ContextImpl extends AVM1Context {
initialScope: AVM1ScopeListItem;
isActive: boolean;
executionProhibited: boolean;
abortExecutionAt: number;
actionTracer: ActionTracer;
stackDepth: number;
frame: AVM1CallFrame;
isTryCatchListening: boolean;
errorsIgnored: number;
deferScriptExecution: boolean;
actions: Lib.AVM1NativeActions;
constructor(loaderInfo: Shumway.AVMX.AS.flash.display.LoaderInfo) {
var swfVersion = loaderInfo.swfVersion;
super(swfVersion);
this.loaderInfo = loaderInfo;
this.sec = loaderInfo.sec; // REDUX:
this.globals = Lib.AVM1Globals.createGlobalsObject(this);
this.actions = new Lib.AVM1NativeActions(this);
this.initialScope = new AVM1ScopeListItem(this.globals, null);
this.utils = new AVM1RuntimeUtilsImpl(this);
this.isActive = false;
this.executionProhibited = false;
this.actionTracer = avm1TraceEnabled.value ? new ActionTracer() : null;
this.abortExecutionAt = 0;
this.stackDepth = 0;
this.frame = null;
this.isTryCatchListening = false;
this.errorsIgnored = 0;
this.deferScriptExecution = true;
}
_getExecutionContext(): ExecutionContext {
// We probably entering this function from some native function,
// so faking execution context. Let's reuse last created context.
return this.frame.ectx;
}
resolveTarget(target: any) : any {
var ectx = this._getExecutionContext();
return avm1ResolveTarget(ectx, target, true);
}
resolveRoot() : any {
var ectx = this._getExecutionContext();
return avm1ResolveRoot(ectx);
}
checkTimeout() {
if (Date.now() >= this.abortExecutionAt) {
throw new AVM1CriticalError('long running script -- AVM1 instruction hang timeout');
}
}
pushCallFrame(thisArg: AVM1Object, fn: AVM1Function, args: any[], ectx: ExecutionContext) : AVM1CallFrame {
var nextFrame = new AVM1CallFrame(this.frame, thisArg, fn, args, ectx);
this.frame = nextFrame;
return nextFrame;
}
popCallFrame() {
var previousFrame = this.frame.previousFrame;
this.frame = previousFrame;
return previousFrame;
}
executeActions(actionsData: AVM1ActionsData, scopeObj): void {
if (this.executionProhibited) {
return; // no more avm1 for this context
}
var savedIsActive = this.isActive;
if (!savedIsActive) {
this.isActive = true;
this.abortExecutionAt = avm1TimeoutDisabled.value ?
Number.MAX_VALUE : Date.now() + MAX_AVM1_HANG_TIMEOUT;
this.errorsIgnored = 0;
}
var caughtError;
try {
executeActionsData(this, actionsData, scopeObj);
} catch (e) {
caughtError = e;
}
this.isActive = savedIsActive;
if (caughtError) {
// Note: this doesn't use `finally` because that's a no-go for performance.
throw caughtError;
}
}
public executeFunction(fn: AVM1Function, thisArg, args: any[]): any {
if (this.executionProhibited) {
return; // no more avm1 for this context
}
var savedIsActive = this.isActive;
if (!savedIsActive) {
this.isActive = true;
this.abortExecutionAt = avm1TimeoutDisabled.value ?
Number.MAX_VALUE : Date.now() + MAX_AVM1_HANG_TIMEOUT;
this.errorsIgnored = 0;
}
var caughtError;
var result;
try {
result = fn.alCall(thisArg, args);
} catch (e) {
caughtError = e;
}
this.isActive = savedIsActive;
if (caughtError) {
// Note: this doesn't use `finally` because that's a no-go for performance.
throw caughtError;
}
return result;
}
}
AVM1Context.create = function(loaderInfo: Shumway.AVMX.AS.flash.display.LoaderInfo): AVM1Context {
return new AVM1ContextImpl(loaderInfo);
};
class AVM1Error {
constructor(public error) {}
}
class AVM1CriticalError extends Error {
constructor(message: string, public error?) {
super(message);
}
}
function isAVM1MovieClip(obj): boolean {
return typeof obj === 'object' && obj &&
obj instanceof Lib.AVM1MovieClip;
}
function as2GetType(v): string {
if (v === null) {
return 'null';
}
var type = typeof v;
if (typeof v === 'object') {
if (v instanceof Lib.AVM1MovieClip) {
return 'movieclip';
}
if (v instanceof AVM1Function) {
return 'function';
}
}
return type;
}
function as2ToAddPrimitive(context: AVM1Context, value: any): any {
return alToPrimitive(context, value);
}
/**
* Performs "less" comparison of two arugments.
* @returns {boolean} Returns true if x is less than y, otherwise false
*/
function as2Compare(context: AVM1Context, x: any, y: any): boolean {
var x2 = alToPrimitive(context, x);
var y2 = alToPrimitive(context, y);
if (typeof x2 === 'string' && typeof y2 === 'string') {
var xs = alToString(context, x2), ys = alToString(context, y2);
return xs < ys;
} else {
var xn = alToNumber(context, x2), yn = alToNumber(context, y2);
return isNaN(xn) || isNaN(yn) ? undefined : xn < yn;
}
}
/**
* Performs equality comparison of two arugments. The equality comparison
* algorithm from EcmaScript 3, Section 11.9.3 is applied.
* http://ecma-international.org/publications/files/ECMA-ST-ARCH/ECMA-262,%203rd%20edition,%20December%201999.pdf#page=67
* @returns {boolean} Coerces x and y to the same type and returns true if they're equal, false otherwise.
*/
function as2Equals(context: AVM1Context, x: any, y: any): boolean {
// Spec steps 1 through 13 can be condensed to ...
if (typeof x === typeof y) {
return x === y;
}
// Spec steps 14 and 15.
if (x == null && y == null) {
return true;
}
// Spec steps 16 and 17.
if (typeof x === 'number' && typeof y === 'string') {
// Unfolding the recursion for `as2Equals(context, x, alToNumber(y))`
return y === '' ? false : x === +y; // in AVM1, ToNumber('') === NaN
}
if (typeof x === 'string' && typeof y === 'number') {
// Unfolding the recursion for `as2Equals(context, alToNumber(x), y)`
return x === '' ? false : +x === y; // in AVM1, ToNumber('') === NaN
}
// Spec step 18.
if (typeof x === 'boolean') {
// Unfolding the recursion for `as2Equals(context, alToNumber(x), y)`
x = +x; // typeof x === 'number'
if (typeof y === 'number' || typeof y === 'string') {
return y === '' ? false : x === +y;
}
// Fall through for typeof y === 'object', 'boolean', 'undefined' cases
}
// Spec step 19.
if (typeof y === 'boolean') {
// Unfolding the recursion for `as2Equals(context, x, alToNumber(y))`
y = +y; // typeof y === 'number'
if (typeof x === 'number' || typeof x === 'string') {
return x === '' ? false : +x === y;
}
// Fall through for typeof x === 'object', 'undefined' cases
}
// Spec step 20.
if ((typeof x === 'number' || typeof x === 'string') &&
typeof y === 'object' && y !== null) {
y = alToPrimitive(context, y);
if (typeof y === 'object') {
return false; // avoiding infinite recursion
}
return as2Equals(context, x, y);
}
// Spec step 21.
if (typeof x === 'object' && x !== null &&
(typeof y === 'number' || typeof y === 'string')) {
x = alToPrimitive(context, x);
if (typeof x === 'object') {
return false; // avoiding infinite recursion
}
return as2Equals(context, x, y);
}
return false;
}
function as2InstanceOf(obj, constructor): boolean {
// TODO refactor this -- quick and dirty hack for now
if (isNullOrUndefined(obj) || isNullOrUndefined(constructor)) {
return false;
}
if (constructor === Shumway.AVMX.AS.ASString) {
return typeof obj === 'string';
} else if (constructor === Shumway.AVMX.AS.ASNumber) {
return typeof obj === 'number';
} else if (constructor === Shumway.AVMX.AS.ASBoolean) {
return typeof obj === 'boolean';
} else if (constructor === Shumway.AVMX.AS.ASArray) {
return Array.isArray(obj);
} else if (constructor === Shumway.AVMX.AS.ASFunction) {
return typeof obj === 'function';
} else if (constructor === Shumway.AVMX.AS.ASObject) {
return typeof obj === 'object';
}
var baseProto = constructor.alGetPrototypeProperty();
if (!baseProto) {
return false;
}
var proto = obj;
while (proto) {
if (proto === baseProto) {
return true; // found the type if the chain
}
proto = proto.alPrototype;
}
// TODO interface check
return false;
}
function as2HasProperty(context: AVM1Context, obj: any, name: any): boolean {
var avm1Obj: AVM1Object = alToObject(context, obj);
name = context.normalizeName(name);
return avm1Obj.alHasProperty(name);
}
function as2GetProperty(context: AVM1Context, obj: any, name: any): any {
var avm1Obj: AVM1Object = alToObject(context, obj);
return avm1Obj.alGet(name);
}
function as2SetProperty(context: AVM1Context, obj: any, name: any, value: any): void {
var avm1Obj: AVM1Object = alToObject(context, obj);
avm1Obj.alPut(name, value);
as2SyncEvents(context, name);
}
function as2DeleteProperty(context: AVM1Context, obj: any, name: any): any {
var avm1Obj: AVM1Object = alToObject(context, obj);
name = context.normalizeName(name);
var result = avm1Obj.alDeleteProperty(name);
as2SyncEvents(context, name);
return result;
}
function as2SyncEvents(context: AVM1Context, name): void {
name = alCoerceString(context, name);
if (name[0] !== 'o' || name[1] !== 'n') { // TODO check case?
return;
}
// Maybe an event property, trying to broadcast change.
(<AVM1ContextImpl>context).broadcastEventPropertyChange(name);
}
function as2CastError(ex) {
if (typeof InternalError !== 'undefined' &&
ex instanceof InternalError && (<any>ex).message === 'too much recursion') {
// HACK converting too much recursion into AVM1CriticalError
return new AVM1CriticalError('long running script -- AVM1 recursion limit is reached');
}
return ex;
}
function as2Construct(ctor, args) {
var result;
if (alIsFunction(ctor)) {
result = (<AVM1Function>ctor).alConstruct(args);
} else {
// AVM1 simply ignores attempts to invoke non-methods.
return undefined;
}
return result;
}
function as2Enumerate(obj, fn: (name) => void, thisArg): void {
var processed = Object.create(null); // TODO remove/refactor
alForEachProperty(obj, function (name) {
if (processed[name]) {
return; // skipping already reported properties
}
fn.call(thisArg, name);
processed[name] = true;
}, thisArg);
}
function avm1FindSuperPropertyOwner(context: AVM1Context, frame: AVM1CallFrame, propertyName: string): AVM1Object {
if (context.swfVersion < 6) {
return null;
}
var proto: AVM1Object = (frame.inSequence && frame.previousFrame.calleeSuper);
if (!proto) {
// Finding first object in prototype chain link that has the property.
proto = frame.currentThis;
while (proto && !proto.alHasOwnProperty(propertyName)) {
proto = proto.alPrototype;
}
if (!proto) {
return null;
}
}
// Skipping one chain link
proto = proto.alPrototype;
return proto;
}
var DEFAULT_REGISTER_COUNT = 4;
function executeActionsData(context: AVM1ContextImpl, actionsData: AVM1ActionsData, scope) {
var actionTracer = context.actionTracer;
var globalPropertiesScopeList = new AVM1ScopeListItem(
new GlobalPropertiesScope(context, scope), context.initialScope);
var scopeList = new AVM1ScopeListItem(scope, globalPropertiesScopeList);
scopeList.flags |= AVM1ScopeListItemFlags.TARGET;
var caughtError;
release || (actionTracer && actionTracer.message('ActionScript Execution Starts'));
release || (actionTracer && actionTracer.indent());
var ectx = ExecutionContext.create(context, scopeList, [], DEFAULT_REGISTER_COUNT);
context.pushCallFrame(scope, null, null, ectx);
try {
interpretActionsData(ectx, actionsData);
} catch (e) {
caughtError = as2CastError(e);
}
ectx.dispose();
if (caughtError instanceof AVM1CriticalError) {
context.executionProhibited = true;
console.error('Disabling AVM1 execution');
}
context.popCallFrame();
release || (actionTracer && actionTracer.unindent());
release || (actionTracer && actionTracer.message('ActionScript Execution Stops'));
if (caughtError) {
// Note: this doesn't use `finally` because that's a no-go for performance.
throw caughtError; // TODO shall we just ignore it?
}
}
function createBuiltinType(context: AVM1Context, cls, args: any[]): any {
var builtins = context.builtins;
var obj = undefined;
if (cls === builtins.Array || cls === builtins.Object ||
cls === builtins.Date || cls === builtins.String ||
cls === builtins.Function) {
obj = cls.alConstruct(args);
}
if (cls === builtins.Boolean || cls === builtins.Number) {
obj = cls.alConstruct(args).value;
}
if (obj instanceof AVM1Object) {
var desc = new AVM1PropertyDescriptor(AVM1PropertyFlags.DATA | AVM1PropertyFlags.DONT_ENUM,
cls);
(<AVM1Object>obj).alSetOwnProperty('__constructor__', desc);
}
return obj;
}
class AVM1SuperWrapper extends AVM1Object {
public callFrame: AVM1CallFrame;
public constructor(context: AVM1Context, callFrame: AVM1CallFrame) {
super(context);
this.callFrame = callFrame;
this.alPrototype = context.builtins.Object.alGetPrototypeProperty();
}
}
class AVM1Arguments extends Natives.AVM1ArrayNative {
public constructor(context: AVM1Context, args: any[],
callee: AVM1Function, caller: AVM1Function) {
super(context, args);
alDefineObjectProperties(this, {
callee: {
value: callee
},
caller: {
value: caller
}
});
}
}
class ExecutionContext {
static MAX_CACHED_EXECUTIONCONTEXTS = 20;
static cache: ExecutionContext[];
static alInitStatic() {
this.cache = [];
}
context: AVM1ContextImpl;
actions: Lib.AVM1NativeActions;
scopeList: AVM1ScopeListItem;
constantPool: any[];
registers: any[];
stack: any[];
frame: AVM1CallFrame;
isSwfVersion5: boolean;
recoveringFromError: boolean;
isEndOfActions: boolean;
constructor(context: AVM1ContextImpl, scopeList: AVM1ScopeListItem, constantPool: any[], registerCount: number) {
this.context = context;
this.actions = context.actions;
this.isSwfVersion5 = context.swfVersion >= 5;
this.registers = [];
this.stack = [];
this.frame = null;
this.recoveringFromError = false;
this.isEndOfActions = false;
this.reset(scopeList, constantPool, registerCount);
}
reset(scopeList: AVM1ScopeListItem, constantPool: any[], registerCount: number) {
this.scopeList = scopeList;
this.constantPool = constantPool;
this.registers.length = registerCount;
}
clean(): void {
this.scopeList = null;
this.constantPool = null;
this.registers.length = 0;
this.stack.length = 0;
this.frame = null;
this.recoveringFromError = false;
this.isEndOfActions = false;
}
pushScope(newScopeList?: AVM1ScopeListItem): ExecutionContext {
var newContext = <ExecutionContext>Object.create(this);
newContext.stack = [];
if (!isNullOrUndefined(newScopeList)) {
newContext.scopeList = newScopeList;
}
return newContext;
}
dispose() {
this.clean();
var state: typeof ExecutionContext = this.context.getStaticState(ExecutionContext);
if (state.cache.length < ExecutionContext.MAX_CACHED_EXECUTIONCONTEXTS) {
state.cache.push(this);
}
}
static create(context: AVM1ContextImpl, scopeList: AVM1ScopeListItem, constantPool: any[], registerCount: number): ExecutionContext {
var state: typeof ExecutionContext = context.getStaticState(ExecutionContext);
var ectx: ExecutionContext;
if (state.cache.length > 0) {
ectx = state.cache.pop();
ectx.reset(scopeList, constantPool, registerCount);
} else {
ectx = new ExecutionContext(context, scopeList, constantPool, registerCount);
}
return ectx;
}
}
/**
* Interpreted function closure.
*/
class AVM1InterpreterScope extends AVM1Object {
constructor(context: AVM1ContextImpl) {
super(context);
this.alPut('toString', new AVM1NativeFunction(context, this._toString));
}
_toString() {
// It shall return 'this'
return this;
}
}
class AVM1InterpretedFunction extends AVM1EvalFunction {
functionName: string;
actionsData: AVM1ActionsData;
parametersNames: string[];
registersAllocation: ArgumentAssignment[];
suppressArguments: ArgumentAssignmentType;
scopeList: AVM1ScopeListItem;
constantPool: any[];
skipArguments: boolean[];
registersLength: number;
constructor(context: AVM1ContextImpl,
ectx: ExecutionContext,
actionsData: AVM1ActionsData,
functionName: string,
parametersNames: string[],
registersCount: number,
registersAllocation: ArgumentAssignment[],
suppressArguments: ArgumentAssignmentType) {
super(context);
this.functionName = functionName;
this.actionsData = actionsData;
this.parametersNames = parametersNames;
this.registersAllocation = registersAllocation;
this.suppressArguments = suppressArguments;
this.scopeList = ectx.scopeList;
this.constantPool = ectx.constantPool;
var skipArguments: boolean[] = null;
var registersAllocationCount = !registersAllocation ? 0 : registersAllocation.length;
for (var i = 0; i < registersAllocationCount; i++) {
var registerAllocation = registersAllocation[i];
if (registerAllocation &&
registerAllocation.type === ArgumentAssignmentType.Argument) {
if (!skipArguments) {
skipArguments = [];
}
skipArguments[registersAllocation[i].index] = true;
}
}
this.skipArguments = skipArguments;
var registersLength = Math.min(registersCount, 255); // max allowed for DefineFunction2
registersLength = Math.max(registersLength, registersAllocationCount + 1);
this.registersLength = registersLength;
}
public alCall(thisArg: any, args?: any[]): any {
var currentContext = <AVM1ContextImpl>this.context;
if (currentContext.executionProhibited) {
return; // no more avm1 execution, ever
}
var newScope = new AVM1InterpreterScope(currentContext);
var newScopeList = new AVM1ScopeListItem(newScope, this.scopeList);
var oldScope = this.scopeList.scope;
thisArg = thisArg || oldScope; // REDUX no isGlobalObject check?
args = args || [];
var ectx = ExecutionContext.create(currentContext, newScopeList,
this.constantPool, this.registersLength);
var caller = currentContext.frame ? currentContext.frame.fn : undefined;
var frame = currentContext.pushCallFrame(thisArg, this, args, ectx);
var supperWrapper;
var suppressArguments = this.suppressArguments;
if (!(suppressArguments & ArgumentAssignmentType.Arguments)) {
newScope.alPut('arguments', new AVM1Arguments(currentContext, args, this, caller));
}
if (!(suppressArguments & ArgumentAssignmentType.This)) {
newScope.alPut('this', thisArg);
}
if (!(suppressArguments & ArgumentAssignmentType.Super)) {
supperWrapper = new AVM1SuperWrapper(currentContext, frame);
newScope.alPut('super', supperWrapper);
}
var i;
var registers = ectx.registers;
var registersAllocation = this.registersAllocation;
var registersAllocationCount = !registersAllocation ? 0 : registersAllocation.length;
for (i = 0; i < registersAllocationCount; i++) {
var registerAllocation = registersAllocation[i];
if (registerAllocation) {
switch (registerAllocation.type) {
case ArgumentAssignmentType.Argument:
registers[i] = args[registerAllocation.index];
break;
case ArgumentAssignmentType.This:
registers[i] = thisArg;
break;
case ArgumentAssignmentType.Arguments:
registers[i] = new AVM1Arguments(currentContext, args, this, caller);
break;
case ArgumentAssignmentType.Super:
supperWrapper = supperWrapper || new AVM1SuperWrapper(currentContext, frame);
registers[i] = supperWrapper;
break;
case ArgumentAssignmentType.Global:
registers[i] = currentContext.globals;
break;
case ArgumentAssignmentType.Parent:
registers[i] = oldScope.alGet('_parent');
break;
case ArgumentAssignmentType.Root:
registers[i] = avm1ResolveRoot(ectx);
break;
}
}
}
var parametersNames = this.parametersNames;
var skipArguments = this.skipArguments;
for (i = 0; i < args.length || i < parametersNames.length; i++) {
if (skipArguments && skipArguments[i]) {
continue;
}
newScope.alPut(parametersNames[i], args[i]);
}
var result;
var caughtError;
var actionTracer = currentContext.actionTracer;
var actionsData = this.actionsData;
release || (actionTracer && actionTracer.indent());
if (++currentContext.stackDepth >= MAX_AVM1_STACK_LIMIT) {
throw new AVM1CriticalError('long running script -- AVM1 recursion limit is reached');
}
try {
result = interpretActionsData(ectx, actionsData);
} catch (e) {
caughtError = e;
}
currentContext.stackDepth--;
currentContext.popCallFrame();
ectx.dispose();
release || (actionTracer && actionTracer.unindent());
if (caughtError) {
// Note: this doesn't use `finally` because that's a no-go for performance.
throw caughtError;
}
return result;
}
}
function fixArgsCount(numArgs: number /* int */, maxAmount: number): number {
if (isNaN(numArgs) || numArgs < 0) {
avm1Warn('Invalid amount of arguments: ' + numArgs);
return 0;
}
numArgs |= 0;
if (numArgs > maxAmount) {
avm1Warn('Truncating amount of arguments: from ' + numArgs + ' to ' + maxAmount);
return maxAmount;
}
return numArgs;
}
function avm1ReadFunctionArgs(stack: any[]) {
var numArgs = +stack.pop();
numArgs = fixArgsCount(numArgs, stack.length);
var args = [];
for (var i = 0; i < numArgs; i++) {
args.push(stack.pop());
}
return args;
}
function avm1SetTarget(ectx: ExecutionContext, targetPath: string) {
var newTarget = null;
if (targetPath) {
try {
newTarget = avm1ResolveTarget(ectx, targetPath, false);
if (!avm1IsTarget(newTarget)) {
avm1Warn('Invalid AVM1 target object: ' + targetPath);
newTarget = undefined;
}
} catch (e) {
avm1Warn('Unable to set target: ' + e);
}
}
if (newTarget) {
ectx.scopeList.flags |= AVM1ScopeListItemFlags.REPLACE_TARGET;
ectx.scopeList.replaceTargetBy = newTarget;
} else {
ectx.scopeList.flags &= ~AVM1ScopeListItemFlags.REPLACE_TARGET;
ectx.scopeList.replaceTargetBy = null;
}
}
function isGlobalObject(obj) {
return obj === this;
}
function avm1DefineFunction(ectx: ExecutionContext,
actionsData: AVM1ActionsData,
functionName: string,
parametersNames: string[],
registersCount: number,
registersAllocation: ArgumentAssignment[],
suppressArguments: ArgumentAssignmentType): AVM1Function {
return new AVM1InterpretedFunction(ectx.context, ectx, actionsData, functionName,
parametersNames, registersCount, registersAllocation, suppressArguments);
}
function avm1VariableNameHasPath(variableName: string): boolean {
return variableName && (variableName.indexOf('.') >= 0 || variableName.indexOf(':') >= 0 || variableName.indexOf('/') >= 0 );
}
const enum AVM1ResolveVariableFlags {
READ = 1,
WRITE = 2,
DELETE = READ,
GET_VALUE = 32,
DISALLOW_TARGET_OVERRIDE = 64,
ONLY_TARGETS = 128
}
interface IAVM1ResolvedVariableResult {
scope: AVM1Object;
propertyName: string;
value: any;
}
var cachedResolvedVariableResult: IAVM1ResolvedVariableResult = {
scope: null,
propertyName: null,
value: undefined
};
function avm1IsTarget(target): boolean {
// TODO refactor
return target instanceof AVM1Object && Lib.hasAS3ObjectReference(target);
}
function avm1ResolveSimpleVariable(scopeList: AVM1ScopeListItem, variableName: string, flags: AVM1ResolveVariableFlags): IAVM1ResolvedVariableResult {
release || Debug.assert(alIsName(scopeList.scope.context, variableName));
var currentTarget;
var resolved = cachedResolvedVariableResult;
for (var p = scopeList; p; p = p.previousScopeItem) {
if ((p.flags & AVM1ScopeListItemFlags.REPLACE_TARGET) &&
!(flags & AVM1ResolveVariableFlags.DISALLOW_TARGET_OVERRIDE) &&
!currentTarget) {
currentTarget = p.replaceTargetBy;
}
if ((p.flags & AVM1ScopeListItemFlags.TARGET)) {
if ((flags & AVM1ResolveVariableFlags.WRITE)) {
// last scope/target we can modify (exclude globals)
resolved.scope = currentTarget || p.scope;
resolved.propertyName = variableName;
resolved.value = (flags & AVM1ResolveVariableFlags.GET_VALUE) ? resolved.scope.alGet(variableName) : undefined;
return resolved;
}
if ((flags & AVM1ResolveVariableFlags.READ) && currentTarget) {
if (currentTarget.alHasProperty(variableName)) {
resolved.scope = currentTarget;
resolved.propertyName = variableName;
resolved.value = (flags & AVM1ResolveVariableFlags.GET_VALUE) ? currentTarget.alGet(variableName) : undefined;
return resolved;
}
continue;
}
}
if (p.scope.alHasProperty(variableName)) {
resolved.scope = p.scope;
resolved.propertyName = variableName;
resolved.value = (flags & AVM1ResolveVariableFlags.GET_VALUE) ? p.scope.alGet(variableName) : undefined;
return resolved;
}
}
release || Debug.assert(!(flags & AVM1ResolveVariableFlags.WRITE));
return undefined;
}
function avm1ResolveVariable(ectx: ExecutionContext, variableName: string, flags: AVM1ResolveVariableFlags): IAVM1ResolvedVariableResult {
// For now it is just very much magical -- designed to pass some of the swfdec tests
// FIXME refactor
release || Debug.assert(variableName);
// Canonicalizing the name here is ok even for paths: the only thing that (potentially)
// happens is that the name is converted to lower-case, which is always valid for paths.
// The original name is saved because the final property name needs to be extracted from
// it for property name paths.
var originalName = variableName;
variableName = ectx.context.normalizeName(variableName);
if (!avm1VariableNameHasPath(variableName)) {
return avm1ResolveSimpleVariable(ectx.scopeList, variableName, flags);
}
var i = 0, j = variableName.length;
var markedAsTarget = true;
var resolved, ch, needsScopeResolution;
var propertyName = null, scope = null, obj = undefined;
if (variableName[0] === '/') {
resolved = avm1ResolveSimpleVariable(ectx.scopeList, '_root', AVM1ResolveVariableFlags.READ | AVM1ResolveVariableFlags.GET_VALUE);
if (resolved) {
propertyName = resolved.propertyName;
scope = resolved.scope;
obj = resolved.value;
}
i++;
needsScopeResolution = false;
} else {
resolved = null;
needsScopeResolution = true;
}
if (i >= j) {
return resolved;
}
var q = i;
while (i < j) {
if (!needsScopeResolution && !(obj instanceof AVM1Object)) {
avm1Warn('Unable to resolve variable on invalid object ' + variableName.substring(q, i - 1) + ' (expr ' + variableName + ')');
return null;
}
var propertyName;
var q = i;
if (variableName[i] === '.' && variableName[i + 1] === '.') {
i += 2;
propertyName = '_parent';
} else {
while (i < j && ((ch = variableName[i]) !== '/' && ch !== '.' && ch !== ':')) {
i++;
}