This repository has been archived by the owner on Feb 12, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 421
/
Copy pathResidualHeapVisitor.js
1396 lines (1282 loc) · 53.6 KB
/
ResidualHeapVisitor.js
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 (c) 2017-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
/* @flow */
import { GlobalEnvironmentRecord, DeclarativeEnvironmentRecord, EnvironmentRecord } from "../environment.js";
import { CompilerDiagnostic, FatalError } from "../errors.js";
import { type Effects, Realm } from "../realm.js";
import { Path } from "../singletons.js";
import type { Descriptor, PropertyBinding, ObjectKind } from "../types.js";
import type { Binding } from "../environment.js";
import { HashSet, IsArray, Get } from "../methods/index.js";
import {
AbstractObjectValue,
AbstractValue,
BoundFunctionValue,
ECMAScriptFunctionValue,
ECMAScriptSourceFunctionValue,
EmptyValue,
FunctionValue,
NativeFunctionValue,
ObjectValue,
ProxyValue,
StringValue,
SymbolValue,
Value,
} from "../values/index.js";
import { describeLocation } from "../intrinsics/ecma262/Error.js";
import * as t from "@babel/types";
import type { BabelNodeBlockStatement } from "@babel/types";
import { Generator } from "../utils/generator.js";
import type { GeneratorEntry, VisitEntryCallbacks } from "../utils/generator.js";
import traverse from "@babel/traverse";
import invariant from "../invariant.js";
import type {
AdditionalFunctionEffects,
AdditionalFunctionInfo,
ClassMethodInstance,
FunctionInfo,
FunctionInstance,
ResidualFunctionBinding,
ReferentializationScope,
Scope,
ResidualHeapInfo,
} from "./types.js";
import { ClosureRefVisitor } from "./visitors.js";
import { Logger } from "../utils/logger.js";
import { Modules } from "../utils/modules.js";
import { HeapInspector } from "../utils/HeapInspector.js";
import { Referentializer } from "./Referentializer.js";
import {
canIgnoreClassLengthProperty,
ClassPropertiesToIgnore,
getObjectPrototypeMetadata,
getOrDefault,
getSuggestedArrayLiteralLength,
withDescriptorValue,
} from "./utils.js";
import { Environment, To } from "../singletons.js";
import { isReactElement, isReactPropsObject, valueIsReactLibraryObject } from "../react/utils.js";
import { ResidualReactElementVisitor } from "./ResidualReactElementVisitor.js";
import { GeneratorDAG } from "./GeneratorDAG.js";
type BindingState = {|
capturedBindings: Set<ResidualFunctionBinding>,
capturingFunctions: Set<FunctionValue>,
|};
/* This class visits all values that are reachable in the residual heap.
In particular, this "filters out" values that are:
- captured by a DeclarativeEnvironmentRecord, but not actually used by any closure.
- Unmodified prototype objects
TODO #680: Figure out minimal set of values that need to be kept alive for WeakSet and WeakMap instances.
*/
export class ResidualHeapVisitor {
constructor(
realm: Realm,
logger: Logger,
modules: Modules,
additionalFunctionValuesAndEffects: Map<FunctionValue, AdditionalFunctionEffects>,
// Referentializer is null if we're just checking what values exist
referentializer: Referentializer | "NO_REFERENTIALIZE"
) {
invariant(realm.useAbstractInterpretation);
this.realm = realm;
this.logger = logger;
this.modules = modules;
this.referentializer = referentializer === "NO_REFERENTIALIZE" ? undefined : referentializer;
this.declarativeEnvironmentRecordsBindings = new Map();
this.globalBindings = new Map();
this.functionInfos = new Map();
this.classMethodInstances = new Map();
this.functionInstances = new Map();
this.values = new Map();
this.conditionalFeasibility = new Map();
let generator = this.realm.generator;
invariant(generator);
this.scope = this.globalGenerator = generator;
this.inspector = new HeapInspector(realm, logger);
this.referencedDeclaredValues = new Map();
this.delayedActions = [];
this.additionalFunctionValuesAndEffects = additionalFunctionValuesAndEffects;
this.equivalenceSet = new HashSet();
this.additionalFunctionValueInfos = new Map();
this.functionToCapturedScopes = new Map();
let environment = realm.$GlobalEnv.environmentRecord;
invariant(environment instanceof GlobalEnvironmentRecord);
this.globalEnvironmentRecord = environment;
this.additionalGeneratorRoots = new Map();
this.residualReactElementVisitor = new ResidualReactElementVisitor(this.realm, this);
this.generatorDAG = new GeneratorDAG();
}
realm: Realm;
logger: Logger;
modules: Modules;
referentializer: Referentializer | void;
globalGenerator: Generator;
// Caches that ensure one ResidualFunctionBinding exists per (record, name) pair
declarativeEnvironmentRecordsBindings: Map<DeclarativeEnvironmentRecord, Map<string, ResidualFunctionBinding>>;
globalBindings: Map<string, ResidualFunctionBinding>;
functionToCapturedScopes: Map<ReferentializationScope, Map<DeclarativeEnvironmentRecord, BindingState>>;
functionInfos: Map<BabelNodeBlockStatement, FunctionInfo>;
scope: Scope;
values: Map<Value, Set<Scope>>;
// For every abstract value of kind "conditional", this map keeps track of whether the consequent and/or alternate is feasible in any scope
conditionalFeasibility: Map<AbstractValue, { t: boolean, f: boolean }>;
inspector: HeapInspector;
referencedDeclaredValues: Map<Value, void | FunctionValue>;
delayedActions: Array<{| scope: Scope, action: () => void | boolean |}>;
additionalFunctionValuesAndEffects: Map<FunctionValue, AdditionalFunctionEffects>;
functionInstances: Map<FunctionValue, FunctionInstance>;
additionalFunctionValueInfos: Map<FunctionValue, AdditionalFunctionInfo>;
equivalenceSet: HashSet<AbstractValue>;
classMethodInstances: Map<FunctionValue, ClassMethodInstance>;
// Parents will always be a generator, optimized function value or "GLOBAL"
additionalGeneratorRoots: Map<Generator, Set<ObjectValue>>;
generatorDAG: GeneratorDAG;
globalEnvironmentRecord: GlobalEnvironmentRecord;
residualReactElementVisitor: ResidualReactElementVisitor;
// Going backwards from the current scope, find either the containing
// additional function, or if there isn't one, return the global generator.
_getCommonScope(): FunctionValue | Generator {
let s = this.scope;
while (true) {
if (s instanceof Generator) s = this.generatorDAG.getParent(s);
else if (s instanceof FunctionValue) {
// Did we find an additional function?
if (this.additionalFunctionValuesAndEffects.has(s)) return s;
// Did the function itself get created by a generator we can chase?
s = this.generatorDAG.getCreator(s) || "GLOBAL";
} else {
invariant(s === "GLOBAL");
let generator = this.globalGenerator;
invariant(generator);
return generator;
}
}
invariant(false);
}
// If the current scope has a containing additional function, retrieve it.
_getAdditionalFunctionOfScope(): FunctionValue | void {
let s = this._getCommonScope();
return s instanceof FunctionValue ? s : undefined;
}
// When a value has been created by some generator that is unrelated
// to the current common scope, visit the value in the scope it was
// created --- this causes the value later to be serialized in its
// creation scope, ensuring that the value has the right creation / life time.
_registerAdditionalRoot(value: ObjectValue): void {
let creationGenerator = this.generatorDAG.getCreator(value) || this.globalGenerator;
let additionalFunction = this._getAdditionalFunctionOfScope() || "GLOBAL";
let targetAdditionalFunction;
if (creationGenerator === this.globalGenerator) {
targetAdditionalFunction = "GLOBAL";
} else {
let s = creationGenerator;
while (s instanceof Generator) {
s = this.generatorDAG.getParent(s);
invariant(s !== undefined);
}
invariant(s === "GLOBAL" || s instanceof FunctionValue);
targetAdditionalFunction = s;
}
let usageScope;
if (additionalFunction === targetAdditionalFunction) {
usageScope = this.scope;
} else {
// Object was created outside of current additional function scope
invariant(additionalFunction instanceof FunctionValue);
let additionalFVEffects = this.additionalFunctionValuesAndEffects.get(additionalFunction);
invariant(additionalFVEffects !== undefined);
additionalFVEffects.additionalRoots.add(value);
this._visitInUnrelatedScope(creationGenerator, value);
usageScope = this.generatorDAG.getCreator(value) || this.globalGenerator;
}
usageScope = this.scope;
if (usageScope instanceof Generator) {
// Also check if object is used in some nested generator scope that involved
// applying effects; if so, store additional information that the serializer
// can use to proactive serialize such objects from within the right generator
let anyRelevantEffects = false;
for (let g = usageScope; g instanceof Generator; g = this.generatorDAG.getParent(g)) {
if (g === creationGenerator) {
if (anyRelevantEffects) {
let s = this.additionalGeneratorRoots.get(g);
if (s === undefined) this.additionalGeneratorRoots.set(g, (s = new Set()));
if (!s.has(value)) {
s.add(value);
this._visitInUnrelatedScope(g, value);
}
}
break;
}
let effectsToApply = g.effectsToApply;
if (effectsToApply)
for (let pb of effectsToApply.modifiedProperties.keys())
if (pb.object === value) {
anyRelevantEffects = true;
break;
}
}
}
}
// Careful!
// Only use _withScope when you know that the currently applied effects makes sense for the given (nested) scope!
_withScope(scope: Scope, f: () => void): void {
let oldScope = this.scope;
this.scope = scope;
try {
f();
} finally {
this.scope = oldScope;
}
}
// Queues up an action to be later processed in some arbitrary scope.
_enqueueWithUnrelatedScope(scope: Scope, action: () => void | boolean): void {
// If we are in a zone with a non-default equivalence set (we are wrapped in a `withCleanEquivalenceSet` call) then
// we need to save our equivalence set so that we may load it before running our action.
if (this.residualReactElementVisitor.defaultEquivalenceSet === false) {
const save = this.residualReactElementVisitor.saveEquivalenceSet();
const originalAction = action;
action = () => this.residualReactElementVisitor.loadEquivalenceSet(save, originalAction);
}
this.delayedActions.push({ scope, action });
}
// Queues up visiting a value in some arbitrary scope.
_visitInUnrelatedScope(scope: Scope, val: Value): void {
let scopes = this.values.get(val);
if (scopes !== undefined && scopes.has(scope)) return;
this._enqueueWithUnrelatedScope(scope, () => this.visitValue(val));
}
visitObjectProperty(binding: PropertyBinding): void {
let desc = binding.descriptor;
let obj = binding.object;
invariant(binding.key !== undefined, "Undefined keys should never make it here.");
if (
obj instanceof AbstractObjectValue ||
!(typeof binding.key === "string" && this.inspector.canIgnoreProperty(obj, binding.key))
) {
if (desc !== undefined) this.visitDescriptor(desc);
}
if (binding.key instanceof Value) this.visitValue(binding.key);
}
visitObjectProperties(obj: ObjectValue, kind?: ObjectKind): void {
// In non-instant render mode, properties of leaked objects are generated via assignments
let { skipPrototype, constructor } = getObjectPrototypeMetadata(this.realm, obj);
if (obj.temporalAlias !== undefined) return;
// visit properties
for (let [symbol, propertyBinding] of obj.symbols) {
invariant(propertyBinding);
let desc = propertyBinding.descriptor;
if (desc === undefined) continue; //deleted
this.visitDescriptor(desc);
this.visitValue(symbol);
}
// visit properties
for (let [propertyBindingKey, propertyBindingValue] of obj.properties) {
// we don't want to visit these as we handle the serialization ourselves
// via a different logic route for classes
let descriptor = propertyBindingValue.descriptor;
if (
obj instanceof ECMAScriptFunctionValue &&
obj.$FunctionKind === "classConstructor" &&
(ClassPropertiesToIgnore.has(propertyBindingKey) ||
(propertyBindingKey === "length" && canIgnoreClassLengthProperty(obj, descriptor, this.logger)))
) {
continue;
}
if (propertyBindingValue.pathNode !== undefined) continue; // property is written to inside a loop
// Leaked object. Properties are set via assignments
// TODO #2259: Make deduplication in the face of leaking work for custom accessors
if (
!obj.mightNotBeHavocedObject() &&
(descriptor !== undefined && (descriptor.get === undefined && descriptor.set === undefined))
)
continue;
invariant(propertyBindingValue);
this.visitObjectProperty(propertyBindingValue);
}
// inject properties with computed names
if (obj.unknownProperty !== undefined) {
let desc = obj.unknownProperty.descriptor;
if (desc !== undefined) {
let val = desc.value;
invariant(val instanceof AbstractValue);
this.visitObjectPropertiesWithComputedNames(val);
}
}
// prototype
if (!skipPrototype) {
this.visitObjectPrototype(obj);
}
if (obj instanceof FunctionValue) {
this.visitConstructorPrototype(constructor ? constructor : obj);
} else if (obj instanceof ObjectValue && skipPrototype && constructor) {
this.visitValue(constructor);
}
}
visitObjectPrototype(obj: ObjectValue): void {
let proto = obj.$Prototype;
let kind = obj.getKind();
if (proto === this.realm.intrinsics[kind + "Prototype"]) return;
if (!obj.$IsClassPrototype || proto !== this.realm.intrinsics.null) {
this.visitValue(proto);
}
}
visitConstructorPrototype(func: Value): void {
// If the original prototype object was mutated,
// request its serialization here as this might be observable by
// residual code.
invariant(func instanceof FunctionValue);
let prototype = HeapInspector.getPropertyValue(func, "prototype");
if (
prototype instanceof ObjectValue &&
prototype.originalConstructor === func &&
!this.inspector.isDefaultPrototype(prototype)
) {
this.visitValue(prototype);
}
}
visitObjectPropertiesWithComputedNames(absVal: AbstractValue): void {
if (absVal.kind === "widened property") return;
if (absVal.kind === "template for prototype member expression") return;
if (absVal.kind === "conditional") {
let cond = absVal.args[0];
invariant(cond instanceof AbstractValue);
if (cond.kind === "template for property name condition") {
let P = cond.args[0];
invariant(P instanceof AbstractValue);
let V = absVal.args[1];
let earlier_props = absVal.args[2];
if (earlier_props instanceof AbstractValue) this.visitObjectPropertiesWithComputedNames(earlier_props);
this.visitValue(P);
this.visitValue(V);
} else {
// conditional assignment
absVal.args[0] = this.visitEquivalentValue(cond);
let consequent = absVal.args[1];
if (consequent instanceof AbstractValue) {
this.visitObjectPropertiesWithComputedNames(consequent);
}
let alternate = absVal.args[2];
if (alternate instanceof AbstractValue) {
this.visitObjectPropertiesWithComputedNames(alternate);
}
}
} else {
this.visitValue(absVal);
}
}
visitDescriptor(desc: Descriptor): void {
invariant(desc.value === undefined || desc.value instanceof Value);
if (desc.joinCondition !== undefined) {
desc.joinCondition = this.visitEquivalentValue(desc.joinCondition);
if (desc.descriptor1 !== undefined) this.visitDescriptor(desc.descriptor1);
if (desc.descriptor2 !== undefined) this.visitDescriptor(desc.descriptor2);
return;
}
if (desc.value !== undefined) desc.value = this.visitEquivalentValue(desc.value);
if (desc.get !== undefined) this.visitValue(desc.get);
if (desc.set !== undefined) this.visitValue(desc.set);
}
visitValueArray(val: ObjectValue): void {
this._registerAdditionalRoot(val);
this.visitObjectProperties(val);
const realm = this.realm;
let lenProperty;
if (val.mightBeHavocedObject()) {
lenProperty = this.realm.evaluateWithoutLeakLogic(() => Get(realm, val, "length"));
} else {
lenProperty = Get(realm, val, "length");
}
let [initialLength, lengthAssignmentNotNeeded] = getSuggestedArrayLiteralLength(realm, val);
if (lengthAssignmentNotNeeded) return;
if (
lenProperty instanceof AbstractValue
? lenProperty.kind !== "widened property"
: To.ToLength(realm, lenProperty) !== initialLength
) {
this.visitValue(lenProperty);
}
}
visitValueMap(val: ObjectValue): void {
invariant(val.getKind() === "Map");
let entries = val.$MapData;
invariant(entries !== undefined);
let len = entries.length;
for (let i = 0; i < len; i++) {
let entry = entries[i];
let key = entry.$Key;
let value = entry.$Value;
if (key === undefined || value === undefined) continue;
this.visitValue(key);
this.visitValue(value);
}
}
visitValueWeakMap(val: ObjectValue): void {
invariant(val.getKind() === "WeakMap");
let entries = val.$WeakMapData;
invariant(entries !== undefined);
let len = entries.length;
for (let i = 0; i < len; i++) {
let entry = entries[i];
let key = entry.$Key;
let value = entry.$Value;
if (key !== undefined && value !== undefined) {
let fixpoint_rerun = () => {
let progress;
if (this.values.has(key)) {
progress = true;
this.visitValue(key);
this.visitValue(value);
} else {
progress = false;
this._enqueueWithUnrelatedScope(this.scope, fixpoint_rerun);
}
return progress;
};
fixpoint_rerun();
}
}
}
visitValueSet(val: ObjectValue): void {
invariant(val.getKind() === "Set");
let entries = val.$SetData;
invariant(entries !== undefined);
let len = entries.length;
for (let i = 0; i < len; i++) {
let entry = entries[i];
if (entry === undefined) continue;
this.visitValue(entry);
}
}
visitValueWeakSet(val: ObjectValue): void {
invariant(val.getKind() === "WeakSet");
let entries = val.$WeakSetData;
invariant(entries !== undefined);
let len = entries.length;
for (let i = 0; i < len; i++) {
let entry = entries[i];
if (entry !== undefined) {
let fixpoint_rerun = () => {
let progress;
if (this.values.has(entry)) {
progress = true;
this.visitValue(entry);
} else {
progress = false;
this._enqueueWithUnrelatedScope(this.scope, fixpoint_rerun);
}
return progress;
};
fixpoint_rerun();
}
}
}
visitValueFunction(val: FunctionValue): void {
let isClass = false;
this._registerAdditionalRoot(val);
if (val instanceof ECMAScriptFunctionValue && val.$FunctionKind === "classConstructor") {
invariant(val instanceof ECMAScriptSourceFunctionValue);
let homeObject = val.$HomeObject;
if (homeObject instanceof ObjectValue && homeObject.$IsClassPrototype) {
isClass = true;
}
}
this.visitObjectProperties(val);
if (val instanceof BoundFunctionValue) {
this.visitValue(val.$BoundTargetFunction);
this.visitValue(val.$BoundThis);
for (let boundArg of val.$BoundArguments) this.visitValue(boundArg);
return;
}
invariant(!(val instanceof NativeFunctionValue), "all native function values should be intrinsics");
invariant(val instanceof ECMAScriptSourceFunctionValue);
invariant(val.constructor === ECMAScriptSourceFunctionValue);
let formalParameters = val.$FormalParameters;
let code = val.$ECMAScriptCode;
let functionInfo = this.functionInfos.get(code);
let residualFunctionBindings = new Map();
this.functionInstances.set(val, {
residualFunctionBindings,
initializationStatements: [],
functionValue: val,
scopeInstances: new Map(),
});
if (!functionInfo) {
functionInfo = {
depth: 0,
lexicalDepth: 0,
unbound: new Map(),
requireCalls: new Map(),
modified: new Set(),
usesArguments: false,
usesThis: false,
};
let state = {
functionInfo,
realm: this.realm,
getModuleIdIfNodeIsRequireFunction: this.modules.getGetModuleIdIfNodeIsRequireFunction(formalParameters, [val]),
};
traverse(
t.file(t.program([t.expressionStatement(t.functionExpression(null, formalParameters, code))])),
ClosureRefVisitor,
null,
state
);
traverse.cache.clear();
this.functionInfos.set(code, functionInfo);
if (val.isResidual && functionInfo.unbound.size) {
if (!val.isUnsafeResidual) {
this.logger.logError(
val,
`residual function ${describeLocation(this.realm, val, undefined, code.loc) ||
"(unknown)"} refers to the following identifiers defined outside of the local scope: ${Object.keys(
functionInfo.unbound
).join(", ")}`
);
}
}
}
let additionalFunctionEffects = this.additionalFunctionValuesAndEffects.get(val);
if (additionalFunctionEffects) {
this._visitAdditionalFunction(val, additionalFunctionEffects);
} else {
this._enqueueWithUnrelatedScope(val, () => {
invariant(this.scope === val);
invariant(functionInfo);
for (let innerName of functionInfo.unbound.keys()) {
let environment = this.resolveBinding(val, innerName);
let residualBinding = this.getBinding(environment, innerName);
this.visitBinding(val, residualBinding);
residualFunctionBindings.set(innerName, residualBinding);
if (functionInfo.modified.has(innerName)) residualBinding.modified = true;
}
});
}
if (isClass && val.$HomeObject instanceof ObjectValue) {
this._visitClass(val, val.$HomeObject);
}
}
_visitBindingHelper(residualFunctionBinding: ResidualFunctionBinding) {
if (residualFunctionBinding.hasLeaked) return;
let environment = residualFunctionBinding.declarativeEnvironmentRecord;
invariant(environment !== null);
if (residualFunctionBinding.value === undefined) {
// The first time we visit, we need to initialize the value to its equivalent value
invariant(environment instanceof DeclarativeEnvironmentRecord);
let binding = environment.bindings[residualFunctionBinding.name];
invariant(binding !== undefined);
invariant(!binding.deletable);
let value = (binding.initialized && binding.value) || this.realm.intrinsics.undefined;
residualFunctionBinding.value = this.visitEquivalentValue(value);
} else {
// Subsequently, we just need to visit the value.
this.visitValue(residualFunctionBinding.value);
}
}
// Addresses the case:
// let x = [];
// let y = [];
// function a() { x.push("hi"); }
// function b() { y.push("bye"); }
// function c() { return x.length + y.length; }
// Here we need to make sure that a and b both initialize x and y because x and y will be in the same
// captured scope because c captures both x and y.
visitBinding(val: FunctionValue, residualFunctionBinding: ResidualFunctionBinding): void {
let environment = residualFunctionBinding.declarativeEnvironmentRecord;
if (environment === null) return;
invariant(this.scope === val);
let refScope = this._getAdditionalFunctionOfScope() || "GLOBAL";
residualFunctionBinding.potentialReferentializationScopes.add(refScope);
invariant(!(refScope instanceof Generator));
let funcToScopes = getOrDefault(this.functionToCapturedScopes, refScope, () => new Map());
let envRec = residualFunctionBinding.declarativeEnvironmentRecord;
invariant(envRec !== null);
let bindingState = getOrDefault(funcToScopes, envRec, () => ({
capturedBindings: new Set(),
capturingFunctions: new Set(),
}));
// If the binding is new for this bindingState, have all functions capturing bindings from that scope visit it
if (!bindingState.capturedBindings.has(residualFunctionBinding)) {
for (let functionValue of bindingState.capturingFunctions) {
this._enqueueWithUnrelatedScope(functionValue, () => this._visitBindingHelper(residualFunctionBinding));
}
bindingState.capturedBindings.add(residualFunctionBinding);
}
// If the function is new for this bindingState, visit all existent bindings in this scope
if (!bindingState.capturingFunctions.has(val)) {
invariant(this.scope === val);
for (let residualBinding of bindingState.capturedBindings) this._visitBindingHelper(residualBinding);
bindingState.capturingFunctions.add(val);
}
}
resolveBinding(val: FunctionValue, name: string): EnvironmentRecord {
let doesNotMatter = true;
let reference = this.logger.tryQuery(
() => Environment.ResolveBinding(this.realm, name, doesNotMatter, val.$Environment),
undefined
);
if (
reference === undefined ||
Environment.IsUnresolvableReference(this.realm, reference) ||
reference.base === this.globalEnvironmentRecord ||
reference.base === this.globalEnvironmentRecord.$DeclarativeRecord
) {
return this.globalEnvironmentRecord;
} else {
invariant(!Environment.IsUnresolvableReference(this.realm, reference));
let referencedBase = reference.base;
let referencedName: string = (reference.referencedName: any);
invariant(referencedName === name);
invariant(referencedBase instanceof DeclarativeEnvironmentRecord);
return referencedBase;
}
}
hasBinding(environment: EnvironmentRecord, name: string): boolean {
if (environment === this.globalEnvironmentRecord.$DeclarativeRecord) environment = this.globalEnvironmentRecord;
if (environment === this.globalEnvironmentRecord) {
// Global Binding
return this.globalBindings.get(name) !== undefined;
} else {
invariant(environment instanceof DeclarativeEnvironmentRecord);
// DeclarativeEnvironmentRecord binding
let residualFunctionBindings = this.declarativeEnvironmentRecordsBindings.get(environment);
if (residualFunctionBindings === undefined) return false;
return residualFunctionBindings.get(name) !== undefined;
}
}
// Visits a binding, returns a ResidualFunctionBinding
getBinding(environment: EnvironmentRecord, name: string): ResidualFunctionBinding {
if (environment === this.globalEnvironmentRecord.$DeclarativeRecord) environment = this.globalEnvironmentRecord;
if (environment === this.globalEnvironmentRecord) {
// Global Binding
return getOrDefault(this.globalBindings, name, () => {
let residualFunctionBinding = {
name,
value: undefined,
modified: true,
hasLeaked: false,
declarativeEnvironmentRecord: null,
potentialReferentializationScopes: new Set(),
};
// Queue up visiting of global binding exactly once in the globalGenerator scope.
this._enqueueWithUnrelatedScope(this.globalGenerator, () => {
let value = this.realm.getGlobalLetBinding(name);
if (value !== undefined) residualFunctionBinding.value = this.visitEquivalentValue(value);
});
return residualFunctionBinding;
});
} else {
invariant(environment instanceof DeclarativeEnvironmentRecord);
// DeclarativeEnvironmentRecord binding
let residualFunctionBindings = getOrDefault(
this.declarativeEnvironmentRecordsBindings,
environment,
() => new Map()
);
return getOrDefault(
residualFunctionBindings,
name,
(): ResidualFunctionBinding => {
invariant(environment instanceof DeclarativeEnvironmentRecord);
return {
name,
value: undefined,
modified: false,
hasLeaked: false,
declarativeEnvironmentRecord: environment,
potentialReferentializationScopes: new Set(),
};
}
);
// Note that we don't yet visit the binding (and its value) here,
// as that should be done by a call to visitBinding, in the right scope,
// if the binding's incoming value is relevant.
}
}
_visitClass(classFunc: ECMAScriptSourceFunctionValue, classPrototype: ObjectValue): void {
let visitClassMethod = (propertyNameOrSymbol, methodFunc, methodType, isStatic) => {
if (methodFunc instanceof ECMAScriptSourceFunctionValue) {
// if the method does not have a $HomeObject, it's not a class method
if (methodFunc.$HomeObject !== undefined) {
if (methodFunc !== classFunc) {
this._visitClassMethod(methodFunc, methodType, classPrototype, !!isStatic);
}
}
}
};
for (let [propertyName, method] of classPrototype.properties) {
withDescriptorValue(propertyName, method.descriptor, visitClassMethod);
}
for (let [symbol, method] of classPrototype.symbols) {
withDescriptorValue(symbol, method.descriptor, visitClassMethod);
}
// handle class inheritance
if (!(classFunc.$Prototype instanceof NativeFunctionValue)) {
this.visitValue(classFunc.$Prototype);
}
if (classPrototype.properties.has("constructor")) {
let constructor = classPrototype.properties.get("constructor");
invariant(constructor !== undefined);
// check if the constructor was deleted, as it can't really be deleted
// it just gets set to empty (the default again)
if (constructor.descriptor === undefined) {
classFunc.$HasEmptyConstructor = true;
} else {
let visitClassProperty = (propertyNameOrSymbol, methodFunc, methodType) => {
visitClassMethod(propertyNameOrSymbol, methodFunc, methodType, true);
};
// check if we have any static methods we need to include
let constructorFunc = Get(this.realm, classPrototype, "constructor");
invariant(constructorFunc instanceof ObjectValue);
for (let [propertyName, method] of constructorFunc.properties) {
if (
!ClassPropertiesToIgnore.has(propertyName) &&
method.descriptor !== undefined &&
!(
propertyName === "length" && canIgnoreClassLengthProperty(constructorFunc, method.descriptor, this.logger)
)
) {
withDescriptorValue(propertyName, method.descriptor, visitClassProperty);
}
}
}
}
this.classMethodInstances.set(classFunc, {
classPrototype,
methodType: "constructor",
classSuperNode: undefined,
classMethodIsStatic: false,
classMethodKeyNode: undefined,
classMethodComputed: false,
});
}
_visitClassMethod(
methodFunc: ECMAScriptSourceFunctionValue,
methodType: "get" | "set" | "value",
classPrototype: ObjectValue,
isStatic: boolean
): void {
this.classMethodInstances.set(methodFunc, {
classPrototype,
methodType: methodType === "value" ? "method" : methodType,
classSuperNode: undefined,
classMethodIsStatic: isStatic,
classMethodKeyNode: undefined,
classMethodComputed: !!methodFunc.$HasComputedName,
});
}
visitValueObject(val: ObjectValue): void {
this._registerAdditionalRoot(val);
if (isReactElement(val)) {
this.residualReactElementVisitor.visitReactElement(val);
return;
}
let kind = val.getKind();
this.visitObjectProperties(val, kind);
// If this object is a prototype object that was implicitly created by the runtime
// for a constructor, then we can obtain a reference to this object
// in a special way that's handled alongside function serialization.
let constructor = val.originalConstructor;
if (constructor !== undefined) {
this.visitValue(constructor);
return;
}
switch (kind) {
case "RegExp":
case "Number":
case "String":
case "Boolean":
case "ArrayBuffer":
return;
case "Date":
let dateValue = val.$DateValue;
invariant(dateValue !== undefined);
this.visitValue(dateValue);
return;
case "Float32Array":
case "Float64Array":
case "Int8Array":
case "Int16Array":
case "Int32Array":
case "Uint8Array":
case "Uint16Array":
case "Uint32Array":
case "Uint8ClampedArray":
case "DataView":
let buf = val.$ViewedArrayBuffer;
invariant(buf !== undefined);
this.visitValue(buf);
return;
case "Map":
this.visitValueMap(val);
return;
case "WeakMap":
this.visitValueWeakMap(val);
return;
case "Set":
this.visitValueSet(val);
return;
case "WeakSet":
this.visitValueWeakSet(val);
return;
default:
if (kind !== "Object") this.logger.logError(val, `Object of kind ${kind} is not supported in residual heap.`);
if (this.realm.react.enabled && valueIsReactLibraryObject(this.realm, val, this.logger)) {
this.realm.fbLibraries.react = val;
}
return;
}
}
visitValueSymbol(val: SymbolValue): void {
if (val.$Description) this.visitValue(val.$Description);
}
visitValueProxy(val: ProxyValue): void {
this._registerAdditionalRoot(val);
this.visitValue(val.$ProxyTarget);
this.visitValue(val.$ProxyHandler);
}
_visitAbstractValueConditional(val: AbstractValue): void {
let condition = val.args[0];
invariant(condition instanceof AbstractValue);
let cf = this.conditionalFeasibility.get(val);
if (cf === undefined) this.conditionalFeasibility.set(val, (cf = { t: false, f: false }));
let feasibleT, feasibleF;
let savedPath = this.realm.pathConditions;
try {
this.realm.pathConditions = this.scope instanceof Generator ? this.scope.pathConditions : [];
let impliesT = Path.implies(condition);
let impliesF = Path.impliesNot(condition);
invariant(!(impliesT && impliesF));
if (!impliesT && !impliesF) {
feasibleT = feasibleF = true;
} else {
feasibleT = impliesT;
feasibleF = impliesF;
}
} finally {
this.realm.pathConditions = savedPath;
}
let visitedT = false,
visitedF = false;
if (!cf.t && feasibleT) {
val.args[1] = this.visitEquivalentValue(val.args[1]);
cf.t = true;
if (cf.f) val.args[0] = this.visitEquivalentValue(val.args[0]);
visitedT = true;
}
if (!cf.f && feasibleF) {
val.args[2] = this.visitEquivalentValue(val.args[2]);
cf.f = true;
if (cf.t) val.args[0] = this.visitEquivalentValue(val.args[0]);
visitedF = true;
}
if (!visitedT || !visitedF) {
let fixpoint_rerun = () => {
let progress = false;
invariant(cf !== undefined);
if (cf.f && cf.t) {
invariant(!visitedT || !visitedF);
this.visitValue(val.args[0]);
}
if (cf.t && !visitedT) {
this.visitValue(val.args[1]);
progress = visitedT = true;
}
invariant(cf.t === visitedT);
if (cf.f && !visitedF) {
this.visitValue(val.args[2]);
progress = visitedF = true;
}
invariant(cf.f === visitedF);
// When not all possible outcomes are assumed to be feasible yet after visiting some scopes,
// it might be that they do become assumed to be feasible when later visiting some other scopes.
// In that case, we should also re-visit the corresponding cases in this scope.
// To this end, calling _enqueueWithUnrelatedScope enqueues this function for later re-execution if
// any other visiting progress was made.
if (!visitedT || !visitedF) this._enqueueWithUnrelatedScope(this.scope, fixpoint_rerun);
return progress;
};
fixpoint_rerun();
}
}