forked from googleprojectzero/fuzzilli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ProgramBuilder.swift
1653 lines (1396 loc) · 66.8 KB
/
ProgramBuilder.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.
/// Builds programs.
///
/// This provides methods for constructing and appending random
/// instances of the different kinds of operations in a program.
public class ProgramBuilder {
/// The fuzzer instance for which this builder is active.
public let fuzzer: Fuzzer
/// The code and type information of the program that is being constructed.
private var code = Code()
public var types = ProgramTypes()
/// Comments for the program that is being constructed.
private var comments = ProgramComments()
/// The parent program for the program being constructed.
private let parent: Program?
public enum Mode {
/// In this mode, the builder will try as hard as possible to generate semantically valid code.
/// However, the generated code is likely not as diverse as in aggressive mode.
case conservative
/// In this mode, the builder tries to generate more diverse code. However, the generated
/// code likely has a lower probability of being semantically correct.
case aggressive
}
/// The mode of this builder
public var mode: Mode
/// Whether to perform splicing as part of the code generation.
public var performSplicingDuringCodeGeneration = true
public var context: Context {
return contextAnalyzer.context
}
/// Counter to quickly determine the next free variable.
private var numVariables = 0
/// Property names and integer values previously seen in the current program.
private var seenPropertyNames = Set<String>()
private var seenIntegers = Set<Int64>()
private var seenFloats = Set<Double>()
/// Keep track of existing variables containing known values. For the reuseOrLoadX APIs.
/// Important: these will contain variables that are no longer in scope. As such, they generally
/// have to be used in combination with the scope analyzer.
private var loadedBuiltins = VariableMap<String>()
private var loadedIntegers = VariableMap<Int64>()
private var loadedFloats = VariableMap<Double>()
/// Various analyzers for the current program.
private var scopeAnalyzer = ScopeAnalyzer()
private var contextAnalyzer = ContextAnalyzer()
/// Abstract interpreter to computer type information.
private var interpreter: AbstractInterpreter?
/// During code generation, contains the minimum number of remaining instructions
/// that should still be generated.
private var currentCodegenBudget = 0
/// Whether there are any variables currently in scope.
public var hasVisibleVariables: Bool {
return scopeAnalyzer.visibleVariables.count > 0
}
/// Constructs a new program builder for the given fuzzer.
init(for fuzzer: Fuzzer, parent: Program?, interpreter: AbstractInterpreter?, mode: Mode) {
self.fuzzer = fuzzer
self.interpreter = interpreter
self.mode = mode
self.parent = parent
}
/// Resets this builder.
public func reset() {
numVariables = 0
seenPropertyNames.removeAll()
seenIntegers.removeAll()
seenFloats.removeAll()
loadedBuiltins.removeAll()
loadedIntegers.removeAll()
loadedFloats.removeAll()
code.removeAll()
types = ProgramTypes()
scopeAnalyzer = ScopeAnalyzer()
contextAnalyzer = ContextAnalyzer()
interpreter?.reset()
currentCodegenBudget = 0
}
/// Finalizes and returns the constructed program, then resets this builder so it can be reused for building another program.
public func finalize() -> Program {
Assert(openFunctions.isEmpty)
let program = Program(code: code, parent: parent, types: types, comments: comments)
// TODO set type status to something meaningful?
reset()
return program
}
/// Prints the current program as FuzzIL code to stdout. Useful for debugging.
public func dumpCurrentProgram() {
print(FuzzILLifter().lift(code))
}
/// Returns the index of the next instruction added to the program. This is equal to the current size of the program.
public func indexOfNextInstruction() -> Int {
return code.count
}
/// Add a trace comment to the currently generated program at the current position.
/// This is only done if history inspection is enabled.
public func trace(_ commentGenerator: @autoclosure () -> String) {
if fuzzer.config.inspection.contains(.history) {
// Use an autoclosure here so that template strings are only evaluated when they are needed.
comments.add(commentGenerator(), at: .instruction(code.count))
}
}
/// Add a trace comment at the start of the currently generated program.
/// This is only done if history inspection is enabled.
public func traceHeader(_ commentGenerator: @autoclosure () -> String) {
if fuzzer.config.inspection.contains(.history) {
comments.add(commentGenerator(), at: .header)
}
}
/// Generates a random integer for the current program context.
public func genInt() -> Int64 {
// Either pick a previously seen integer or generate a random one
if probability(0.2) && seenIntegers.count >= 2 {
return chooseUniform(from: seenIntegers)
} else {
return withEqualProbability({
chooseUniform(from: self.fuzzer.environment.interestingIntegers)
}, {
Int64.random(in: -0x100000000...0x100000000)
})
}
}
/// Generates a random regex pattern.
public func genRegExp() -> String {
// Generate a "base" regexp
var regex = ""
let desiredLength = Int.random(in: 1...4)
while regex.count < desiredLength {
regex += withEqualProbability({
String.random(ofLength: 1)
}, {
chooseUniform(from: self.fuzzer.environment.interestingRegExps)
})
}
// Now optionally concatenate with another regexp
if probability(0.3) {
regex += genRegExp()
}
// Or add a quantifier, if there is not already a quantifier in the last position.
if probability(0.2) && !self.fuzzer.environment.interestingRegExpQuantifiers.contains(String(regex.last!)) {
regex += chooseUniform(from: self.fuzzer.environment.interestingRegExpQuantifiers)
}
// Or wrap in brackets
if probability(0.1) {
withEqualProbability({
// optionally invert the character set
if probability(0.2) {
regex = "^" + regex
}
regex = "[" + regex + "]"
}, {
regex = "(" + regex + ")"
})
}
return regex
}
/// Generates a random set of RegExpFlags
public func genRegExpFlags() -> RegExpFlags {
return RegExpFlags.random()
}
/// Generates a random index value for the current program context.
public func genIndex() -> Int64 {
return genInt()
}
/// Generates a random integer for the current program context.
public func genFloat() -> Double {
// TODO improve this
if probability(0.2) && seenFloats.count >= 2 {
return chooseUniform(from: seenFloats)
} else {
return withEqualProbability({
chooseUniform(from: self.fuzzer.environment.interestingFloats)
}, {
Double.random(in: -1000000...1000000)
})
}
}
/// Generates a random string value for the current program context.
public func genString() -> String {
return withEqualProbability({
self.genPropertyNameForRead()
}, {
chooseUniform(from: self.fuzzer.environment.interestingStrings)
}, {
String.random(ofLength: 10)
}, {
String(chooseUniform(from: self.fuzzer.environment.interestingIntegers))
})
}
/// Generates a random builtin name for the current program context.
public func genBuiltinName() -> String {
return chooseUniform(from: fuzzer.environment.builtins)
}
/// Generates a random property name for the current program context.
public func genPropertyNameForRead() -> String {
if probability(0.15) && seenPropertyNames.count >= 2 {
return chooseUniform(from: seenPropertyNames)
} else {
return chooseUniform(from: fuzzer.environment.readPropertyNames)
}
}
/// Generates a random property name for the current program context.
public func genPropertyNameForWrite() -> String {
if probability(0.15) && seenPropertyNames.count >= 2 {
return chooseUniform(from: seenPropertyNames)
} else {
return chooseUniform(from: fuzzer.environment.writePropertyNames)
}
}
/// Generates a random method name for the current program context.
public func genMethodName() -> String {
return chooseUniform(from: fuzzer.environment.methodNames)
}
///
/// Access to variables.
///
/// Returns a random variable.
public func randVar(excludeInnermostScope: Bool = false) -> Variable {
Assert(hasVisibleVariables)
return randVarInternal(excludeInnermostScope: excludeInnermostScope)!
}
/// Returns a random variable of the given type.
///
/// In conservative mode, this function fails unless it finds a matching variable.
/// In aggressive mode, this function will also return variables that have unknown type, and may, if no matching variables are available, return variables of any type.
///
/// In certain cases, for example in the InputMutator, it might be required to exclude variables from the innermost scopes, which can be achieved by passing excludeInnermostScope: true.
public func randVar(ofType type: Type, excludeInnermostScope: Bool = false) -> Variable? {
var wantedType = type
// As query/input type, .unknown is treated as .anything.
// This for example simplifies code that is attempting to replace a given variable with another one with a "compatible" type.
// If the real type of the replaced variable is unknown, it doesn't make sense to search for another variable of unknown type, so just use .anything.
if wantedType.Is(.unknown) {
wantedType = .anything
}
if mode == .aggressive {
wantedType |= .unknown
}
if let v = randVarInternal(filter: { self.type(of: $0).Is(wantedType) }, excludeInnermostScope: excludeInnermostScope) {
return v
}
// Didn't find a matching variable. If we are in aggressive mode, we now simply return a random variable.
if mode == .aggressive {
return randVar()
}
// Otherwise, we give up
return nil
}
/// Returns a random variable of the given type. This is the same as calling randVar in conservative building mode.
public func randVar(ofConservativeType type: Type) -> Variable? {
let oldMode = mode
mode = .conservative
defer { mode = oldMode }
return randVar(ofType: type)
}
/// Returns a random variable satisfying the given constraints or nil if none is found.
func randVarInternal(filter: ((Variable) -> Bool)? = nil, excludeInnermostScope: Bool = false) -> Variable? {
var candidates = [Variable]()
let scopes = excludeInnermostScope ? scopeAnalyzer.scopes.dropLast() : scopeAnalyzer.scopes
// Prefer inner scopes
withProbability(0.75) {
candidates = chooseBiased(from: scopes, factor: 1.25)
if let f = filter {
candidates = candidates.filter(f)
}
}
if candidates.isEmpty {
let visibleVariables = excludeInnermostScope ? scopes.reduce([], +) : scopeAnalyzer.visibleVariables
if let f = filter {
candidates = visibleVariables.filter(f)
} else {
candidates = visibleVariables
}
}
if candidates.isEmpty {
return nil
}
return chooseUniform(from: candidates)
}
/// Type information access.
public func type(of v: Variable) -> Type {
return types.getType(of: v, after: code.lastInstruction.index)
}
public func type(ofProperty property: String) -> Type {
return interpreter?.type(ofProperty: property) ?? .unknown
}
/// Returns the type of the `super` binding at the current position.
public func currentSuperType() -> Type {
return interpreter?.currentSuperType() ?? .unknown
}
public func methodSignature(of methodName: String, on object: Variable) -> FunctionSignature {
return interpreter?.inferMethodSignature(of: methodName, on: object) ?? FunctionSignature.forUnknownFunction
}
public func methodSignature(of methodName: String, on objType: Type) -> FunctionSignature {
return interpreter?.inferMethodSignature(of: methodName, on: objType) ?? FunctionSignature.forUnknownFunction
}
public func setType(ofProperty propertyName: String, to propertyType: Type) {
trace("Setting global property type: \(propertyName) => \(propertyType)")
interpreter?.setType(ofProperty: propertyName, to: propertyType)
}
public func setType(ofVariable variable: Variable, to variableType: Type) {
interpreter?.setType(of: variable, to: variableType)
}
public func setSignature(ofMethod methodName: String, to methodSignature: FunctionSignature) {
trace("Setting global method signature: \(methodName) => \(methodSignature)")
interpreter?.setSignature(ofMethod: methodName, to: methodSignature)
}
// This expands and collects types for arguments in function signatures.
private func prepareArgumentTypes(forSignature signature: FunctionSignature) -> [Type] {
var argumentTypes = [Type]()
for param in signature.parameters {
if param.isOptional {
// It's an optional argument, so stop here in some cases
if probability(0.25) {
break
}
}
if param.isRestParam {
// "Unroll" the rest parameter
for _ in 0..<Int.random(in: 0...5) {
argumentTypes.append(param.callerType)
}
// Rest parameter must be the last one
break
}
argumentTypes.append(param.callerType)
}
return argumentTypes
}
public func generateCallArguments(for signature: FunctionSignature) -> [Variable] {
let argumentTypes = prepareArgumentTypes(forSignature: signature)
var arguments = [Variable]()
for argumentType in argumentTypes {
if let v = randVar(ofConservativeType: argumentType) {
arguments.append(v)
} else {
let argument = generateVariable(ofType: argumentType)
// make sure, that now after generation we actually have a
// variable of that type available.
Assert(randVar(ofType: argumentType) != nil)
arguments.append(argument)
}
}
return arguments
}
public func randCallArguments(for signature: FunctionSignature) -> [Variable]? {
let argumentTypes = prepareArgumentTypes(forSignature: signature)
var arguments = [Variable]()
for argumentType in argumentTypes {
guard let v = randVar(ofType: argumentType) else { return nil }
arguments.append(v)
}
return arguments
}
public func randCallArguments(for function: Variable) -> [Variable]? {
let signature = type(of: function).signature ?? FunctionSignature.forUnknownFunction
return randCallArguments(for: signature)
}
public func generateCallArguments(for function: Variable) -> [Variable] {
let signature = type(of: function).signature ?? FunctionSignature.forUnknownFunction
return generateCallArguments(for: signature)
}
public func randCallArguments(forMethod methodName: String, on object: Variable) -> [Variable]? {
let signature = methodSignature(of: methodName, on: object)
return randCallArguments(for: signature)
}
public func randCallArguments(forMethod methodName: String, on objType: Type) -> [Variable]? {
let signature = methodSignature(of: methodName, on: objType)
return randCallArguments(for: signature)
}
public func randCallArgumentsWithSpreading(n: Int) -> (arguments: [Variable], spreads: [Bool]) {
var arguments: [Variable] = []
var spreads: [Bool] = []
for _ in 0...n {
let val = randVar()
arguments.append(val)
// Prefer to spread values that we know are iterable, as non-iterable values will lead to exceptions ("TypeError: Found non-callable @@iterator")
if type(of: val).Is(.iterable) {
spreads.append(probability(0.9))
} else {
spreads.append(probability(0.1))
}
}
return (arguments, spreads)
}
public func generateCallArguments(forMethod methodName: String, on object: Variable) -> [Variable] {
let signature = methodSignature(of: methodName, on: object)
return generateCallArguments(for: signature)
}
/// Generates a sequence of instructions that generate the desired type.
/// This function can currently generate:
/// - primitive types
/// - arrays
/// - objects of certain types
/// - plain objects with properties that are either generated or selected
/// and methods that are selected from the environment.
/// It currently cannot generate:
/// - methods for objects
func generateVariable(ofType type: Type) -> Variable {
trace("Generating variable of type \(type)")
// Check primitive types
if type.Is(.integer) || type.Is(fuzzer.environment.intType) {
return loadInt(genInt())
}
if type.Is(.float) || type.Is(fuzzer.environment.floatType) {
return loadFloat(genFloat())
}
if type.Is(.string) || type.Is(fuzzer.environment.stringType) {
return loadString(genString())
}
if type.Is(.boolean) || type.Is(fuzzer.environment.booleanType) {
return loadBool(Bool.random())
}
if type.Is(.bigint) || type.Is(fuzzer.environment.bigIntType) {
return loadBigInt(genInt())
}
if type.Is(.function()) {
let signature = type.signature ?? FunctionSignature(withParameterCount: Int.random(in: 2...5), hasRestParam: probability(0.1))
return buildPlainFunction(withSignature: signature, isStrict: probability(0.1)) { _ in
generateRecursive()
doReturn(value: randVar())
}
}
if type.Is(.regexp) || type.Is(fuzzer.environment.regExpType) {
return loadRegExp(genRegExp(), genRegExpFlags())
}
Assert(type.Is(.object()), "Unexpected type encountered \(type)")
// The variable that we will return.
var obj: Variable
// Fast path for array creation.
if type.Is(fuzzer.environment.arrayType) && probability(0.9) {
let value = randVar()
return createArray(with: Array(repeating: value, count: Int.random(in: 1...5)))
}
if let group = type.group {
// Objects with predefined groups must be constructable through a Builtin exposed by the Environment.
// Normally, that builtin is a .constructor(), but we also allow just a .function() for constructing object.
// This is for example necessary for JavaScript Symbols, as the Symbol builtin is not a constructor.
let constructorType = fuzzer.environment.type(ofBuiltin: group)
Assert(constructorType.Is(.function() | .constructor()), "We don't know how to construct \(group)")
Assert(constructorType.signature != nil, "We don't know how to construct \(group) (missing signature for constructor)")
Assert(constructorType.signature!.outputType.group == group, "We don't know how to construct \(group) (invalid signature for constructor)")
let constructorSignature = constructorType.signature!
let arguments = generateCallArguments(for: constructorSignature)
let constructor = loadBuiltin(group)
if !constructorType.Is(.constructor()) {
obj = callFunction(constructor, withArgs: arguments)
} else {
obj = construct(constructor, withArgs: arguments)
}
} else {
// Either generate a literal or use the store property stuff.
if probability(0.8) { // Do the literal
var initialProperties: [String: Variable] = [:]
// gather properties of the correct types
for prop in type.properties {
var value: Variable?
let type = self.type(ofProperty: prop)
if type != .unknown {
// TODO Here and elsewhere in this function: turn this pattern into a new helper function,
// e.g. reuseOrGenerateVariable(ofType: ...). See also the discussions in
// https://github.com/googleprojectzero/fuzzilli/blob/main/Docs/HowFuzzilliWorks.md#when-to-instantiate
// TODO I don't think we need to use the ofConservativeType version. The regular ofType version should
// be fine since the ProgramTemplates/HybridEngine do the code generation in conservative mode anyway.
value = randVar(ofConservativeType: type) ?? generateVariable(ofType: type)
} else {
if !hasVisibleVariables {
value = loadInt(genInt())
} else {
value = randVar()
}
}
initialProperties[prop] = value
}
// TODO: This should take the method type/signature into account!
_ = type.methods.map { initialProperties[$0] = randVar(ofType: .function()) ?? generateVariable(ofType: .function()) }
obj = createObject(with: initialProperties)
} else { // Do it with storeProperty
obj = construct(loadBuiltin("Object"), withArgs: [])
for method in type.methods {
// TODO: This should take the method type/signature into account!
let methodVar = randVar(ofType: .function()) ?? generateVariable(ofType: .function())
storeProperty(methodVar, as: method, on: obj)
}
// These types might have been defined in the interpreter
for prop in type.properties {
var value: Variable?
let type = self.type(ofProperty: prop)
if type != .unknown {
value = randVar(ofConservativeType: type) ?? generateVariable(ofType: type)
} else {
value = randVar()
}
storeProperty(value!, as: prop, on: obj)
}
}
}
return obj
}
///
/// Adoption of variables from a different program.
/// Required when copying instructions between program.
///
private var varMaps = [VariableMap<Variable>]()
/// Formatted ProgramTypes structure for easier adopting of runtimeTypes
private var runtimeTypesMaps = [[[(Variable, Type)]]]()
/// Prepare for adoption of variables from the given program.
///
/// This sets up a mapping for variables from the given program to the
/// currently constructed one to avoid collision of variable names.
public func beginAdoption(from program: Program) {
varMaps.append(VariableMap())
runtimeTypesMaps.append(program.types.onlyRuntimeTypes().indexedByInstruction(for: program))
}
/// Finishes the most recently started adoption.
public func endAdoption() {
varMaps.removeLast()
runtimeTypesMaps.removeLast()
}
/// Executes the given block after preparing for adoption from the provided program.
public func adopting(from program: Program, _ block: () -> Void) {
beginAdoption(from: program)
block()
endAdoption()
}
/// Maps a variable from the program that is currently configured for adoption into the program being constructed.
public func adopt(_ variable: Variable) -> Variable {
if !varMaps.last!.contains(variable) {
varMaps[varMaps.count - 1][variable] = nextVariable()
}
return varMaps.last![variable]!
}
private func createVariableMapping(from sourceVariable: Variable, to hostVariable: Variable) {
Assert(!varMaps.last!.contains(sourceVariable))
varMaps[varMaps.count - 1][sourceVariable] = hostVariable
}
/// Maps a list of variables from the program that is currently configured for adoption into the program being constructed.
public func adopt<Variables: Collection>(_ variables: Variables) -> [Variable] where Variables.Element == Variable {
return variables.map(adopt)
}
private func adoptTypes(at origInstrIndex: Int) {
for (variable, type) in runtimeTypesMaps.last![origInstrIndex] {
// No need to keep unknown type nor type of not adopted variable
if let adoptedVariable = varMaps.last![variable] {
// Unknown runtime types should not be saved in ProgramTypes
Assert(type != .unknown)
interpreter?.setType(of: adoptedVariable, to: type)
// We should save this type even if we do not have interpreter
// This way we can use runtime types without interpreter
types.setType(of: adoptedVariable, to: type, after: code.lastInstruction.index, quality: .runtime)
}
}
}
/// Adopts an instruction from the program that is currently configured for adoption into the program being constructed.
public func adopt(_ instr: Instruction, keepTypes: Bool) {
internalAppend(Instruction(instr.op, inouts: adopt(instr.inouts)))
if keepTypes {
adoptTypes(at: instr.index)
}
}
/// Append an instruction at the current position.
public func append(_ instr: Instruction) {
for v in instr.allOutputs {
numVariables = max(v.number + 1, numVariables)
}
internalAppend(instr)
}
/// Append a program at the current position.
///
/// This also renames any variable used in the given program so all variables
/// from the appended program refer to the same values in the current program.
public func append(_ program: Program) {
adopting(from: program) {
for instr in program.code {
adopt(instr, keepTypes: true)
}
}
}
/// Append a splice from another program.
public func splice(from program: Program, at index: Int) {
trace("Splicing instruction \(index) (\(program.code[index].op.name)) from \(program.id)")
beginAdoption(from: program)
let source = program.code
// The slice of the given program that will be inserted into the current program.
var slice = Set<Int>()
// Determine all necessary input instructions for the choosen instruction
// We need special handling for blocks:
// If the choosen instruction is a block instruction then copy the whole block
// If we need an inner output of a block instruction then only copy the block instructions, not the content
// Otherwise copy the whole block including its content
var requiredInputs = VariableSet()
// A Set of variables that have yet to be included in the slice
var remainingInputs = VariableSet()
// A stack of contexts that are required by the instruction in the slice
var requiredContextStack = [Context.empty]
// Helper function to handle context updates when handling block instructions
func handleBlockInstruction(instruction instr: Instruction, shouldAdd: Bool = false){
// When we encounter a block begin:
// 1. We ensure that the context being opened removes at least one required context
// 2. The default context (.script) isn't the only context being removed
// 3. The required context is not empty
if instr.isBlockStart {
var requiredContext = requiredContextStack.removeLast()
if requiredContext.subtracting(instr.op.contextOpened) != requiredContext && requiredContext.intersection(instr.op.contextOpened) != .script && requiredContext != .empty {
requiredContextStack.append(requiredContext)
if shouldAdd {
add(instr)
}
requiredContext = requiredContextStack.removeLast()
}
requiredContext = requiredContext.subtracting(instr.op.contextOpened)
// If the required context is not a subset of the current stack top, then we have contexts that should be propagated to the current stack top
// We must have at least one context on the stack
if requiredContextStack.count >= 1 {
var currentTop = requiredContextStack.removeLast()
requiredContext = requiredContext.subtracting(currentTop)
if requiredContext != .empty {
currentTop.formUnion(requiredContext)
}
requiredContextStack.append(currentTop)
} else {
requiredContextStack.append(requiredContext)
}
}
if instr.isBlockEnd {
requiredContextStack.append([])
}
}
// Helper function to add a context to the context stack
func addContextRequired(requiredContext: Context) {
var currentContext = requiredContextStack.removeLast()
currentContext.formUnion(requiredContext)
requiredContextStack.append(currentContext)
}
// Helper function to add an instruction, or possibly multiple instruction in the case of blocks, to the slice.
func add(_ instr: Instruction, includeBlockContent: Bool = false) {
guard !slice.contains(instr.index) else { return }
func internalAdd(_ instr: Instruction) {
remainingInputs.subtract(instr.allOutputs)
requiredInputs.formUnion(instr.inputs)
remainingInputs.formUnion(instr.inputs)
addContextRequired(requiredContext: instr.op.requiredContext)
handleBlockInstruction(instruction: instr)
slice.insert(instr.index)
}
if instr.isBlock {
let group = BlockGroup(around: instr, in: source)
let instructions = includeBlockContent ? group.includingContent() : group.excludingContent()
// Instructions within blocks are evaluated in reverse order so that the evaluation is consistent with the caller loop
for instr in instructions.reversed() {
internalAdd(instr)
}
} else {
internalAdd(instr)
}
}
// Compute the slice...
var idx = index
// First, add the selected instruction.
add(source[idx], includeBlockContent: true)
// Then add all instructions that the slice has data dependencies on.
while idx > 0 {
// This is the exit condition from the loop
// We have no remaining inputs to account for and
// There's only one context on the stack which must be a subset of self.context (i.e. context of the host program)
if remainingInputs.isEmpty && requiredContextStack.count == 1 {
let requiredContext = requiredContextStack.last!
if requiredContext.isSubset(of: self.context) {
break
}
}
idx -= 1
let instr = source[idx]
if !requiredInputs.isDisjoint(with: instr.allOutputs) {
let onlyNeedsInnerOutputs = requiredInputs.isDisjoint(with: instr.outputs)
// If we only need inner outputs (e.g. function parameters), then we don't include
// the block's content in the slice. Otherwise we do.
add(instr, includeBlockContent: !onlyNeedsInnerOutputs)
}
// If we perform a potentially mutating operation (such as a property store or a method call)
// on a required variable, then we may decide to keep that instruction as well.
if mode == .conservative || (mode == .aggressive && probability(0.5)) {
if instr.mayMutate(requiredInputs) {
add(instr)
}
}
handleBlockInstruction(instruction: instr, shouldAdd: true)
}
// If, after the loop, the current context does not contain the required context (e.g. because we are just after a BeginSwitch), abort the splicing
let stillRequired = requiredContextStack.removeLast()
guard stillRequired.isSubset(of: self.context) else {
endAdoption()
return
}
// Finally, insert the slice into the current program.
for instr in source {
if slice.contains(instr.index) {
adopt(instr, keepTypes: true)
}
}
endAdoption()
trace("Splicing done")
}
func splice(from program: Program) {
// Pick a starting instruction from the selected program.
// For that, prefer dataflow "sinks" whose outputs are not used for anything else,
// as these are probably the most interesting instructions.
var idx = 0
var counter = 0
repeat {
counter += 1
idx = Int.random(in: 0..<program.size)
// Some instructions are less suited to be the start of a splice. Skip them.
} while counter < 25 && (program.code[idx].isJump || program.code[idx].isBlockEnd || !program.code[idx].hasInputs)
splice(from: program, at: idx)
}
private var openFunctions = [Variable]()
private func callLikelyRecurses(function: Variable) -> Bool {
return openFunctions.contains(function)
}
/// Executes a code generator.
///
/// - Parameter generators: The code generator to run at the current position.
/// - Returns: the number of instructions added by all generators.
public func run(_ generator: CodeGenerator, recursiveCodegenBudget: Int? = nil) {
Assert(generator.requiredContext.isSubset(of: context))
if let budget = recursiveCodegenBudget {
currentCodegenBudget = budget
}
var inputs: [Variable] = []
for type in generator.inputTypes {
guard let val = randVar(ofType: type) else { return }
// In conservative mode, attempt to prevent direct recursion to reduce the number of timeouts
// This is a very crude mechanism. It might be worth implementing a more sophisticated one.
if mode == .conservative && type.Is(.function()) && callLikelyRecurses(function: val) { return }
inputs.append(val)
}
self.trace("Executing code generator \(generator.name)")
generator.run(in: self, with: inputs)
self.trace("Code generator finished")
}
private func generateInternal() {
while currentCodegenBudget > 0 {
// There are two modes of code generation:
// 1. Splice code from another program in the corpus
// 2. Pick a CodeGenerator, find or generate matching variables, and execute it
withEqualProbability({
guard self.performSplicingDuringCodeGeneration else { return }
let program = self.fuzzer.corpus.randomElementForSplicing()
self.splice(from: program)
}, {
// We can't run code generators if we don't have any visible variables.
if self.scopeAnalyzer.visibleVariables.isEmpty {
// Generate some variables
self.run(chooseUniform(from: self.fuzzer.trivialCodeGenerators))
Assert(!self.scopeAnalyzer.visibleVariables.isEmpty)
}
// Enumerate generators that have the required context
// TODO: To improve performance it may be beneficial to implement a caching mechanism for these results
var availableGenerators: [CodeGenerator] = []
for generator in self.fuzzer.codeGenerators {
if generator.requiredContext.isSubset(of: self.context) {
availableGenerators.append(generator)
}
}
guard !availableGenerators.isEmpty else { return }
// Select a generator at random and run it
let generator = chooseUniform(from: availableGenerators)
self.run(generator)
})
// This effectively limits the size of recursively generated code fragments.
if probability(0.25) {
return
}
}
}
/// Generates random code at the current position.
///
/// Code generation involves executing the configured code generators as well as splicing code from other
/// programs in the corpus into the current one.
public func generate(n: Int = 1) {
currentCodegenBudget = n
while currentCodegenBudget > 0 {
generateInternal()
}
}
/// Called by a code generator to generate more additional code, for example inside a newly created block.
public func generateRecursive() {
// Generate at least one instruction, even if already below budget
if currentCodegenBudget <= 0 {
currentCodegenBudget = 1
}
generateInternal()
}
//
// Variable reuse APIs.
//
// These attempt to find an existing variable containing the desired value.
// If none exist, a new instruction is emitted to create it.
//
// This is generally an O(n) operation in the number of currently visible
// varialbes (~= current size of program). This should be fine since it is
// not too frequently used. Also, this way of implementing it keeps the
// overhead in internalAppend to a minimum, which is probably more important.
public func reuseOrLoadBuiltin(_ name: String) -> Variable {
for v in scopeAnalyzer.visibleVariables {
if let builtin = loadedBuiltins[v], builtin == name {
return v
}
}
return loadBuiltin(name)
}
public func reuseOrLoadInt(_ value: Int64) -> Variable {
for v in scopeAnalyzer.visibleVariables {
if let val = loadedIntegers[v], val == value {
return v
}
}
return loadInt(value)
}
public func reuseOrLoadAnyInt() -> Variable {
// This isn't guaranteed to succeed, but that's probably fine.
let val = seenIntegers.randomElement() ?? genInt()
return reuseOrLoadInt(val)
}
public func reuseOrLoadFloat(_ value: Double) -> Variable {
for v in scopeAnalyzer.visibleVariables {
if let val = loadedFloats[v], val == value {
return v
}
}
return loadFloat(value)
}
public func reuseOrLoadAnyFloat() -> Variable {
let val = seenFloats.randomElement() ?? genFloat()
return reuseOrLoadFloat(val)
}
//
// Low-level instruction constructors.
//
// These create an instruction with the provided values and append it to the program at the current position.
// If the instruction produces a new variable, that variable is returned to the caller.
// Each class implementing the Operation protocol will have a constructor here.
//
@discardableResult
private func emit(_ op: Operation, withInputs inputs: [Variable] = []) -> Instruction {