-
Notifications
You must be signed in to change notification settings - Fork 0
/
pysyn.py
2069 lines (1597 loc) · 65.8 KB
/
pysyn.py
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
#!/usr/bin/env python
import ast
import copy
import inspect
import logging
import re
import sys
import z3
from os import path
import threading
logging.basicConfig(level = logging.WARN)
ABORT_TIMEOUT=10 ##!!! Set to higher level later on
WITH_HYPO = True
class FunctionLoader(object):
"""
Offers functionality to load functions ('f' & 'f_inv') as ast trees
"""
def __init__(self, p):
assert path.isfile(p)
self.path = p
# they are used for lazy initialization
self.source = None
self.ast = None
def has_f(self):
p = self.get_ast()
for node in p.body:
if FunctionLoader.is_f(node):
return True
return False
def has_template(self):
p = self.get_ast()
for node in p.body:
if FunctionLoader.is_template(node):
return True
return False
def get_source(self):
if self.source == None:
self.source = read_file_to_string(self.path)
return self.source
def get_ast(self):
if self.ast == None:
self.ast = ast.parse(self.get_source())
return self.ast
def get_f(self):
p = self.get_ast()
for node in p.body:
if FunctionLoader.is_f(node):
return node
def get_template(self):
assert self.has_template()
p = self.get_ast()
for node in p.body:
if FunctionLoader.is_template(node):
return node
@classmethod
def is_f(cls, ast):
return cls.is_function(ast, "f")
@classmethod
def is_template(cls, ast):
return cls.is_function(ast, "f_inv")
@classmethod
def is_function(cls, ast, name):
return type(ast).__name__ == "FunctionDef" and ast.name == name
class PathRaises(Exception):
"""
Denotes that a path will raise an exception and is therefore no longer worth
exploring.
"""
pass
class GiveUp(Exception):
"""
Denotes that the FunctionAnalyzer should give up analyzing a function.
This may be raised if an irreversible path was found while analyzing
for the 'syn' command, then it's no longer worth exploring other paths.
"""
pass
class FunctionAnalyzer:
"""
Creates Path objects for a function
"""
def __init__(self, f):
self.f = f
# fetch parameters
self.input = map(lambda p: z3.Int(p.id), f.args.args)
self.input_names = set(map(lambda p: p.id, f.args.args))
self.output = None
self.solver = z3.Solver()
# initialize argument constraint: x in [1000, -1000]
self.solver.add(z3.And(*[p >= -1000 for p in self.input]))
self.solver.add(z3.And(*[p <= 1000 for p in self.input]))
# add parameters to store
self.store = dict(zip(map(str, self.input), self.input))
self.paths = []
self.reachable = z3.sat
self.return_size = -1
self.is_irreversible = False
self.migh_be_irreversible = False
self.irreversible_path_constraints = []
def analyze(self, give_up_on_irreversible_path = False):
self.give_up_on_irreversible_path = give_up_on_irreversible_path
try:
self.explore_path(self.f.body)
except GiveUp:
pass
def check_return_size(self, size):
if self.return_size != -1 and self.return_size != size:
raise Exception("Function is not part of the valid python subset due to unequal size of return tuples!")
else:
self.return_size = size
def update_reachable(self):
self.reachable = self.solver.check()
def quick_check(self, *constraints):
self.solver.push()
self.solver.add(constraints)
result = self.solver.check()
self.solver.pop()
return result
def block(self, block):
if len(block) > 0:
self.statement(block[0], block[1:])
else:
if self.reachable == z3.sat:
# path that doesn't end with a return statement!
raise Exception("Function is not part of the valid python subset due to a missing return!")
elif self.reachable == z3.unknown:
# if we don't know whether a path is reachable
# but it doesn't end with a return statement, we will assume
# that it's not reachable, because it's clearly specified
# that we're working with a python subset where every path
# contains at least one return statement.
pass
else:
assert(False)
def statement(self, stmt, block):
if type(stmt).__name__ == 'Return':
self._return(stmt, block)
elif type(stmt).__name__ == 'If':
self._if(stmt, block)
elif type(stmt).__name__ == 'Assign':
self._assign(stmt, block)
else:
raise Exception('Invalid statement: ' + ast.dump(stmt))
def _return(self, _return, block):
expr = self.expression(_return.value)
if isinstance(expr, tuple):
self.check_return_size(len(expr))
output = list(expr)
else:
self.check_return_size(1)
output = [expr]
relation = []
# initialize output variables if necessary
if self.output == None:
self.output = []
for i in xrange(len(output)):
outname = "y" + str(i + 1)
# avoid collisions with existing variables
while outname in self.input_names:
outname = "__" + outname
outvariable = z3.Int(outname)
self.output.append(outvariable)
for i in xrange(len(output)):
relation.append(self.output[i] == output[i])
path = Path(self.input, self.output, self.solver.assertions(), relation)
self.paths.append(path)
def _if(self, _if, block):
# create check point
self.solver.push()
store = self.store.copy()
reachable = self.reachable
# fetch condition
test = self.expression(_if.test)
# handle true branch
self.solver.add(test)
self.update_reachable()
# explore true branch
if self.reachable == z3.sat or self.reachable == z3.unknown:
self.explore_path(_if.body + block)
# reset back to checkpoint
self.solver.pop()
self.store = store
self.reachable = reachable
# handle false branch
self.solver.push()
self.solver.add(z3.Not(test))
self.update_reachable()
# explore false branch
if self.reachable == z3.sat or self.reachable == z3.unknown:
if not _if.orelse:
self.explore_path(block)
else:
self.explore_path(_if.orelse + block)
self.solver.pop()
def explore_path(self, block):
try:
self.block(block)
except PathRaises:
self.irreversible_path_constraints.append(list(self.solver.assertions()))
if self.reachable == z3.sat:
self.is_irreversible = True
if self.give_up_on_irreversible_path:
raise GiveUp()
elif self.reachable == z3.unknown:
self.migh_be_irreversible = True
else:
assert(False)
def _assign(self, assign, block):
assert(len(assign.targets) == 1) # Disallow a = b = c syntax
target = self.assignable_expression(assign.targets[0])
value = self.expression(assign.value)
target_is_tuple = isinstance(target, tuple)
value_is_tuple = isinstance(value, tuple)
if target_is_tuple and value_is_tuple:
if len(value) != len(target):
# unequal size of tuples!
raise PathRaises()
for v, t in zip(value, target):
self.store[t] = v
elif not target_is_tuple and not target_is_tuple:
self.store[target] = value
else:
# assignment of target and value have different types!
raise PathRaises()
self.block(block)
def assignable_expression(self, expr):
if type(expr).__name__ == 'Name':
return expr.id
if type(expr).__name__ == 'Tuple':
return tuple(map(self.assignable_expression, expr.elts))
raise Exception("Tried to assign to non-assignable expression! " + ast.dump(expr))
def expression(self, expr):
if type(expr).__name__ == 'Tuple':
return tuple(map(self.expression, expr.elts))
if type(expr).__name__ == 'Name':
if self.store.has_key(expr.id):
return self.store[expr.id]
# variable doesn't exist, will raise a ValueError!
raise PathRaises()
if type(expr).__name__ == 'Num':
return expr.n
if type(expr).__name__ == 'BinOp':
left = self.expression(expr.left)
right = self.expression(expr.right)
if type(expr.op).__name__ == 'Add':
return left + right
if type(expr.op).__name__ == 'Sub':
return left - right
if type(expr.op).__name__ == 'Mult':
return left*right
if type(expr.op).__name__ == 'Div':
# for some reasons it seems that add with check seems to produce
# better results than check with assumptions
# can x be non-zero?
non_zero = self.quick_check(right != 0)
if non_zero == z3.sat or non_zero == z3.unknown:
# check for division by zero
division_by_zero = self.quick_check(right == 0)
# handle potential division by zero
if division_by_zero == z3.sat:
constraint = list(self.solver.assertions())
constraint.append(right == 0)
self.irreversible_path_constraints.append(constraint)
self.is_irreversible = True
if self.give_up_on_irreversible_path:
raise GiveUp()
elif division_by_zero == z3.unknown:
constraint = list(self.solver.assertions())
constraint.append(right == 0)
self.irreversible_path_constraints.append(constraint)
self.migh_be_irreversible = True
else:
# x can't be 0, so everything's good
pass
# continue with assumption that x != 0
self.solver.add(right != 0)
self.reachable = non_zero
return left/right
else:
# x can't be non-zero
raise PathRaises
if type(expr).__name__ == 'UnaryOp':
operand = self.expression(expr.operand)
if type(expr.op).__name__ == 'Not':
return z3.Not(operand)
if type(expr.op).__name__ == 'USub':
return -operand
if type(expr.op).__name__ == 'UAdd':
return operand
if type(expr).__name__ == 'Compare':
assert(len(expr.ops) == 1) # Do not allow for x == y == 0 syntax
assert(len(expr.comparators) == 1)
left = self.expression(expr.left)
right = self.expression(expr.comparators[0])
op = expr.ops[0]
if type(op).__name__ == 'Eq':
return left == right
if type(op).__name__ == 'NotEq':
return left != right
if type(op).__name__ == 'Gt':
return left > right
if type(op).__name__ == 'GtE':
return left >= right
if type(op).__name__ == 'Lt':
return left < right
if type(op).__name__ == 'LtE':
return left <= right
if type(expr).__name__ == 'BoolOp':
operands = expr.values
if type(expr.op).__name__ == 'And':
real_operands = []
for operand in operands:
operand = self.expression(operand)
real_operands.append(operand)
if self.quick_check(*real_operands) == z3.unsat:
# we could prove that the operands are false
# so therefore due to python's short-circuit and operator
# the remaining operands don't need to be evaluated
# anymore
break
return z3.And(*real_operands)
if type(expr.op).__name__ == 'Or':
real_operands = []
for operand in operands:
operand = self.expression(operand)
real_operands.append(operand)
if self.quick_check(z3.Not(z3.Or(*real_operands))) == z3.unsat:
# we could prove that the operands cannot be false
# thus the operands are always true
# so therefore with python's short-circuit or operator
# the remaining operands don't need to be evaluated
# anymore
break
return z3.Or(*real_operands)
raise Exception('Invalid expression: ' + ast.dump(expr))
class Path:
"""
Entity class that represents a path
"""
def __init__(self, input, output, constraints, relation):
assert isinstance(input, list)
assert isinstance(output, list)
assert isinstance(relation, list)
self.input = input
self.output = output
self.constraints = constraints
self.relation = relation
class PathDataGenerator:
"""
Generates input/output samples for a given path
"""
def __init__(self, path):
self.path = path
self.solver = z3.Solver()
self.solver.add(path.constraints)
self.solver.add(path.relation)
self.solver.push()
self.stack_size = 0
def another(self):
sat = self.solver.check()
if sat != z3.sat:
return None
model = self.solver.model()
in_vector = [model[x].as_long() for x in self.path.input]
out_vector = [model[y].as_long() for y in self.path.output]
# make sure we don't generate the same sample twice
self.solver.add(z3.Not(z3.And(*[ x == model[x] for x in self.path.input])))
self.solver.add(z3.Not(z3.And(*[ y == model[y] for y in self.path.output])))
self.solver.push()
self.stack_size += 1
return (in_vector, out_vector)
def take(self, num):
v = []
for i in xrange(num):
d = self.another()
if d == None:
return v
v.append(d)
return v
def reset(self):
while self.stack_size > 0:
self.solver.pop()
self.stack_size -= 1
class DiversePathDataGenerator:
"""
Generates input/output samples with a strong emphasize on diversity
"""
def __init__(self, path):
self.path = path
self.solver = z3.Solver()
self.solver.add(path.constraints)
self.solver.add(path.relation)
self.solver.push()
def generate_one(self):
# try to find one
if self.solver.check() != z3.sat:
return None, None
# extract solution
model = self.solver.model()
x_vec = [ model[x] for x in self.path.input ]
y_vec = [ model[y] for y in self.path.output ]
if None in x_vec or None in y_vec:
return None, None
x_vec = [ x.as_long() for x in x_vec]
y_vec = [ y.as_long() for y in y_vec]
return [y_vec, x_vec]
def generate_k_for_dimension(self, k, d, avoid = []):
assert(d < len(self.path.input))
self.solver.push()
# make sure we get a new value for the given dimension d
self.solver.add([ self.path.input[d] != x[d] for x in avoid ])
xs = []
ys = []
for i in xrange(k):
y, x = self.generate_one()
if x is None or y is None:
break
xs.append(x)
ys.append(y)
self.solver.add([ self.path.input[d] != x[d] ])
self.solver.pop()
return ys, xs
def generate_k_per_dimension(self, k):
xs = []
ys = []
for d in range(len(self.path.input)):
_ys, _xs = self.generate_k_for_dimension(k, d, xs)
xs += _xs
ys += _ys
return ys, xs
def generate_k_different(self, k, avoid = []):
self.solver.push()
for x in avoid:
self.solver.add(z3.Not(z3.And(*[ self.path.input[d] == x[d] for d in xrange(len(self.path.input)) ])))
xs = []
ys = []
for i in xrange(k):
y, x = self.generate_one()
if x is None or y is None:
break
xs.append(x)
ys.append(y)
self.solver.add(z3.Not(z3.And(*[ self.path.input[d] == x[d] for d in xrange(len(self.path.input)) ])))
self.solver.pop()
return ys, xs
def generate(self, k):
ys, xs = self.generate_k_per_dimension(k)
_ys, _xs = self.generate_k_different(k, xs)
ys += _ys
xs += _xs
out = []
for y, x in zip(ys, xs):
out.append([y, x])
return out
class ExecutionPath:
"""
Represents the conditions for one execution path.
"""
def __init__(self):
# List of conditions, each representing one branch decision
self.cond = []
# bit pattern of the current branch:
# reference ID of the if statement is the bit number (e.g. refId 2 --> bit 2 --> bitmask 4 (start bit count at 0)
self.branchBits = 0
# To remember which branches we actually encountered, set corresponding bit
# --> Allows later on to sort out duplicate path settings (i.e. with bits set that were not encountered in exec
self.maskBits = 0
def addBranch(self, ref, selection, cond_in):
"""
Adds a branch decision made at an if statement
* ref: the reference id for the if
* selection: the (forced) result of the condition (1 --> take if, 0 --> take else)
* cond_in: the actual condition (usually z3 expression)
"""
b = 1 <<ref;
# In case we're evaluating mixed data, we may arrive here with only an int or bool value
# --> Make sure to convert it into a boolean so z3 does not choke on it
if not z3.is_expr(cond_in):
cond_in = bool(cond_in)
cond = cond_in
# If we're not in the if branch, negate condition
if not selection:
cond = z3.Not(cond_in)
self.cond.append(cond)
if self.maskBits & b:
raise "same branch encountered twice: {0}".format(ref)
self.maskBits |= b
self.branchBits |= (selection&1) <<ref
def samePath(self, otherPath):
# It's the same path if we went through the same if statements (maskBits)
# ... and took the same branch for all these (branchBits)
return otherPath.maskBits == self.maskBits and otherPath.branchBits&otherPath.maskBits == self.branchBits&self.maskBits
@property
def pathCondition(self):
"""Return the path condition as z3 expression"""
if len(self.cond) == 0:
return True
else:
return z3.And(*self.cond)
class PathLog:
"""Keeps track of paths already encountered"""
def __init__(self):
self.paths = []
def addPath(self, path):
"""If not yet in paths, adds the path. Returns if the passed path has been added"""
for p in self.paths:
if p.samePath(path):
return False
self.paths.append(path)
return True
def compile_ast(f):
"""
Compiles a function in ast form and returns it.
Once returned the function can be called just like any other python function
"""
assert(f.__class__.__name__ == "FunctionDef")
ast.fix_missing_locations(f)
m = ast.Module([f])
compiled = compile(m, "<pysyn.compile_ast>", "exec")
scope = {}
exec compiled in scope
return scope[f.name]
class FunctionExecutor:
"""
Compiles a given ast tree and provides functionality to execute an indicated function
"""
def __init__(self, astTree, fname, global_vars = {}):
"""
* ast tree : tree to parse (containing one or more func decls)
* fname : function name to use in call()
* global_vars: additional global variables the compilation
"""
self.funcName = fname
self.globalVars = global_vars
self.tree = astTree
#print ast.dump(tree.body[0])
ast.fix_missing_locations(astTree)
#unparse.Unparser(astTree)
comp = compile(astTree, "<no >", "exec")
self.localVars = {}
exec(comp, global_vars, self.localVars)
self.spec = inspect.getargspec(self.localVars[fname])
self.func = self.localVars[fname]
def call(self, *args):
"""Calls the function"""
res = self.func.__call__(*args)
return res
def genData(self, inData):
"""
Generates output data from input by calling the given function multiple times
inData: list of list: e.g.: [[run1_arg1, run1_arg2], [run2_arg1, run2_arg2]]
returns list of list of list:
e.g. [
[[run1_arg1, run1_arg2], [run1_out1, run1_out2],
[[run2_arg1, run2_arg2], [run2_out1, run2_out2],
]
Executions resulting in exceptions are skipped in the output
"""
outData = []
for dt in inData:
try:
res = self.call(*dt)
except:
# Maybe add logging here
continue
if isinstance(res, tuple):
res = list(res)
else:
res = [res]
outData.append([dt, res])
return outData
class InstrumentedExecutor(FunctionExecutor):
"""
Utility class for execution after instrumentation. To be bound to global variable "cond_context".
Upon execution of the instrumented function forces execution along a predefined path and captures
the conditions passed to the wrap_condition(). While
Can be switched to next path using nextPath()
"""
def __init__(self, astTree, fname = 'f'):
self.tree = copy.deepcopy(astTree)
vv = InstrumentingVisitor()
self.visitor = vv
vv.visit(find_function(self.tree, fname))
# Pass the cond_context down to parent class so the instrumented ast tree will compile
FunctionExecutor.__init__(self, self.tree, fname, {"cond_context":self})
# choice is the bit pattern for the current branching path (ref id in wrap_call corresponds to bit number)
# Start with recognizable value --> need call to nextPath() to be ready for func calls
# nextPath() always increments choice, therefore walking through all branches
self.choice = -1
# where to stop iterating with next Path... set to the first unused bit (i.e. 1 bit above the biggest branch ref id)
self.maxChoice = 1 << vv.refLength
# Only enable during call()
self._currentPath = None
self._extraCond = None
def call(self, *args):
"""Executes a function with instrumentation, witout keeping the path setting. Only returns the result of the func"""
if(self.choice == -1):
raise "can only call after first use of nextPath()"
self._currentPath = ExecutionPath()
res = FunctionExecutor.call(self, *args)
self._currentPath = None
return res
def callExt(self, *args):
"""Executes a function with instrumentation, returns return values and path object"""
if(self.choice == -1):
raise "can only call after first use of nextPath()"
self._currentPath = ExecutionPath()
self._extraCond = []
res = None
try:
res = FunctionExecutor.call(self, *args)
finally:
pth = self._currentPath
extraCond = self._extraCond
self._currentPath = None
self._extraCond = None
return (res, pth, extraCond)
def wrap_condition(self, ref, cond_in, outer):
"""Called from within the instrumented code, at each if condition"""
rv = (self.choice >> ref) & 1
self._currentPath.addBranch(ref, rv, cond_in)
return rv;
def nonZero(self, e):
if(z3.is_expr(e)):
self._extraCond.append(e != 0)
elif e == 0:
self._extraCond.append(False)
return e
def nextPath(self):
"""
Advance to next path
NOTE: as the path choice is iterating through all combinations of branching decisions,
some combinations may be redundant as the changed branching decisions are not executed (outer if set differently)
use PathLog.addPath() or ExecutionPath.samePath() to distinguish
"""
self.choice = self.choice + 1
return self.choice < self.maxChoice
def resetPath(self):
self.choice = -1
# expects global var cond_context: class with methods
# instrument(self, refNo, marker[[e.g. if endif else endelse]])
# wrap_condition(self, refNo, condition, refToOuterIf)
#
# Use instance.visit(astTree) to start adding instrumentation
#
class InstrumentingVisitor(ast.NodeTransformer):
"""
AST Node transformer that inserts instrumentation into the tree.
* All instrumentation is implemented as method call on variable "cond_context".
* If conditions are wrapped by "cond_context.wrap_condition(<<ReferenceId>>, <<original condition>>, <<OuterIfId>>)
* ReferenceId: Each wrapped condition is associated with an id (counting upward from 0).
* original condition: AST tree of the original condition
* OuterIfID: In case of nested ifs: The ReferenceID of the next ancestor IF in the tree
* Additionally transforms unknown_int and unknown_choice into a method call and adds reference IDs:
--> cond_context.unknown_choice(<<ReferenceId>>, <<original args>>)
--> cond_context.unknown_int(<<ReferenceId>>
TODOS:
* Currently same reference ID or even same class for unknowns and if instrumentation --> separate
"""
def __init__(self):
self.refCnt = 0
self.refCntUnknowns = 0
self.outer = -1
self._unknowns = {}
self.unknown_choice_max = {}
ctx_var = ast.Name(id = 'cond_context', ctx = ast.Load())
@property
def refLength(self):
"""Contains the last ReferenceId used for IFs +1 (array length semantics)"""
return self.refCnt
@property
def unknowns(self):
"""returns a map unknownId --> corresponding Call node in the AST tree"""
return self._unknowns
def gen_wrap_call(self, t):
"""Generate the condition wrapper call. t is the AST expression tree for the conditional"""
func = ast.Attribute(value = InstrumentingVisitor.ctx_var, attr='wrap_condition', ctx = ast.Load())
return ast.Call(func = func, args = [ast.Num(n = self.refCnt), t, ast.Num(n=self.outer)], keywords=[])
def generic_visit(self, node):
"""
Override the visitor's generic method to find If conditions and Calls in the tree
TODO: better override visit_If and visit_Call instead.
"""
#print ast.dump(node)
# keep track of nested IFs
prevOuter = self.outer
if node.__class__.__name__ == 'BinOp' and node.op.__class__.__name__ == "Div":
if node.right.__class__.__name__ != 'Call' or node.right.func.__class__.__name__ != 'Attribute' or node.right.func.attr != 'nonZero':
fname = ast.Attribute(value = InstrumentingVisitor.ctx_var, attr="nonZero", ctx = ast.Load())
node.right = ast.Call(func = fname, args=[node.right], keywords=[])
elif node.__class__.__name__ == 'Call' and node.func.__class__.__name__ == 'Name':
if node.func.id == 'unknown_int':
node.func = ast.Attribute(value = InstrumentingVisitor.ctx_var, attr="unknown_int", ctx= ast.Load())
node.args.insert(0, ast.Num(n = self.refCntUnknowns))
self._unknowns[self.refCntUnknowns] = node
self.refCntUnknowns += 1
elif node.func.id == 'unknown_choice':
node.func = ast.Attribute(value = InstrumentingVisitor.ctx_var, attr="unknown_choice", ctx= ast.Load())
maxch = len(node.args)
node.args.insert(0, ast.Num(n = self.refCntUnknowns))
self._unknowns[self.refCntUnknowns] = node
self.unknown_choice_max[self.refCntUnknowns] = maxch
self.refCntUnknowns += 1
elif node.__class__.__name__ == 'If' :
#print ast.dump(node.test)
t = node.test
node.test = self.gen_wrap_call(t)
self.outer = self.refCnt
self.refCnt = self.refCnt + 1
#print node.__class__.__name__
# Go through all children... original method would do this already.
for c in ast.iter_child_nodes(node):
self.visit(c)
# keep track of nested IFs
self.outer = prevOuter
return node
class TemplateTransformer(ast.NodeTransformer):
"""
Replaces unknown_int and unknown_choice with the supplied values
Requires that the visited AST tree has been instrumented (using InstrumentingVisitor) as the
replacements are matched by ReferenceId.
"""
def __init__(self, unknown_vars, unknown_choices):
"""
Constructor. Requires two maps to replace unknown_ints and unknown_choices:
* unknown_ints: ReferenceId -> integer literal to replace with
* unknwon_choice: ReferenceId -> argument of the function to substitute the call with
e.g. cond_context.unknown_choice(4, v0, v1, v2) ( {4:1} ) --> replace by "v1" in AST
"""
self.unknown_vars = unknown_vars
self.unknown_choices = unknown_choices
def visit_Call(self, node):
"""
called from generic_visitor during visit for all calls. only reacts on unknown_... methods
"""
rv = node
if not node.func.__class__.__name__=='Attribute':
return node
if self.unknown_vars is not None and node.func.attr =='unknown_int':
ref = node.args[0].n
if not self.unknown_vars.has_key(ref):
val=99999
#raise Exception("trying to replace unknown_int with ref {0}. Solution not supplied: {1}".format(ref, self.unknown_vars))
# Substitute with whatever value... Wasn't considered in the training data
else:
val = self.unknown_vars[ref]
rv = ast.Num(n = val)
elif self.unknown_choices is not None and node.func.attr =='unknown_choice':
ref = node.args[0].n
if not self.unknown_choices.has_key(ref):
sel=0
#raise "trying to replace unknown_choice with ref {0}. Solution not supplied".format(ref)
# Substitute with whatever value... Wasn't considered in the training data
else: