forked from googleprojectzero/fuzzilli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJavaScriptLifter.swift
2271 lines (1982 loc) · 106 KB
/
JavaScriptLifter.swift
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 2019 Google LLC
//
// 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
//
// https://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.
import Foundation
/// Supported versions of the ECMA standard.
public enum ECMAScriptVersion {
case es5
case es6
}
/// Lifts a FuzzIL program to JavaScript.
public class JavaScriptLifter: Lifter {
/// Prefix and suffix to surround the emitted code in
private let prefix: String
private let suffix: String
private let logger: Logger
private var wasmLiftingFailures = 0
private var liftedSamples = 0
/// The version of the ECMAScript standard that this lifter generates code for.
let version: ECMAScriptVersion
/// This environment is used if we need to re-type a program before we compile Wasm code.
private var environment: Environment?
/// Counter to assist the lifter in detecting nested CodeStrings
private var codeStringNestingLevel = 0
/// Stack of for-loop header parts. A for-loop's header consists of three different blocks (initializer, condition, afterthought), which
/// are lifted independently but should then typically be combined into a single line. This helper stack makes that possible.
struct ForLoopHeader {
var initializer = ""
var condition = ""
// No need for the afterthought string since this struct will be consumed
// by the handler for the afterthought block.
var loopVariables = [String]()
}
private var forLoopHeaderStack = Stack<ForLoopHeader>()
// Stack for object literals.
private var objectLiteralStack = Stack<ObjectLiteralWriter>()
private var currentObjectLiteral: ObjectLiteralWriter {
get {
return objectLiteralStack.top
}
set(newValue) {
objectLiteralStack.top = newValue
}
}
public init(prefix: String = "",
suffix: String = "",
ecmaVersion: ECMAScriptVersion,
environment: Environment? = nil) {
self.prefix = prefix
self.suffix = suffix
self.version = ecmaVersion
self.environment = environment
self.logger = Logger(withLabel: "JavaScriptLifter")
}
public func lift(_ program: Program, withOptions options: LiftingOptions) -> String {
liftedSamples += 1
// Perform some analysis on the program, for example to determine variable uses
var needToSupportExploration = false
var needToSupportProbing = false
var needToSupportFixup = false
var needToSupportWasm = false
var analyzer = DefUseAnalyzer(for: program)
// If this program has a WasmModule, i.e. has a BeginWasmModule / EndWasmModule instruction, we need a typer to collect type information for lifting of that module.
// This typer is shared across WasmLifters and a WasmLifter is only valid for a single WasmModule.
var typer: JSTyper? = nil
// The currently active WasmLifter, we can only have one of them.
var wasmLifter: WasmLifter? = nil
for instr in program.code {
analyzer.analyze(instr)
if instr.op is Explore { needToSupportExploration = true }
if instr.op is Probe { needToSupportProbing = true }
if instr.op is Fixup { needToSupportFixup = true }
if instr.op is BeginWasmModule { needToSupportWasm = true }
}
analyzer.finishAnalysis()
if needToSupportWasm {
// If we need to support Wasm we need to type all instructions outside of Wasm such that the WasmLifter can access extra type information during lifting.
typer = JSTyper(for: environment!)
}
var w = JavaScriptWriter(analyzer: analyzer, version: version, stripComments: !options.contains(.includeComments), includeLineNumbers: options.contains(.includeLineNumbers))
var wasmCodeStarts: Int? = nil
if options.contains(.includeComments), let header = program.comments.at(.header) {
w.emitComment(header)
}
w.emitBlock(prefix)
if needToSupportExploration {
w.emitBlock(JavaScriptExploreLifting.prefixCode)
}
if needToSupportProbing {
w.emitBlock(JavaScriptProbeLifting.prefixCode)
}
if needToSupportFixup {
w.emitBlock(JavaScriptFixupLifting.prefixCode)
}
// Singular operation handling.
// Singular operations (e.g. class constructors or switch default cases) should only occur once inside their surrounding blocks. If there are
// multiple singular operations, then all but the first one are ignored. We implement this here simply by commenting them out, for which we
// need some additional state tracking.
struct Block {
var seenSingularOperation = false
var singularOperationName = ""
var previouslyIgnoringCode: Bool
}
var activeBlocks = Stack([Block(previouslyIgnoringCode: false)])
var currentlyIgnoringCode = false
// Helper function to bind a variable to |this|. This requires special handling because |this| must never be reassigned (`this = 42;`) as that is a syntax error.
func bindVariableToThis(_ v: Variable) {
// Assignments to |this| are syntax errors, so we use assign() here (instead of declare()) which will make sure to emit a local variable if the FuzzIL variable is ever reassigned.
w.assign(Identifier.new("this"), to: v)
}
for instr in program.code {
if options.contains(.includeComments), let comment = program.comments.at(.instruction(instr.index)) {
w.emitComment(comment)
}
// Collect type information that we might pass to the WasmLifter.
typer?.analyze(instr)
// Singular operation handling:
// All but the first singular operation in the same block are removed.
// TODO(saelo): instead consider enforcing this in FuzzIL already.
if currentlyIgnoringCode && !activeBlocks.top.previouslyIgnoringCode {
currentlyIgnoringCode = false
}
if instr.isSingular {
if activeBlocks.top.seenSingularOperation {
currentlyIgnoringCode = true
assert(activeBlocks.top.singularOperationName == instr.op.name)
}
activeBlocks.top.seenSingularOperation = true
activeBlocks.top.singularOperationName = instr.op.name
}
if instr.isBlockEnd {
currentlyIgnoringCode = activeBlocks.pop().previouslyIgnoringCode
}
if instr.isBlockStart {
activeBlocks.push(Block(previouslyIgnoringCode: currentlyIgnoringCode))
}
if currentlyIgnoringCode {
continue
}
// Pass Wasm instructions to the WasmLifter
if (instr.op as? WasmOperation) != nil {
// Forward all the Wasm related instructions to the WasmLifter,
// they will be emitted once we see the end of the module.
wasmLifter!.addInstruction(instr)
continue;
}
// Handling of guarded operations, part 1: unless we have special handling (e.g. for guarded property loads we use `o?.foo`),
// we emit a try-catch around guarded operations so prepare for that.
var guarding = false
if instr.isGuarded && !haveSpecialHandlingForGuardedOp(instr.op) {
assert(!instr.isBlock, "Cannot wrap block headers/footers in try-catch")
guarding = true
// Emit all pending expressions so that the guarded operation is guaranteed to lift to a single line.
w.emitPendingExpressions()
// We need to declare all outputs of the guarded operation before the try-catch so that they are
// visible to subsequent code.
assert(instr.numInnerOutputs == 0, "Inner outputs are not currently supported in guarded operations")
let neededOutputs = instr.allOutputs.filter({ analyzer.numUses(of: $0) > 0 })
if !neededOutputs.isEmpty {
let VARS = w.declareAll(neededOutputs).joined(separator: ", ")
let LET = w.varKeyword
w.emit("\(LET) \(VARS);")
}
// Lift the operation into a temporary buffer, then wrap the resulting code into try-catch afterwards.
w.pushTemporaryOutputBuffer(initialIndentionLevel: 0)
}
// Retrieve all input expressions.
//
// Here we assume that the input expressions are evaluated exactly in the order that they appear in the instructions inputs array.
// If that is not the case, it may change the program's semantics as inlining could reorder operations, see JavaScriptWriter.retrieve
// for more details.
// We also have some lightweight checking logic to ensure that the input expressions are retrieved in the correct order.
// This does not guarantee that they will also _evaluate_ in that order at runtime, but it's probably a decent approximation.
let inputs = w.retrieve(expressionsFor: instr.inputs)!
var nextExpressionToFetch = 0
func input(_ i: Int) -> Expression {
assert(i == nextExpressionToFetch)
nextExpressionToFetch += 1
return inputs[i]
}
// Retrieves the expression for the given input and makes sure that it is an identifier. If necessary, this will create a temporary variable.
func inputAsIdentifier(_ i: Int) -> Expression {
let expr = input(i)
let identifier = w.ensureIsIdentifier(expr, for: instr.input(i))
assert(identifier.type === Identifier)
return identifier
}
switch instr.op.opcode {
case .loadInteger(let op):
let expr: Expression
if op.value < 0 {
expr = NegativeNumberLiteral.new(String(op.value))
} else {
expr = NumberLiteral.new(String(op.value))
}
w.assign(expr, to: instr.output)
case .loadBigInt(let op):
let expr: Expression
if op.value < 0 {
expr = NegativeNumberLiteral.new(String(op.value) + "n")
} else {
expr = NumberLiteral.new(String(op.value) + "n")
}
w.assign(expr, to: instr.output)
case .loadFloat(let op):
let expr = liftFloatValue(op.value)
w.assign(expr, to: instr.output)
case .loadString(let op):
w.assign(StringLiteral.new("\"\(op.value)\""), to: instr.output)
case .loadRegExp(let op):
let flags = op.flags.asString()
w.assign(RegExpLiteral.new() + "/" + op.pattern + "/" + flags, to: instr.output)
case .loadBoolean(let op):
w.assign(Literal.new(op.value ? "true" : "false"), to: instr.output)
case .loadUndefined:
w.assign(Identifier.new("undefined"), to: instr.output)
case .loadNull:
w.assign(Literal.new("null"), to: instr.output)
case .loadThis:
bindVariableToThis(instr.output)
case .loadArguments:
w.assign(Identifier.new("arguments"), to: instr.output)
case .createNamedVariable(let op):
assert(op.declarationMode == .none || op.hasInitialValue)
if op.hasInitialValue {
switch op.declarationMode {
case .none:
fatalError("This declaration mode doesn't have an initial value")
case .global:
w.emit("\(op.variableName) = \(input(0));")
case .var:
// Small optimization: turn `var x = undefined;` into just `var x;`
let initialValue = input(0).text
if initialValue == "undefined" {
w.emit("var \(op.variableName);")
} else {
w.emit("var \(op.variableName) = \(initialValue);")
}
case .let:
// Small optimization: turn `let x = undefined;` into just `let x;`
let initialValue = input(0).text
if initialValue == "undefined" {
w.emit("let \(op.variableName);")
} else {
w.emit("let \(op.variableName) = \(initialValue);")
}
case .const:
w.emit("const \(op.variableName) = \(input(0));")
}
}
w.declare(instr.output, as: op.variableName)
case .loadDisposableVariable:
let V = w.declare(instr.output);
w.emit("using \(V) = \(input(0));");
case .loadAsyncDisposableVariable:
let V = w.declare(instr.output);
w.emit("await using \(V) = \(input(0));");
case .beginObjectLiteral:
// We force all expressions to evaluate before the object literal.
// Technically we could allow expression inlining into object literals, but
// in practice it wouldn't work a lot of the time (e.g. whenever we have
// more than one value to inline) so isn't all that useful and adds complexity.
w.emitPendingExpressions()
objectLiteralStack.push(ObjectLiteralWriter())
// Push a dummy script writer so we can assert that nothing writes to it (which shouldn't happen).
w.pushTemporaryOutputBuffer(initialIndentionLevel: 0)
case .objectLiteralAddProperty(let op):
let PROPERTY = op.propertyName
let VALUE = input(0)
assert(!PROPERTY.contains(" "))
currentObjectLiteral.addField("\(PROPERTY): \(VALUE)")
case .objectLiteralAddElement(let op):
let INDEX = op.index < 0 ? "[\(op.index)]" : String(op.index)
let VALUE = input(0)
currentObjectLiteral.addField("\(INDEX): \(VALUE)")
case .objectLiteralAddComputedProperty:
let PROPERTY = input(0)
let VALUE = input(1)
currentObjectLiteral.addField("[\(PROPERTY)]: \(VALUE)")
case .objectLiteralCopyProperties:
let EXPR = SpreadExpression.new() + "..." + input(0)
currentObjectLiteral.addField("\(EXPR)")
case .objectLiteralSetPrototype:
let PROTO = input(0)
currentObjectLiteral.addField("__proto__: \(PROTO)")
case .beginObjectLiteralMethod(let op):
let vars = w.declareAll(instr.innerOutputs.dropFirst(), usePrefix: "a")
let PARAMS = liftParameters(op.parameters, as: vars)
let METHOD = op.methodName
currentObjectLiteral.beginMethod("\(METHOD)(\(PARAMS)) {", &w)
bindVariableToThis(instr.innerOutput(0))
case .endObjectLiteralMethod:
currentObjectLiteral.endMethod(&w)
case .beginObjectLiteralComputedMethod(let op):
let vars = w.declareAll(instr.innerOutputs.dropFirst(), usePrefix: "a")
let PARAMS = liftParameters(op.parameters, as: vars)
let METHOD = input(0)
currentObjectLiteral.beginMethod("[\(METHOD)](\(PARAMS)) {", &w)
bindVariableToThis(instr.innerOutput(0))
case .endObjectLiteralComputedMethod:
currentObjectLiteral.endMethod(&w)
case .beginObjectLiteralGetter(let op):
assert(instr.numInnerOutputs == 1)
let PROPERTY = op.propertyName
currentObjectLiteral.beginMethod("get \(PROPERTY)() {", &w)
bindVariableToThis(instr.innerOutput(0))
case .beginObjectLiteralSetter(let op):
assert(instr.numInnerOutputs == 2)
let vars = w.declareAll(instr.innerOutputs.dropFirst(), usePrefix: "a")
let PARAMS = liftParameters(op.parameters, as: vars)
let PROPERTY = op.propertyName
currentObjectLiteral.beginMethod("set \(PROPERTY)(\(PARAMS)) {", &w)
bindVariableToThis(instr.innerOutput(0))
case .endObjectLiteralGetter,
.endObjectLiteralSetter:
currentObjectLiteral.endMethod(&w)
case .endObjectLiteral:
// We don't expect anything to have been written to the dummy output buffer.
// Everything needs to be written into the object literal writer.
let dummy = w.popTemporaryOutputBuffer()
// The dummy might still contain the comments.
assert(dummy.isEmpty || dummy.split(separator: "\n").allSatisfy( {$0.hasPrefix("//")}))
let literal = objectLiteralStack.pop()
if literal.isEmpty {
w.assign(ObjectLiteral.new("{}"), to: instr.output)
} else if literal.canInline {
// In this case, we inline the object literal.
let code = "{ \(literal.fields.joined(separator: ", ")) }";
w.assign(ObjectLiteral.new(code), to: instr.output)
} else {
let LET = w.declarationKeyword(for: instr.output)
let V = w.declare(instr.output)
w.emit("\(LET) \(V) = {")
w.enterNewBlock()
for field in literal.fields {
w.emitBlock("\(field),")
}
w.leaveCurrentBlock()
w.emit("};")
}
case .beginClassDefinition(let op):
// The name of the class is set to the uppercased variable name. This ensures that the heuristics used by the JavaScriptExploreLifting code to detect constructors works correctly (see shouldTreatAsConstructor).
let NAME = "C\(instr.output.number)"
w.declare(instr.output, as: NAME)
var declaration = "class \(NAME)"
if op.hasSuperclass {
declaration += " extends \(input(0))"
}
declaration += " {"
w.emit(declaration)
w.enterNewBlock()
case .beginClassConstructor(let op):
let vars = w.declareAll(instr.innerOutputs.dropFirst(), usePrefix: "a")
let PARAMS = liftParameters(op.parameters, as: vars)
w.emit("constructor(\(PARAMS)) {")
w.enterNewBlock()
bindVariableToThis(instr.innerOutput(0))
case .endClassConstructor:
w.leaveCurrentBlock()
w.emit("}")
case .classAddInstanceProperty(let op):
let PROPERTY = op.propertyName
if op.hasValue {
let VALUE = input(0)
w.emit("\(PROPERTY) = \(VALUE);")
} else {
w.emit("\(PROPERTY);")
}
case .classAddInstanceElement(let op):
let INDEX = op.index < 0 ? "[\(op.index)]" : String(op.index)
if op.hasValue {
let VALUE = input(0)
w.emit("\(INDEX) = \(VALUE);")
} else {
w.emit("\(INDEX);")
}
case .classAddInstanceComputedProperty(let op):
let PROPERTY = input(0)
if op.hasValue {
let VALUE = input(1)
w.emit("[\(PROPERTY)] = \(VALUE);")
} else {
w.emit("[\(PROPERTY)];")
}
case .beginClassInstanceMethod(let op):
let vars = w.declareAll(instr.innerOutputs.dropFirst(), usePrefix: "a")
let PARAMS = liftParameters(op.parameters, as: vars)
let METHOD = op.methodName
w.emit("\(METHOD)(\(PARAMS)) {")
w.enterNewBlock()
bindVariableToThis(instr.innerOutput(0))
case .beginClassInstanceGetter(let op):
let PROPERTY = op.propertyName
w.emit("get \(PROPERTY)() {")
w.enterNewBlock()
bindVariableToThis(instr.innerOutput(0))
case .beginClassInstanceSetter(let op):
assert(instr.numInnerOutputs == 2)
let vars = w.declareAll(instr.innerOutputs.dropFirst(), usePrefix: "a")
let PARAMS = liftParameters(op.parameters, as: vars)
let PROPERTY = op.propertyName
w.emit("set \(PROPERTY)(\(PARAMS)) {")
w.enterNewBlock()
bindVariableToThis(instr.innerOutput(0))
case .endClassInstanceMethod,
.endClassInstanceGetter,
.endClassInstanceSetter:
w.leaveCurrentBlock()
w.emit("}")
case .classAddStaticProperty(let op):
let PROPERTY = op.propertyName
if op.hasValue {
let VALUE = input(0)
w.emit("static \(PROPERTY) = \(VALUE);")
} else {
w.emit("static \(PROPERTY);")
}
case .classAddStaticElement(let op):
let INDEX = op.index < 0 ? "[\(op.index)]" : String(op.index)
if op.hasValue {
let VALUE = input(0)
w.emit("static \(INDEX) = \(VALUE);")
} else {
w.emit("static \(INDEX);")
}
case .classAddStaticComputedProperty(let op):
let PROPERTY = input(0)
if op.hasValue {
let VALUE = input(1)
w.emit("static [\(PROPERTY)] = \(VALUE);")
} else {
w.emit("static [\(PROPERTY)];")
}
case .beginClassStaticInitializer:
w.emit("static {")
w.enterNewBlock()
bindVariableToThis(instr.innerOutput(0))
case .beginClassStaticMethod(let op):
let vars = w.declareAll(instr.innerOutputs.dropFirst(), usePrefix: "a")
let PARAMS = liftParameters(op.parameters, as: vars)
let METHOD = op.methodName
w.emit("static \(METHOD)(\(PARAMS)) {")
w.enterNewBlock()
bindVariableToThis(instr.innerOutput(0))
case .beginClassStaticGetter(let op):
assert(instr.numInnerOutputs == 1)
let PROPERTY = op.propertyName
w.emit("static get \(PROPERTY)() {")
w.enterNewBlock()
bindVariableToThis(instr.innerOutput)
case .beginClassStaticSetter(let op):
assert(instr.numInnerOutputs == 2)
let vars = w.declareAll(instr.innerOutputs.dropFirst(), usePrefix: "a")
let PARAMS = liftParameters(op.parameters, as: vars)
let PROPERTY = op.propertyName
w.emit("static set \(PROPERTY)(\(PARAMS)) {")
w.enterNewBlock()
bindVariableToThis(instr.innerOutput(0))
case .endClassStaticInitializer,
.endClassStaticMethod,
.endClassStaticGetter,
.endClassStaticSetter:
w.leaveCurrentBlock()
w.emit("}")
case .classAddPrivateInstanceProperty(let op):
let PROPERTY = op.propertyName
if op.hasValue {
let VALUE = input(0)
w.emit("#\(PROPERTY) = \(VALUE);")
} else {
w.emit("#\(PROPERTY);")
}
case .beginClassPrivateInstanceMethod(let op):
let vars = w.declareAll(instr.innerOutputs.dropFirst(), usePrefix: "a")
let PARAMS = liftParameters(op.parameters, as: vars)
let METHOD = op.methodName
w.emit("#\(METHOD)(\(PARAMS)) {")
w.enterNewBlock()
bindVariableToThis(instr.innerOutput(0))
case .classAddPrivateStaticProperty(let op):
let PROPERTY = op.propertyName
if op.hasValue {
let VALUE = input(0)
w.emit("static #\(PROPERTY) = \(VALUE);")
} else {
w.emit("static #\(PROPERTY);")
}
case .beginClassPrivateStaticMethod(let op):
let vars = w.declareAll(instr.innerOutputs.dropFirst(), usePrefix: "a")
let PARAMS = liftParameters(op.parameters, as: vars)
let METHOD = op.methodName
w.emit("static #\(METHOD)(\(PARAMS)) {")
w.enterNewBlock()
bindVariableToThis(instr.innerOutput(0))
case .endClassPrivateInstanceMethod,
.endClassPrivateStaticMethod:
w.leaveCurrentBlock()
w.emit("}")
case .endClassDefinition:
w.leaveCurrentBlock()
w.emit("}")
case .createArray:
// When creating arrays, treat undefined elements as holes. This also relies on literals always being inlined.
var elems = inputs.map({ $0.text }).map({ $0 == "undefined" ? "" : $0 }).joined(separator: ",")
if elems.last == "," || (instr.inputs.count == 1 && elems == "") {
// If the last element is supposed to be a hole, we need one additional comma
elems += ","
}
w.assign(ArrayLiteral.new("[\(elems)]"), to: instr.output)
case .createIntArray(let op):
let values = op.values.map({ String($0) }).joined(separator: ",")
w.assign(ArrayLiteral.new("[\(values)]"), to: instr.output)
case .createFloatArray(let op):
let values = op.values.map({ liftFloatValue($0).text }).joined(separator: ",")
w.assign(ArrayLiteral.new("[\(values)]"), to: instr.output)
case .createArrayWithSpread(let op):
var elems = [String]()
for (i, expr) in inputs.enumerated() {
if op.spreads[i] {
let expr = SpreadExpression.new() + "..." + expr
elems.append(expr.text)
} else {
let text = expr.text
elems.append(text == "undefined" ? "" : text)
}
}
var elemString = elems.joined(separator: ",");
if elemString.last == "," || (instr.inputs.count==1 && elemString=="") {
// If the last element is supposed to be a hole, we need one additional commas
elemString += ","
}
w.assign(ArrayLiteral.new("[" + elemString + "]"), to: instr.output)
case .createTemplateString(let op):
assert(!op.parts.isEmpty)
assert(op.parts.count == instr.numInputs + 1)
var parts = [op.parts[0]]
for i in 1..<op.parts.count {
let VALUE = input(i - 1)
parts.append("${\(VALUE)}\(op.parts[i])")
}
// See BeginCodeString case.
let count = Int(pow(2, Double(codeStringNestingLevel)))-1
let escapeSequence = String(repeating: "\\", count: count)
let expr = TemplateLiteral.new("\(escapeSequence)`" + parts.joined() + "\(escapeSequence)`")
w.assign(expr, to: instr.output)
case .getProperty(let op):
let obj = input(0)
let accessOperator = op.isGuarded ? "?." : "."
let expr = MemberExpression.new() + obj + accessOperator + op.propertyName
w.assign(expr, to: instr.output)
case .setProperty(let op):
// For aesthetic reasons, we don't want to inline the lhs of an assignment, so force it to be stored in a variable.
let obj = inputAsIdentifier(0)
let PROPERTY = MemberExpression.new() + obj + "." + op.propertyName
let VALUE = input(1)
w.emit("\(PROPERTY) = \(VALUE);")
case .updateProperty(let op):
// For aesthetic reasons, we don't want to inline the lhs of an assignment, so force it to be stored in a variable.
let obj = inputAsIdentifier(0)
let PROPERTY = MemberExpression.new() + obj + "." + op.propertyName
let VALUE = input(1)
w.emit("\(PROPERTY) \(op.op.token)= \(VALUE);")
case .deleteProperty(let op):
// For aesthetic reasons, we don't want to inline the lhs of a property deletion, so force it to be stored in a variable.
let obj = inputAsIdentifier(0)
let accessOperator = op.isGuarded ? "?." : "."
let target = MemberExpression.new() + obj + accessOperator + op.propertyName
let expr = UnaryExpression.new() + "delete " + target
w.assign(expr, to: instr.output)
case .configureProperty(let op):
let OBJ = input(0)
let PROPERTY = op.propertyName
let DESCRIPTOR = liftPropertyDescriptor(flags: op.flags, type: op.type, values: inputs.dropFirst())
w.emit("Object.defineProperty(\(OBJ), \"\(PROPERTY)\", \(DESCRIPTOR));")
case .getElement(let op):
let obj = input(0)
let accessOperator = op.isGuarded ? "?.[" : "["
let expr = MemberExpression.new() + obj + accessOperator + op.index + "]"
w.assign(expr, to: instr.output)
case .setElement(let op):
// For aesthetic reasons, we don't want to inline the lhs of an assignment, so force it to be stored in a variable.
let obj = inputAsIdentifier(0)
let ELEMENT = MemberExpression.new() + obj + "[" + op.index + "]"
let VALUE = input(1)
w.emit("\(ELEMENT) = \(VALUE);")
case .updateElement(let op):
// For aesthetic reasons, we don't want to inline the lhs of an assignment, so force it to be stored in a variable.
let obj = inputAsIdentifier(0)
let ELEMENT = MemberExpression.new() + obj + "[" + op.index + "]"
let VALUE = input(1)
w.emit("\(ELEMENT) \(op.op.token)= \(VALUE);")
case .deleteElement(let op):
// For aesthetic reasons, we don't want to inline the lhs of an element deletion, so force it to be stored in a variable.
let obj = inputAsIdentifier(0)
let accessOperator = op.isGuarded ? "?.[" : "["
let target = MemberExpression.new() + obj + accessOperator + op.index + "]"
let expr = UnaryExpression.new() + "delete " + target
w.assign(expr, to: instr.output)
case .configureElement(let op):
let OBJ = input(0)
let INDEX = op.index
let DESCRIPTOR = liftPropertyDescriptor(flags: op.flags, type: op.type, values: inputs.dropFirst())
w.emit("Object.defineProperty(\(OBJ), \(INDEX), \(DESCRIPTOR));")
case .getComputedProperty(let op):
let obj = input(0)
let accessOperator = op.isGuarded ? "?.[" : "["
let expr = MemberExpression.new() + obj + accessOperator + input(1).text + "]"
w.assign(expr, to: instr.output)
case .setComputedProperty:
// For aesthetic reasons, we don't want to inline the lhs of an assignment, so force it to be stored in a variable.
let obj = inputAsIdentifier(0)
let PROPERTY = MemberExpression.new() + obj + "[" + input(1).text + "]"
let VALUE = input(2)
w.emit("\(PROPERTY) = \(VALUE);")
case .updateComputedProperty(let op):
// For aesthetic reasons, we don't want to inline the lhs of an assignment, so force it to be stored in a variable.
let obj = inputAsIdentifier(0)
let PROPERTY = MemberExpression.new() + obj + "[" + input(1).text + "]"
let VALUE = input(2)
w.emit("\(PROPERTY) \(op.op.token)= \(VALUE);")
case .deleteComputedProperty(let op):
// For aesthetic reasons, we don't want to inline the lhs of a property deletion, so force it to be stored in a variable.
let obj = inputAsIdentifier(0)
let accessOperator = op.isGuarded ? "?.[" : "["
let target = MemberExpression.new() + obj + accessOperator + input(1).text + "]"
let expr = UnaryExpression.new() + "delete " + target
w.assign(expr, to: instr.output)
case .configureComputedProperty(let op):
let OBJ = input(0)
let PROPERTY = input(1)
let DESCRIPTOR = liftPropertyDescriptor(flags: op.flags, type: op.type, values: inputs.dropFirst(2))
w.emit("Object.defineProperty(\(OBJ), \(PROPERTY), \(DESCRIPTOR));")
case .typeOf:
let expr = UnaryExpression.new() + "typeof " + input(0)
w.assign(expr, to: instr.output)
case .void:
let expr = UnaryExpression.new() + "void " + input(0)
w.assign(expr, to: instr.output)
case .testInstanceOf:
let lhs = input(0)
let rhs = input(1)
let expr = BinaryExpression.new() + lhs + " instanceof " + rhs
w.assign(expr, to: instr.output)
case .testIn:
let lhs = input(0)
let rhs = input(1)
let expr = BinaryExpression.new() + lhs + " in " + rhs
w.assign(expr, to: instr.output)
case .beginPlainFunction:
liftFunctionDefinitionBegin(instr, keyword: "function", using: &w)
case .beginArrowFunction(let op):
let LET = w.declarationKeyword(for: instr.output)
let V = w.declare(instr.output)
let vars = w.declareAll(instr.innerOutputs, usePrefix: "a")
let PARAMS = liftParameters(op.parameters, as: vars)
w.emit("\(LET) \(V) = (\(PARAMS)) => {")
w.enterNewBlock()
case .beginGeneratorFunction:
liftFunctionDefinitionBegin(instr, keyword: "function*", using: &w)
case .beginAsyncFunction:
liftFunctionDefinitionBegin(instr, keyword: "async function", using: &w)
case .beginAsyncArrowFunction(let op):
let LET = w.declarationKeyword(for: instr.output)
let V = w.declare(instr.output)
let vars = w.declareAll(instr.innerOutputs, usePrefix: "a")
let PARAMS = liftParameters(op.parameters, as: vars)
w.emit("\(LET) \(V) = async (\(PARAMS)) => {")
w.enterNewBlock()
case .beginAsyncGeneratorFunction:
liftFunctionDefinitionBegin(instr, keyword: "async function*", using: &w)
case .endArrowFunction(_),
.endAsyncArrowFunction:
w.leaveCurrentBlock()
w.emit("};")
case .endPlainFunction(_),
.endGeneratorFunction(_),
.endAsyncFunction(_),
.endAsyncGeneratorFunction:
w.leaveCurrentBlock()
w.emit("}")
case .beginConstructor(let op):
// Make the constructor name uppercased so that the difference to a plain function is visible, but also so that the heuristics to determine which functions are constructors in the ExplorationMutator work correctly.
let NAME = "F\(instr.output.number)"
w.declare(instr.output, as: NAME)
let vars = w.declareAll(instr.innerOutputs.dropFirst(), usePrefix: "a")
let PARAMS = liftParameters(op.parameters, as: vars)
w.emit("function \(NAME)(\(PARAMS)) {")
w.enterNewBlock()
// Disallow invoking constructors without `new` (i.e. Construct in FuzzIL).
w.emit("if (!new.target) { throw 'must be called with new'; }")
bindVariableToThis(instr.innerOutput(0))
case .endConstructor:
w.leaveCurrentBlock()
w.emit("}")
case .directive(let op):
assert(!op.content.contains("'"))
w.emit("'\(op.content)';")
case .return(let op):
if op.hasReturnValue {
let VALUE = input(0)
w.emit("return \(VALUE);")
} else {
w.emit("return;")
}
case .yield(let op):
let expr: Expression
if op.hasArgument {
expr = YieldExpression.new() + "yield " + input(0)
} else {
expr = YieldExpression.new() + "yield"
}
w.assign(expr, to: instr.output)
case .yieldEach:
let VALUES = input(0)
w.emit("yield* \(VALUES);")
case .await:
let expr = UnaryExpression.new() + "await " + input(0)
w.assign(expr, to: instr.output)
case .callFunction:
// Avoid inlining of the function expression. This is mostly for aesthetic reasons, but is also required if the expression for
// the function is a MemberExpression since it would otherwise be interpreted as a method call, not a function call.
let f = inputAsIdentifier(0)
let args = inputs.dropFirst()
let expr = CallExpression.new() + f + "(" + liftCallArguments(args) + ")"
w.assign(expr, to: instr.output)
case .callFunctionWithSpread(let op):
let f = inputAsIdentifier(0)
let args = inputs.dropFirst()
let expr = CallExpression.new() + f + "(" + liftCallArguments(args, spreading: op.spreads) + ")"
w.assign(expr, to: instr.output)
case .construct:
let f = inputAsIdentifier(0)
let args = inputs.dropFirst()
let expr = NewExpression.new() + "new " + f + "(" + liftCallArguments(args) + ")"
// For aesthetic reasons we disallow inlining "new" expressions so that their result is always assigned to a new variable.
w.assign(expr, to: instr.output, allowInlining: false)
case .constructWithSpread(let op):
let f = inputAsIdentifier(0)
let args = inputs.dropFirst()
let expr = NewExpression.new() + "new " + f + "(" + liftCallArguments(args, spreading: op.spreads) + ")"
// For aesthetic reasons we disallow inlining "new" expressions so that their result is always assigned to a new variable.
w.assign(expr, to: instr.output, allowInlining: false)
case .callMethod(let op):
let obj = input(0)
let method = MemberExpression.new() + obj + "." + op.methodName
let args = inputs.dropFirst()
let expr = CallExpression.new() + method + "(" + liftCallArguments(args) + ")"
w.assign(expr, to: instr.output)
case .callMethodWithSpread(let op):
let obj = input(0)
let method = MemberExpression.new() + obj + "." + op.methodName
let args = inputs.dropFirst()
let expr = CallExpression.new() + method + "(" + liftCallArguments(args, spreading: op.spreads) + ")"
w.assign(expr, to: instr.output)
case .callComputedMethod:
let obj = input(0)
let method = MemberExpression.new() + obj + "[" + input(1).text + "]"
let args = inputs.dropFirst(2)
let expr = CallExpression.new() + method + "(" + liftCallArguments(args) + ")"
w.assign(expr, to: instr.output)
case .callComputedMethodWithSpread(let op):
let obj = input(0)
let method = MemberExpression.new() + obj + "[" + input(1).text + "]"
let args = inputs.dropFirst(2)
let expr = CallExpression.new() + method + "(" + liftCallArguments(args, spreading: op.spreads) + ")"
w.assign(expr, to: instr.output)
case .unaryOperation(let op):
var input = input(0)
let expr: Expression
// Special case: we need parenthesis when performing a unary negation on a negative number literal, otherwise we'd end up with something like `--42`.
if op.op == .Minus && input.type === NegativeNumberLiteral {
input = NumberLiteral.new("(\(input.text))")
}
if op.op.isPostfix {
expr = UnaryExpression.new() + input + op.op.token
} else {
expr = UnaryExpression.new() + op.op.token + input
}
w.assign(expr, to: instr.output)
case .binaryOperation(let op):
var lhs = input(0)
let rhs = input(1)
// Special case: we need parenthesis when performing an exponentiation on a negative number literal, otherwise we get a syntax error:
// "Unary operator used immediately before exponentiation expression. Parenthesis must be used to disambiguate operator precedence"
if op.op == .Exp && lhs.type === NegativeNumberLiteral {
lhs = NumberLiteral.new("(\(lhs.text))")
}
let expr = BinaryExpression.new() + lhs + " " + op.op.token + " " + rhs
w.assign(expr, to: instr.output)
case .ternaryOperation:
let cond = input(0)
let value1 = input(1)
let value2 = input(2)
let expr = TernaryExpression.new() + cond + " ? " + value1 + " : " + value2
w.assign(expr, to: instr.output)
case .reassign:
let dest = input(0)
assert(dest.type === Identifier)
let expr = AssignmentExpression.new() + dest + " = " + input(1)
w.reassign(instr.input(0), to: expr)
case .update(let op):
let dest = input(0)
assert(dest.type === Identifier)
let expr = AssignmentExpression.new() + dest + " \(op.op.token)= " + input(1)
w.reassign(instr.input(0), to: expr)
case .dup:
let LET = w.declarationKeyword(for: instr.output)
let V = w.declare(instr.output)
let VALUE = input(0)
w.emit("\(LET) \(V) = \(VALUE);")
case .destructArray(let op):
let outputs = w.declareAll(instr.outputs)
let ARRAY = input(0)
let PATTERN = liftArrayDestructPattern(indices: op.indices, outputs: outputs, hasRestElement: op.lastIsRest)
let LET = w.varKeyword
w.emit("\(LET) [\(PATTERN)] = \(ARRAY);")
case .destructArrayAndReassign(let op):
assert(inputs.dropFirst().allSatisfy({ $0.type === Identifier }))
let ARRAY = input(0)
let outputs = inputs.dropFirst().map({ $0.text })
let PATTERN = liftArrayDestructPattern(indices: op.indices, outputs: outputs, hasRestElement: op.lastIsRest)
w.emit("[\(PATTERN)] = \(ARRAY);")
case .destructObject(let op):
let outputs = w.declareAll(instr.outputs)
let OBJ = input(0)
let PATTERN = liftObjectDestructPattern(properties: op.properties, outputs: outputs, hasRestElement: op.hasRestElement)
let LET = w.varKeyword
w.emit("\(LET) {\(PATTERN)} = \(OBJ);")
case .destructObjectAndReassign(let op):
assert(inputs.dropFirst().allSatisfy({ $0.type === Identifier }))
let OBJ = input(0)
let outputs = inputs.dropFirst().map({ $0.text })
let PATTERN = liftObjectDestructPattern(properties: op.properties, outputs: outputs, hasRestElement: op.hasRestElement)
w.emit("({\(PATTERN)} = \(OBJ));")
case .compare(let op):
let lhs = input(0)
let rhs = input(1)
let expr = BinaryExpression.new() + lhs + " " + op.op.token + " " + rhs
w.assign(expr, to: instr.output)
case .eval(let op):
// Woraround until Strings implement the CVarArg protocol in the linux Foundation library...
// TODO can make this permanent, but then use different placeholder pattern
var EXPR = op.code
for expr in inputs {
let range = EXPR.range(of: "%@")!
EXPR.replaceSubrange(range, with: expr.text)
}
if op.hasOutput {