-
Notifications
You must be signed in to change notification settings - Fork 49
/
builtinslib.py
4908 lines (4122 loc) · 161 KB
/
builtinslib.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
import codecs
import collections
import copy
import enum
import io
import math
import operator as ops
import re
import string
import sys
import typing
from abc import ABCMeta
from array import array
from dataclasses import dataclass
from functools import wraps
from itertools import zip_longest
from numbers import Integral, Number, Real
from sys import maxunicode
from typing import (
Any,
BinaryIO,
ByteString,
Callable,
Dict,
FrozenSet,
Hashable,
Iterable,
List,
NamedTuple,
NoReturn,
Optional,
Sequence,
Set,
SupportsAbs,
SupportsBytes,
SupportsComplex,
SupportsFloat,
SupportsInt,
SupportsRound,
TextIO,
Tuple,
Type,
TypeVar,
Union,
cast,
get_type_hints,
)
import typing_inspect # type: ignore
import z3 # type: ignore
from crosshair.abcstring import AbcString
from crosshair.core import (
CrossHairValue,
SymbolicFactory,
deep_realize,
iter_types,
normalize_pytype,
proxy_for_type,
python_type,
realize,
register_patch,
register_type,
with_realized_args,
with_symbolic_self,
with_uniform_probabilities,
)
from crosshair.objectproxy import ObjectProxy
from crosshair.simplestructs import (
SequenceConcatenation,
SetBase,
ShellMutableMap,
ShellMutableSequence,
ShellMutableSet,
SimpleDict,
SliceView,
compose_slices,
concatenate_sequences,
)
from crosshair.statespace import (
HeapRef,
SnapshotRef,
StateSpace,
VerificationStatus,
context_statespace,
optional_context_statespace,
prefer_true,
)
from crosshair.tracers import (
NoTracing,
ResumedTracing,
Untracable,
is_tracing,
tracing_iter,
)
from crosshair.type_repo import PYTYPE_SORT, SymbolicTypeRepository
from crosshair.unicode_categories import UnicodeMaskCache
from crosshair.util import (
ATOMIC_IMMUTABLE_TYPES,
CrosshairInternal,
CrosshairUnsupported,
IgnoreAttempt,
debug,
is_hashable,
is_iterable,
memo,
name_of_type,
smtlib_typename,
test_stack,
type_arg_of,
)
from crosshair.z3util import z3And, z3Eq, z3Ge, z3Gt, z3IntVal, z3Or
_T = TypeVar("_T")
_VT = TypeVar("_VT")
class _Missing(enum.Enum):
value = 0
_LIST_INDEX_START_DEFAULT = 0
_LIST_INDEX_STOP_DEFAULT = 9223372036854775807
_MISSING = _Missing.value
NoneType = type(None)
def smt_min(x, y):
if x is y:
return x
return z3.If(x <= y, x, y)
def smt_and(a: bool, b: bool) -> bool:
with NoTracing():
if isinstance(a, SymbolicBool) and isinstance(b, SymbolicBool):
return SymbolicBool(z3.And(a.var, b.var))
return a and b
def smt_or(a: bool, b: bool) -> bool:
with NoTracing():
if isinstance(a, SymbolicBool) and isinstance(b, SymbolicBool):
return SymbolicBool(z3.Or(a.var, b.var))
return a or b
def smt_not(x: object) -> Union[bool, "SymbolicBool"]:
with NoTracing():
if isinstance(x, SymbolicBool):
return SymbolicBool(z3.Not(x.var))
return not x
_NONHEAP_PYTYPES = set([int, float, bool, NoneType, complex])
# TODO: isn't this pretty close to isinstance(typ, AtomicSymbolicValue)?
def pytype_uses_heap(typ: Type) -> bool:
return not (typ in _NONHEAP_PYTYPES)
def typeable_value(val: object) -> object:
"""
Foces values of unknown type (SymbolicObject) into a typed (but possibly still symbolic) value.
"""
while type(val) is SymbolicObject:
val = cast(SymbolicObject, val)._wrapped()
return val
_SMT_INT_SORT = z3.IntSort()
_SMT_BOOL_SORT = z3.BoolSort()
_SMT_FLOAT_SORT = z3.RealSort() # difficulty getting the solver to use z3.Float64()
@memo
def possibly_missing_sort(sort):
datatype = z3.Datatype("optional_" + str(sort) + "_")
datatype.declare("missing")
datatype.declare("present", ("valueat", sort))
ret = datatype.create()
return ret
_MAYBE_HEAPREF = possibly_missing_sort(HeapRef)
def is_heapref_sort(sort: z3.SortRef) -> bool:
return sort == HeapRef or sort == _MAYBE_HEAPREF
SymbolicGenerator = Callable[[Union[str, z3.ExprRef], type], object]
def origin_of(typ: Type) -> Type:
typ = _WRAPPER_TYPE_TO_PYTYPE.get(typ, typ) # TODO is the still required?
if hasattr(typ, "__origin__"):
return typ.__origin__
return typ
# TODO: refactor away casting in SMT-sapce:
def smt_int_to_float(a: z3.ExprRef) -> z3.ExprRef:
if _SMT_FLOAT_SORT == z3.Float64():
return z3.fpRealToFP(z3.RNE(), z3.ToReal(a), _SMT_FLOAT_SORT)
elif _SMT_FLOAT_SORT == z3.RealSort():
return z3.ToReal(a)
else:
raise CrosshairInternal()
def smt_bool_to_float(a: z3.ExprRef) -> z3.ExprRef:
if _SMT_FLOAT_SORT == z3.Float64():
return z3.If(a, z3.FPVal(1.0, _SMT_FLOAT_SORT), z3.FPVal(0.0, _SMT_FLOAT_SORT))
elif _SMT_FLOAT_SORT == z3.RealSort():
return z3.If(a, z3.RealVal(1), z3.RealVal(0))
else:
raise CrosshairInternal()
def smt_coerce(val: Any) -> z3.ExprRef:
if isinstance(val, SymbolicValue):
return val.var
return val
def invoke_dunder(obj: object, method_name: str, *args, **kwargs):
"""
Invoke a special method in the same way Python does.
Emulates how Python calls special methods, avoiding:
(1) methods directly set on the instance, and
(2) normal attribute resolution logic (descriptors, etc)
See https://docs.python.org/3/reference/datamodel.html#special-method-lookup
"""
method = _MISSING
with NoTracing():
mro = type.__dict__["__mro__"].__get__(type(obj)) # type: ignore
for klass in mro:
method = klass.__dict__.get(method_name, _MISSING)
if method is not _MISSING:
break
if method is _MISSING:
return _MISSING
return method(obj, *args, **kwargs)
class SymbolicValue(CrossHairValue):
def __init__(self, smtvar: Union[str, z3.ExprRef], typ: Type):
if is_tracing():
raise CrosshairInternal
self.snapshot = SnapshotRef(-1)
self.python_type = typ
if type(smtvar) is str:
self.var = self.__init_var__(typ, smtvar)
else:
self.var = smtvar
# TODO test that smtvar's sort matches expected?
def __init_var__(self, typ, varname):
raise CrosshairInternal(f"__init_var__ not implemented in {type(self)}")
def __deepcopy__(self, memo):
result = copy.copy(self)
result.snapshot = context_statespace().current_snapshot()
memo[id(self)] = result
return result
def __bool__(self):
return NotImplemented
# TODO: do we need these comparison rejections?:
def __lt__(self, other):
raise TypeError
def __gt__(self, other):
raise TypeError
def __le__(self, other):
raise TypeError
def __ge__(self, other):
raise TypeError
def __add__(self, other):
raise TypeError
def __sub__(self, other):
raise TypeError
def __mul__(self, other):
raise TypeError
def __pow__(self, other, mod=None):
raise TypeError
def __truediv__(self, other):
return numeric_binop(ops.truediv, self, other)
def __floordiv__(self, other):
raise TypeError
def __mod__(self, other):
raise TypeError
def __ch_pytype__(self):
return self.python_type
def _unary_op(self, op):
with NoTracing():
return self.__class__(op(self.var), self.python_type)
class AtomicSymbolicValue(SymbolicValue):
def __init_var__(self, typ, varname):
if is_tracing():
raise CrosshairInternal("Tracing while creating symbolic")
z3type = self.__class__._ch_smt_sort()
return z3.Const(varname, z3type)
def __ch_is_deeply_immutable__(self) -> bool:
return True
@classmethod
def _ch_smt_sort(cls) -> z3.SortRef:
raise CrosshairInternal(f"_ch_smt_sort not implemented in {cls}")
@classmethod
def _pytype(cls) -> Type:
raise CrosshairInternal(f"_pytype not implemented in {cls}")
@classmethod
def _smt_promote_literal(cls, val: object) -> Optional[z3.SortRef]:
raise CrosshairInternal(f"_smt_promote_literal not implemented in {cls}")
@classmethod
def _coerce_to_smt_sort(cls, input_value: Any) -> Optional[z3.ExprRef]:
if is_tracing():
raise CrosshairInternal("_coerce_to_smt_sort called while tracing")
input_value = typeable_value(input_value)
target_pytype = cls._pytype()
# check the likely cases first
if isinstance(input_value, cls):
return input_value.var
elif isinstance(input_value, target_pytype):
return cls._smt_promote_literal(input_value)
# see whether we can safely cast and retry
if isinstance(input_value, Number) and issubclass(cls, Number):
casting_fn_name = "__" + target_pytype.__name__ + "__"
caster = getattr(input_value, casting_fn_name, None)
if not caster:
return None
try:
converted = caster()
except TypeError:
return None
return cls._coerce_to_smt_sort(converted)
return None
def __eq__(self, other):
with NoTracing():
coerced = type(self)._coerce_to_smt_sort(other)
if coerced is None:
return False
return SymbolicBool(self.var == coerced)
def __ne__(self, other):
with NoTracing():
coerced = type(self)._coerce_to_smt_sort(other)
if coerced is None:
return True
return SymbolicBool(self.var != coerced)
_PYTYPE_TO_WRAPPER_TYPE: Dict[
type, Tuple[Type[AtomicSymbolicValue], ...]
] = {} # to be populated later
_WRAPPER_TYPE_TO_PYTYPE: Dict[SymbolicGenerator, type] = {}
def crosshair_types_for_python_type(typ: Type) -> Tuple[Type[AtomicSymbolicValue], ...]:
typ = normalize_pytype(typ)
origin = origin_of(typ)
return _PYTYPE_TO_WRAPPER_TYPE.get(origin, ())
def smt_to_ch_value(
space: StateSpace, snapshot: SnapshotRef, smt_val: z3.ExprRef, pytype: type
) -> object:
def proxy_generator(typ: Type) -> object:
return proxy_for_type(
typ, smtlib_typename(typ) + "_inheap" + space.uniq(), allow_subtypes=True
)
if smt_val.sort() == HeapRef:
return space.find_key_in_heap(smt_val, pytype, proxy_generator, snapshot)
ch_type = crosshair_types_for_python_type(pytype)
assert ch_type
return ch_type[0](smt_val, pytype)
def force_to_smt_sort(
input_value: Any, desired_ch_type: Type[AtomicSymbolicValue]
) -> z3.ExprRef:
with NoTracing():
ret = desired_ch_type._coerce_to_smt_sort(input_value)
if ret is None:
raise TypeError
return ret
# The Python numeric tower is (at least to me) fairly confusing.
# A summary here, with some example implementations:
#
# Number
# |
# Complex
# | \- complex
# Real
# | \- float
# Rational
# | \- Fraction
# Integral
# |
# int
# |
# bool (yes, bool is a subtype of int!)
#
TypePair = Tuple[type, type]
BinFn = Callable[[Any, Any], Any]
OpHandler = Union[_Missing, Callable[[BinFn, Number, Number], Number]]
_BIN_OPS: Dict[Tuple[BinFn, type, type], OpHandler] = {}
_BIN_OPS_SEARCH_ORDER: List[Tuple[BinFn, type, type, OpHandler]] = []
@dataclass
class KindedFloat:
val: float
class FiniteFloat(KindedFloat):
pass
class NonFiniteFloat(KindedFloat):
pass
def numeric_binop(op: BinFn, a: Number, b: Number):
if not is_tracing():
raise CrosshairInternal("Numeric operation on symbolic while not tracing")
with NoTracing():
return numeric_binop_internal(op, a, b)
def numeric_binop_internal(op: BinFn, a: Number, b: Number):
a_type, b_type = type(a), type(b)
binfn = _BIN_OPS.get((op, a_type, b_type))
if binfn is None:
for curop, cur_a_type, cur_b_type, curfn in reversed(_BIN_OPS_SEARCH_ORDER):
if op != curop:
continue
if issubclass(a_type, cur_a_type) and issubclass(b_type, cur_b_type):
_BIN_OPS[(op, a_type, b_type)] = curfn # cache concrete types for later
binfn = curfn
break
if binfn is None:
binfn = _MISSING
_BIN_OPS[(op, a_type, b_type)] = _MISSING
if binfn is _MISSING:
return NotImplemented
with ResumedTracing(): # TODO: <-- can we instead selectively resume? Am I only doing this to satisfy the binop tracing check?
return binfn(op, a, b)
def _binop_type_hints(fn: Callable):
hints = get_type_hints(fn)
a, b = hints["a"], hints["b"]
if typing_inspect.get_origin(a) == Union:
a = typing_inspect.get_args(a)
else:
a = [a]
if typing_inspect.get_origin(b) == Union:
b = typing_inspect.get_args(b)
else:
b = [b]
return (a, b)
def setup_promotion(
fn: Callable[[Number, Number], Tuple[Number, Number]], reg_ops: Set[BinFn]
):
a, b = _binop_type_hints(fn)
for a_type in a:
for b_type in b:
for op in reg_ops:
def promotion_forward(o, x, y):
x2, y2 = fn(x, y)
return numeric_binop(o, x2, y2)
def promotion_backward(o, x, y):
y2, x2 = fn(y, x)
return numeric_binop(o, x2, y2)
_BIN_OPS_SEARCH_ORDER.append((op, a_type, b_type, promotion_forward))
_BIN_OPS_SEARCH_ORDER.append((op, b_type, a_type, promotion_backward))
_FLIPPED_OPS: Dict[BinFn, BinFn] = {
ops.ge: ops.le,
ops.gt: ops.lt,
ops.le: ops.ge,
ops.lt: ops.gt,
}
def setup_binop(fn: Callable[[BinFn, Number, Number], Number], reg_ops: Set[BinFn]):
a, b = _binop_type_hints(fn)
for a_type in a:
for b_type in b:
for op in reg_ops:
_BIN_OPS_SEARCH_ORDER.append((op, a_type, b_type, fn))
# Also, handle flipped comparisons transparently:
## (a >= b) <==> (b <= a)
if op in (ops.ge, ops.gt, ops.le, ops.lt):
def flipped(o: BinFn, x: Number, y: Number) -> Number:
return fn(_FLIPPED_OPS[o], y, x)
_BIN_OPS_SEARCH_ORDER.append(
(_FLIPPED_OPS[op], b_type, a_type, flipped)
)
_COMPARISON_OPS: Set[BinFn] = {
ops.eq,
ops.ne,
ops.ge,
ops.gt,
ops.le,
ops.lt,
}
_ARITHMETIC_OPS: Set[BinFn] = {
ops.add,
ops.sub,
ops.mul,
ops.truediv,
ops.floordiv,
ops.mod,
ops.pow,
}
_BITWISE_OPS: Set[BinFn] = {
ops.and_,
ops.or_,
ops.xor,
ops.rshift,
ops.lshift,
}
def apply_smt(op: BinFn, x: z3.ExprRef, y: z3.ExprRef) -> z3.ExprRef:
# Mostly, z3 overloads operators and things just work.
# But some special cases need to be checked first.
space = context_statespace()
if op in _ARITHMETIC_OPS:
if op in (ops.truediv, ops.floordiv, ops.mod):
if space.smt_fork(y == 0):
raise ZeroDivisionError
if op == ops.floordiv:
if space.smt_fork(y >= 0):
if space.smt_fork(x >= 0):
return x / y
else:
return -((y - x - 1) / y)
else:
if space.smt_fork(x >= 0):
return -((x - y - 1) / -y)
else:
return -x / -y
if op == ops.mod:
if space.smt_fork(y >= 0):
return x % y
elif space.smt_fork(x % y == 0):
return z3IntVal(0)
else:
return (x % y) + y
elif op == ops.pow:
if space.smt_fork(z3.And(x == 0, y < 0)):
raise ZeroDivisionError("zero cannot be raised to a negative power")
return op(x, y)
_ARITHMETIC_AND_COMPARISON_OPS = _ARITHMETIC_OPS.union(_COMPARISON_OPS)
_ALL_OPS = _ARITHMETIC_AND_COMPARISON_OPS.union(_BITWISE_OPS)
def setup_binops():
# Lower entries take precendence when searching.
# We check NaN and infitity immediately; not all
# symbolic floats support these cases.
def _(a: Real, b: float):
if math.isfinite(b):
return (a, FiniteFloat(b)) # type: ignore
return (a, NonFiniteFloat(b))
setup_promotion(_, _ARITHMETIC_AND_COMPARISON_OPS)
# Almost all operators involving booleans should upconvert to integers.
def _(a: SymbolicBool, b: Number):
with NoTracing():
return (SymbolicInt(z3.If(a.var, 1, 0)), b)
setup_promotion(_, _ALL_OPS)
# Implicitly upconvert symbolic ints to floats.
def _(a: SymbolicInt, b: Union[float, FiniteFloat, SymbolicFloat, complex]):
with NoTracing():
return (SymbolicFloat(z3.ToReal(a.var)), b)
setup_promotion(_, _ARITHMETIC_AND_COMPARISON_OPS)
# Implicitly upconvert native ints to floats.
def _(a: int, b: Union[float, FiniteFloat, SymbolicFloat, complex]):
return (float(a), b)
setup_promotion(_, _ARITHMETIC_AND_COMPARISON_OPS)
# Implicitly upconvert native bools to ints.
def _(a: bool, b: Union[SymbolicInt, SymbolicFloat]):
return (int(a), b)
setup_promotion(_, _ARITHMETIC_AND_COMPARISON_OPS)
# complex
def _(op: BinFn, a: SymbolicNumberAble, b: complex):
return op(complex(a), b) # type: ignore
setup_binop(_, _ALL_OPS)
# float
def _(op: BinFn, a: SymbolicFloat, b: SymbolicFloat):
with NoTracing():
return SymbolicFloat(apply_smt(op, a.var, b.var))
setup_binop(_, _ARITHMETIC_OPS)
def _(op: BinFn, a: SymbolicFloat, b: SymbolicFloat):
with NoTracing():
return SymbolicBool(apply_smt(op, a.var, b.var))
setup_binop(_, _COMPARISON_OPS)
def _(op: BinFn, a: SymbolicFloat, b: FiniteFloat):
with NoTracing():
return SymbolicFloat(apply_smt(op, a.var, z3.RealVal(b.val)))
setup_binop(_, _ARITHMETIC_OPS)
def _(op: BinFn, a: FiniteFloat, b: SymbolicFloat):
with NoTracing():
return SymbolicFloat(apply_smt(op, z3.RealVal(a.val), b.var))
setup_binop(_, _ARITHMETIC_OPS)
def _(op: BinFn, a: Union[FiniteFloat, SymbolicFloat], b: NonFiniteFloat):
if isinstance(a, FiniteFloat):
comparable_a: Union[float, SymbolicFloat] = a.val
else:
comparable_a = a
# These three cases help cover operations like `a * -inf` which is either
# positive of negative infinity depending on the sign of `a`.
if comparable_a > 0: # type: ignore
return op(1, b.val) # type: ignore
elif comparable_a < 0:
return op(-1, b.val) # type: ignore
else:
return op(0, b.val) # type: ignore
setup_binop(_, _ARITHMETIC_AND_COMPARISON_OPS)
def _(op: BinFn, a: NonFiniteFloat, b: NonFiniteFloat):
return op(a.val, b.val) # type: ignore
setup_binop(_, _ARITHMETIC_AND_COMPARISON_OPS)
def _(op: BinFn, a: SymbolicFloat, b: FiniteFloat):
with NoTracing():
return SymbolicBool(apply_smt(op, a.var, z3.RealVal(b.val)))
setup_binop(_, _COMPARISON_OPS)
# int
def _(op: BinFn, a: SymbolicInt, b: SymbolicInt):
with NoTracing():
return SymbolicInt(apply_smt(op, a.var, b.var))
setup_binop(_, _ARITHMETIC_OPS)
def _(op: BinFn, a: SymbolicInt, b: SymbolicInt):
with NoTracing():
return SymbolicBool(apply_smt(op, a.var, b.var))
setup_binop(_, _COMPARISON_OPS)
def _(op: BinFn, a: SymbolicInt, b: int):
with NoTracing():
return SymbolicInt(apply_smt(op, a.var, z3IntVal(b)))
setup_binop(_, _ARITHMETIC_OPS)
def _(op: BinFn, a: int, b: SymbolicInt):
with NoTracing():
return SymbolicInt(apply_smt(op, z3IntVal(a), b.var))
setup_binop(_, _ARITHMETIC_OPS)
def _(op: BinFn, a: SymbolicInt, b: int):
with NoTracing():
return SymbolicBool(apply_smt(op, a.var, z3IntVal(b)))
setup_binop(_, _COMPARISON_OPS)
def _(op: BinFn, a: Integral, b: Integral):
# Some bitwise operators require realization presently.
# TODO: when one side is already realized, we could do something smarter.
return op(a.__index__(), b.__index__()) # type: ignore
setup_binop(_, {ops.or_, ops.xor})
def _(op: BinFn, a: Integral, b: Integral):
if b < 0:
raise ValueError("negative shift count")
b = realize(b) # Symbolic exponents defeat the solver
if op == ops.lshift:
return a * (2**b)
else:
return a // (2**b)
setup_binop(_, {ops.lshift, ops.rshift})
_AND_MASKS_TO_MOD = {
# It's common to use & to mask low bits. We can avoid realization by converting
# these situations into mod operations.
0x01: 2,
0x03: 4,
0x07: 8,
0x0F: 16,
0x1F: 32,
0x3F: 64,
0x7F: 128,
0xFF: 256,
}
def _(op: BinFn, a: Integral, b: Integral):
with NoTracing():
if isinstance(b, SymbolicInt):
# Have `a` be symbolic, if possible
(a, b) = (b, a)
# Check whether we can interpret the mask as a mod operation:
b = realize(b)
if b == 0:
return 0
mask_mod = _AND_MASKS_TO_MOD.get(b)
if mask_mod and isinstance(a, SymbolicInt):
if context_statespace().smt_fork(a.var >= 0, probability_true=0.75):
return SymbolicInt(a.var % mask_mod)
else:
return SymbolicInt(b - ((-a.var - 1) % mask_mod))
# Fall back to full realization
return op(realize(a), b)
setup_binop(_, {ops.and_})
# TODO: is this necessary still?
def _(
op: BinFn, a: Integral, b: Integral
): # Floor division over ints requires realization, at present
return op(a.__index__(), b.__index__()) # type: ignore
setup_binop(_, {ops.truediv})
def _(a: SymbolicInt, b: Number): # Division over ints must produce float
return (a.__float__(), b)
setup_promotion(_, {ops.truediv})
def _float_divmod(a: Union[float, SymbolicFloat], b: Union[float, SymbolicFloat]):
with NoTracing():
smt_a = SymbolicFloat._coerce_to_smt_sort(a)
smt_b = SymbolicFloat._coerce_to_smt_sort(b)
if smt_a is None or smt_b is None:
raise CrosshairInternal
space = context_statespace()
remainder = z3.Real(f"remainder{space.uniq()}")
modproduct = z3.Int(f"modproduct{space.uniq()}")
# From https://docs.python.org/3.3/reference/expressions.html#binary-arithmetic-operations:
# The modulo operator always yields a result with the same sign as its second operand (or zero).
# absolute value of the result is strictly smaller than the absolute value of the second operand.
space.add(smt_b * modproduct + remainder == smt_a)
if space.smt_fork(smt_b == 0):
raise ZeroDivisionError
elif space.smt_fork(smt_b > 0):
space.add(remainder >= 0)
space.add(remainder < smt_b)
else:
space.add(remainder <= 0)
space.add(smt_b < remainder)
return (SymbolicInt(modproduct), SymbolicFloat(remainder))
def _(op: BinFn, a: Union[float, SymbolicFloat], b: Union[float, SymbolicFloat]):
return _float_divmod(a, b)[1]
setup_binop(_, {ops.mod})
def _(op: BinFn, a: Union[float, SymbolicFloat], b: Union[float, SymbolicFloat]):
return _float_divmod(a, b)[0]
setup_binop(_, {ops.floordiv})
# bool
def _(op: BinFn, a: SymbolicBool, b: SymbolicBool):
with NoTracing():
return SymbolicBool(apply_smt(op, a.var, b.var))
setup_binop(_, {ops.eq, ops.ne})
#
# END new numbers
#
class SymbolicNumberAble(SymbolicValue, Real):
def __pos__(self):
return self
def __neg__(self):
return self._unary_op(ops.neg)
def __abs__(self):
return self._unary_op(lambda v: z3.If(v < 0, -v, v))
def __lt__(self, other):
return numeric_binop(ops.lt, self, other)
def __gt__(self, other):
return numeric_binop(ops.gt, self, other)
def __le__(self, other):
return numeric_binop(ops.le, self, other)
def __ge__(self, other):
return numeric_binop(ops.ge, self, other)
def __eq__(self, other):
return numeric_binop(ops.eq, self, other)
def __add__(self, other):
return numeric_binop(ops.add, self, other)
def __radd__(self, other):
return numeric_binop(ops.add, other, self)
def __sub__(self, other):
return numeric_binop(ops.sub, self, other)
def __rsub__(self, other):
return numeric_binop(ops.sub, other, self)
def __mul__(self, other):
return numeric_binop(ops.mul, self, other)
def __rmul__(self, other):
return numeric_binop(ops.mul, other, self)
def __pow__(self, other, mod=None):
if mod is not None:
return pow(realize(self), pow, mod)
return numeric_binop(ops.pow, self, other)
def __rpow__(self, other, mod=None):
if mod is not None:
return pow(other, realize(self), mod)
return numeric_binop(ops.pow, other, self)
def __lshift__(self, other):
return numeric_binop(ops.lshift, self, other)
def __rlshift__(self, other):
return numeric_binop(ops.lshift, other, self)
def __rshift__(self, other):
return numeric_binop(ops.rshift, self, other)
def __rrshift__(self, other):
return numeric_binop(ops.rshift, other, self)
def __and__(self, other):
return numeric_binop(ops.and_, self, other)
def __rand__(self, other):
return numeric_binop(ops.and_, other, self)
def __or__(self, other):
return numeric_binop(ops.or_, self, other)
def __ror__(self, other):
return numeric_binop(ops.or_, other, self)
def __xor__(self, other):
return numeric_binop(ops.xor, self, other)
def __rxor__(self, other):
return numeric_binop(ops.xor, other, self)
def __rtruediv__(self, other):
return numeric_binop(ops.truediv, other, self)
def __floordiv__(self, other):
return numeric_binop(ops.floordiv, self, other)
def __rfloordiv__(self, other):
return numeric_binop(ops.floordiv, other, self)
def __mod__(self, other):
return numeric_binop(ops.mod, self, other)
def __rmod__(self, other):
return numeric_binop(ops.mod, other, self)
def __divmod__(self, other):
return (self // other, self % other)
def __rdivmod__(self, other):
return (other // self, other % self)
def __format__(self, fmt: str):
return realize(self).__format__(realize(fmt))
class SymbolicIntable(SymbolicNumberAble, Integral):
# bitwise operators
def __invert__(self):
return -(self + 1)
def __floor__(self):
return self
def __ceil__(self):
return self
def __trunc__(self):
return self
def __mul__(self, other):
if isinstance(other, str):
if self <= 0:
return ""
return other * realize(self)
return numeric_binop(ops.mul, self, other)
__rmul__ = __mul__
def bit_count(self):
if self < 0:
return (-self).bit_count()
count = 0
threshold = 2
halfway = 1
while self >= halfway:
if self % threshold >= halfway:
count += 1
threshold *= 2
halfway *= 2
return count
class SymbolicBool(SymbolicIntable, AtomicSymbolicValue):
def __init__(self, smtvar: Union[str, z3.ExprRef], typ: Type = bool):
assert typ == bool
SymbolicValue.__init__(self, smtvar, typ)
@classmethod
def _ch_smt_sort(cls) -> z3.SortRef:
return _SMT_BOOL_SORT
@classmethod
def _pytype(cls) -> Type:
return bool