-
Notifications
You must be signed in to change notification settings - Fork 8
/
FuzzILLifter.swift
490 lines (367 loc) · 18 KB
/
FuzzILLifter.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
// Copyright 2020 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
/// Lifter to convert FuzzIL into its human readable text format
public class FuzzILLifter: Lifter {
public init() {}
private func lift(_ instr : Instruction, with w: inout ScriptWriter) {
func input(_ n: Int) -> Variable {
return instr.input(n)
}
// Helper function to lift call arguments
func liftCallArguments(_ args: ArraySlice<Variable>, spreading spreads: [Bool] = []) -> String {
var arguments = [String]()
for (i, v) in args.enumerated() {
if spreads.count > i && spreads[i] {
arguments.append("...\(v.identifier)")
} else {
arguments.append(v.identifier)
}
}
return arguments.joined(separator: ", ")
}
// Helper function to lift destruct array operations
func liftArrayPattern(indices: [Int], outputs: [String], hasRestElement: Bool) -> String {
Assert(indices.count == outputs.count)
var arrayPattern = ""
var lastIndex = 0
for (index, output) in zip(indices, outputs) {
let skipped = index - lastIndex
lastIndex = index
let dots = index == indices.last! && hasRestElement ? "..." : ""
arrayPattern += String(repeating: ",", count: skipped) + dots + output
}
return arrayPattern
}
func liftObjectDestructPattern(properties: [String], outputs: [String], hasRestElement: Bool) -> String {
Assert(outputs.count == properties.count + (hasRestElement ? 1 : 0))
var objectPattern = ""
for (property, output) in zip(properties, outputs) {
objectPattern += "\(property):\(output),"
}
if hasRestElement {
objectPattern += "...\(outputs.last!)"
}
return objectPattern
}
switch instr.op {
case let op as LoadInteger:
w.emit("\(instr.output) <- LoadInteger '\(op.value)'")
case let op as LoadBigInt:
w.emit("\(instr.output) <- LoadBigInt '\(op.value)'")
case let op as LoadFloat:
w.emit("\(instr.output) <- LoadFloat '\(op.value)'")
case let op as LoadString:
w.emit("\(instr.output) <- LoadString '\(op.value)'")
case let op as LoadRegExp:
w.emit("\(instr.output) <- LoadRegExp '\(op.value)' '\(op.flags.asString())'")
case let op as LoadBoolean:
w.emit("\(instr.output) <- LoadBoolean '\(op.value)'")
case is LoadUndefined:
w.emit("\(instr.output) <- LoadUndefined")
case is LoadNull:
w.emit("\(instr.output) <- LoadNull")
case is LoadThis:
w.emit("\(instr.output) <- LoadThis")
case is LoadArguments:
w.emit("\(instr.output) <- LoadArguments")
case let op as CreateObject:
var properties = [String]()
for (index, propertyName) in op.propertyNames.enumerated() {
properties.append("'\(propertyName)':\(input(index))")
}
w.emit("\(instr.output) <- CreateObject [\(properties.joined(separator: ", "))]")
case is CreateArray:
let elems = instr.inputs.map({ $0.identifier }).joined(separator: ", ")
w.emit("\(instr.output) <- CreateArray [\(elems)]")
case let op as CreateObjectWithSpread:
var properties = [String]()
for (index, propertyName) in op.propertyNames.enumerated() {
properties.append("'\(propertyName)':\(input(index))")
}
// Remaining ones are spread.
for v in instr.inputs.dropFirst(properties.count) {
properties.append("...\(v)")
}
w.emit("\(instr.output) <- CreateObjectWithSpread [\(properties.joined(separator: ", "))]")
case let op as CreateArrayWithSpread:
var elems = [String]()
for (i, v) in instr.inputs.enumerated() {
if op.spreads[i] {
elems.append("...\(v)")
} else {
elems.append(v.identifier)
}
}
w.emit("\(instr.output) <- CreateArrayWithSpread [\(elems.joined(separator: ", "))]")
case let op as CreateTemplateString:
let parts = op.parts.map({ "'\($0)'" }).joined(separator: ", ")
let values = instr.inputs.map({ $0.identifier }).joined(separator: ", ")
w.emit("\(instr.output) <- CreateTemplateString [\(parts)], [\(values)]")
case let op as LoadBuiltin:
w.emit("\(instr.output) <- LoadBuiltin '\(op.builtinName)'")
case let op as LoadProperty:
w.emit("\(instr.output) <- LoadProperty \(input(0)), '\(op.propertyName)'")
case let op as StoreProperty:
w.emit("StoreProperty \(input(0)), '\(op.propertyName)', \(input(1))")
case let op as StorePropertyWithBinop:
w.emit("\(instr.input(0)) <- StorePropertyWithBinop '\(op.op.token)', \(input(1))")
case let op as DeleteProperty:
w.emit("\(instr.output) <- DeleteProperty \(input(0)), '\(op.propertyName)'")
case let op as LoadElement:
w.emit("\(instr.output) <- LoadElement \(input(0)), '\(op.index)'")
case let op as StoreElement:
w.emit("StoreElement \(input(0)), '\(op.index)', \(input(1))")
case let op as StoreElementWithBinop:
w.emit("\(instr.input(0)) <- StoreElementWithBinop '\(op.index)', '\(op.op.token)', \(input(1))")
case let op as DeleteElement:
w.emit("\(instr.output) <- DeleteElement \(input(0)), '\(op.index)'")
case is LoadComputedProperty:
w.emit("\(instr.output) <- LoadComputedProperty \(input(0)), \(input(1))")
case is StoreComputedProperty:
w.emit("StoreComputedProperty \(input(0)), \(input(1)), \(input(2))")
case let op as StoreComputedPropertyWithBinop:
w.emit("StoreComputedPropertyWithBinop \(input(0)), \(input(1)), '\(op.op.token)',\(input(2))")
case is DeleteComputedProperty:
w.emit("\(instr.output) <- DeleteComputedProperty \(input(0)), \(input(1))")
case is TypeOf:
w.emit("\(instr.output) <- TypeOf \(input(0))")
case is TestInstanceOf:
w.emit("\(instr.output) <- TestInstanceOf \(input(0)), \(input(1))")
case is TestIn:
w.emit("\(instr.output) <- TestIn \(input(0)), \(input(1))")
case let op as BeginAnyFunction:
let params = instr.innerOutputs.map({ $0.identifier }).joined(separator: ", ")
w.emit("\(instr.output) <- \(op.name) -> \(params)\(op.isStrict ? ", strict" : "")")
w.increaseIndentionLevel()
case let op as EndAnyFunction:
w.decreaseIndentionLevel()
w.emit("\(op.name)")
case is Return:
w.emit("Return \(input(0))")
case is DifferentialHash:
w.emit("DifferentialHash \(input(0))")
case is Yield:
w.emit("\(instr.output) <- Yield \(input(0))")
case is YieldEach:
w.emit("YieldEach \(input(0))")
case is Await:
w.emit("\(instr.output) <- Await \(input(0))")
case is CallFunction:
w.emit("\(instr.output) <- CallFunction \(input(0)), [\(liftCallArguments(instr.variadicInputs))]")
case let op as CallFunctionWithSpread:
w.emit("\(instr.output) <- CallFunctionWithSpread \(input(0)), [\(liftCallArguments(instr.variadicInputs, spreading: op.spreads))]")
case is Construct:
w.emit("\(instr.output) <- Construct \(input(0)), [\(liftCallArguments(instr.variadicInputs))]")
case let op as ConstructWithSpread:
w.emit("\(instr.output) <- ConstructWithSpread \(input(0)), [\(liftCallArguments(instr.variadicInputs, spreading: op.spreads))]")
case let op as CallMethod:
w.emit("\(instr.output) <- CallMethod \(input(0)), '\(op.methodName)', [\(liftCallArguments(instr.variadicInputs))]")
case let op as CallMethodWithSpread:
w.emit("\(instr.output) <- CallMethodWithSpread \(input(0)), '\(op.methodName)', [\(liftCallArguments(instr.variadicInputs, spreading: op.spreads))]")
case is CallComputedMethod:
w.emit("\(instr.output) <- CallComputedMethod \(input(0)), \(input(1)), [\(liftCallArguments(instr.variadicInputs))]")
case let op as CallComputedMethodWithSpread:
w.emit("\(instr.output) <- CallComputedMethodWithSpread \(input(0)), \(input(1)), [\(liftCallArguments(instr.variadicInputs, spreading: op.spreads))]")
case let op as UnaryOperation:
if op.op.isPostfix {
w.emit("\(instr.output) <- UnaryOperation \(input(0)), '\(op.op.token)'")
} else {
w.emit("\(instr.output) <- UnaryOperation '\(op.op.token)', \(input(0))")
}
case let op as BinaryOperation:
w.emit("\(instr.output) <- BinaryOperation \(input(0)), '\(op.op.token)', \(input(1))")
case let op as ReassignWithBinop:
w.emit("\(instr.input(0)) <- ReassignWithBinop '\(op.op.token)', \(input(1))")
case is Dup:
w.emit("\(instr.output) <- Dup \(input(0))")
case is Reassign:
w.emit("Reassign \(input(0)), \(input(1))")
case let op as DestructArray:
let outputs = instr.outputs.map({ $0.identifier })
w.emit("[\(liftArrayPattern(indices: op.indices, outputs: outputs, hasRestElement: op.hasRestElement))] <- DestructArray \(input(0))")
case let op as DestructArrayAndReassign:
let outputs = instr.inputs.dropFirst().map({ $0.identifier })
w.emit("[\(liftArrayPattern(indices: op.indices, outputs: outputs, hasRestElement: op.hasRestElement))] <- DestructArrayAndReassign \(input(0))")
case let op as DestructObject:
let outputs = instr.outputs.map({ $0.identifier })
w.emit("{\(liftObjectDestructPattern(properties: op.properties, outputs: outputs, hasRestElement: op.hasRestElement))} <- DestructObject \(input(0))")
case let op as DestructObjectAndReassign:
let outputs = instr.inputs.dropFirst().map({ $0.identifier })
w.emit("{\(liftObjectDestructPattern(properties: op.properties, outputs: outputs, hasRestElement: op.hasRestElement))} <- DestructObjectAndReassign \(input(0))")
case let op as Compare:
w.emit("\(instr.output) <- Compare \(input(0)), '\(op.op.token)', \(input(1))")
case is ConditionalOperation:
w.emit("\(instr.output) <- ConditionalOperation \(input(0)), \(input(1)), \(input(2))")
case let op as Eval:
let args = instr.inputs.map({ $0.identifier }).joined(separator: ", ")
w.emit("Eval '\(op.code)', [\(args)]")
case is Explore:
w.emit("Explore \(instr.input(0)), [\(liftCallArguments(instr.variadicInputs))]")
case is BeginWith:
w.emit("BeginWith \(input(0))")
w.increaseIndentionLevel()
case is EndWith:
w.decreaseIndentionLevel()
w.emit("EndWith")
case let op as LoadFromScope:
w.emit("\(instr.output) <- LoadFromScope '\(op.id)'")
case let op as StoreToScope:
w.emit("StoreToScope '\(op.id)', \(input(0))")
case is Nop:
w.emit("Nop")
case is BeginIf:
w.emit("BeginIf \(input(0))")
w.increaseIndentionLevel()
case is BeginElse:
w.decreaseIndentionLevel()
w.emit("BeginElse")
w.increaseIndentionLevel()
case is EndIf:
w.decreaseIndentionLevel()
w.emit("EndIf")
case let op as BeginSwitch:
w.emit("BeginSwitch \(input(0))\(op.isDefaultCase ? "" : input(1).description)")
w.increaseIndentionLevel()
case let op as BeginSwitchCase:
w.decreaseIndentionLevel()
w.emit("BeginSwitchCase \(op.isDefaultCase ? "" : input(0).description) \(op.previousCaseFallsThrough ? "previousCaseFallsThrough" : "")")
w.increaseIndentionLevel()
case is EndSwitch:
w.decreaseIndentionLevel()
w.emit("EndSwitch")
case let op as BeginClass:
var line = "\(instr.output) <- BeginClass"
if instr.hasInputs {
line += " \(input(0)),"
}
line += " \(op.instanceProperties),"
line += " \(Array(op.instanceMethods.map({ $0.name })))"
w.emit(line)
w.increaseIndentionLevel()
case is BeginMethod:
w.decreaseIndentionLevel()
let params = instr.innerOutputs.map({ $0.identifier }).joined(separator: ", ")
w.emit("BeginMethod -> \(params)")
w.increaseIndentionLevel()
case is EndClass:
w.decreaseIndentionLevel()
w.emit("EndClass")
case is CallSuperConstructor:
w.emit("CallSuperConstructor [\(liftCallArguments(instr.variadicInputs))]")
case let op as CallSuperMethod:
w.emit("\(instr.output) <- CallSuperMethod '\(op.methodName)', [\(liftCallArguments(instr.variadicInputs))]")
case let op as LoadSuperProperty:
w.emit("\(instr.output) <- LoadSuperProperty '\(op.propertyName)'")
case let op as StoreSuperProperty:
w.emit("StoreSuperProperty '\(op.propertyName)', \(input(0))")
case let op as StoreSuperPropertyWithBinop:
w.emit("StoreSuperPropertyWithBinop '\(op.propertyName)', '\(op.op.token)', \(input(0))")
case let op as BeginWhileLoop:
w.emit("BeginWhileLoop \(input(0)), '\(op.comparator.token)', \(input(1))")
w.increaseIndentionLevel()
case is EndWhileLoop:
w.decreaseIndentionLevel()
w.emit("EndWhileLoop")
case let op as BeginDoWhileLoop:
w.emit("BeginDoWhileLoop \(input(0)), '\(op.comparator.token)', \(input(1))")
w.increaseIndentionLevel()
case is EndDoWhileLoop:
w.decreaseIndentionLevel()
w.emit("EndDoWhileLoop")
case let op as BeginForLoop:
w.emit("BeginForLoop \(input(0)), '\(op.comparator.token)', \(input(1)), '\(op.op.token)', \(input(2)) -> \(instr.innerOutput)")
w.increaseIndentionLevel()
case is EndForLoop:
w.decreaseIndentionLevel()
w.emit("EndForLoop")
case is BeginForInLoop:
w.emit("BeginForInLoop \(input(0)) -> \(instr.innerOutput)")
w.increaseIndentionLevel()
case is EndForInLoop:
w.decreaseIndentionLevel()
w.emit("EndForInLoop")
case is BeginForOfLoop:
w.emit("BeginForOfLoop \(input(0)) -> \(instr.innerOutput)")
w.increaseIndentionLevel()
case let op as BeginForOfWithDestructLoop:
let outputs = instr.innerOutputs.map({ $0.identifier })
w.emit(" BeginForOfLoop \(input(0)) -> [\(liftArrayPattern(indices: op.indices, outputs: outputs, hasRestElement: op.hasRestElement))]")
w.increaseIndentionLevel()
case is EndForOfLoop:
w.decreaseIndentionLevel()
w.emit("EndForOfLoop")
case is LoopBreak,
is SwitchBreak:
w.emit("Break")
case is LoopContinue:
w.emit("Continue")
case is BeginTry:
w.emit("BeginTry")
w.increaseIndentionLevel()
case is BeginCatch:
w.decreaseIndentionLevel()
w.emit("BeginCatch -> \(instr.innerOutput)")
w.increaseIndentionLevel()
case is BeginFinally:
w.decreaseIndentionLevel()
w.emit("BeginFinally")
w.increaseIndentionLevel()
case is EndTryCatchFinally:
w.decreaseIndentionLevel()
w.emit("EndTryCatch")
case is ThrowException:
w.emit("ThrowException \(input(0))")
case is BeginCodeString:
w.emit("\(instr.output) <- BeginCodeString")
w.increaseIndentionLevel()
case is EndCodeString:
w.decreaseIndentionLevel()
w.emit("EndCodeString")
case is BeginBlockStatement:
w.emit("BeginBlockStatement")
w.increaseIndentionLevel()
case is EndBlockStatement:
w.decreaseIndentionLevel()
w.emit("EndBlockStatement")
case is Print:
w.emit("Print \(input(0))")
default:
fatalError("Unhandled Operation: \(type(of: instr.op))")
}
}
public func lift(_ program: Program, withOptions options: LiftingOptions) -> String {
var w = ScriptWriter()
if options.contains(.includeComments), let header = program.comments.at(.header) {
w.emitComment(header)
}
for instr in program.code {
if options.contains(.includeComments), let comment = program.comments.at(.instruction(instr.index)) {
w.emitComment(comment)
}
lift(instr, with: &w)
}
if options.contains(.includeComments), let footer = program.comments.at(.footer) {
w.emitComment(footer)
}
return w.code
}
public func lift(_ code: Code) -> String {
var w = ScriptWriter()
for instr in code {
lift(instr, with: &w)
}
return w.code
}
}