code
stringlengths
17
6.64M
class TruncCnxp(FunCnxp): sig = (Constant,) code = 'trunc' def type_constraints(self, tcs): tcs.integer(self) tcs.integer(self._args[0]) tcs.width_order(self, self._args[0])
class UMaxCnxp(FunCnxp): sig = (Constant, Constant) code = 'umax' def type_constraints(self, tcs): tcs.integer(self) tcs.eq_types(self, *self._args)
class UMinCnxp(FunCnxp): sig = (Constant, Constant) code = 'umin' def type_constraints(self, tcs): tcs.integer(self) tcs.eq_types(self, *self._args)
class WidthCnxp(FunCnxp): sig = (Value,) code = 'width' def type_constraints(self, tcs): tcs.integer(self) tcs.integer(self._args[0])
class ZExtCnxp(FunCnxp): sig = (Constant,) code = 'zext' def type_constraints(self, tcs): tcs.integer(self) tcs.integer(self._args[0]) tcs.width_order(self._args[0], self)
class FPExtCnxp(FunCnxp): sig = (Constant,) code = 'fpext' def type_constraints(self, tcs): tcs.float(self) tcs.float(self._args[0]) tcs.width_order(self._args[0], self)
class FPTruncCnxp(FunCnxp): sig = (Constant,) code = 'fptrunc' def type_constraints(self, tcs): tcs.float(self) tcs.float(self._args[0]) tcs.width_order(self, self._args[0])
class FPtoSICnxp(FunCnxp): sig = (Constant,) code = 'fptosi' def type_constraints(self, tcs): tcs.integer(self) tcs.float(self._args[0])
class FPtoUICnxp(FunCnxp): sig = (Constant,) code = 'fptoui' def type_constraints(self, tcs): tcs.integer(self) tcs.float(self._args[0])
class SItoFPCnxp(FunCnxp): sig = (Constant,) code = 'sitofp' def type_constraints(self, tcs): tcs.float(self) tcs.integer(self._args[0])
class UItoFPCnxp(FunCnxp): sig = (Constant,) code = 'uitofp' def type_constraints(self, tcs): tcs.float(self) tcs.integer(self._args[0])
class Predicate(Node): pass
class AndPred(Predicate): __slots__ = ('clauses',) @classmethod def of(cls, clauses): clauses = tuple(clauses) if (len(clauses) == 1): return clauses[0] return cls(clauses) def __init__(self, clauses): self.clauses = tuple(clauses) def pretty(self): ...
class OrPred(Predicate): __slots__ = ('clauses',) @classmethod def of(cls, clauses): clauses = tuple(clauses) if (len(clauses) == 1): return clauses[0] return cls(clauses) def __init__(self, clauses): self.clauses = tuple(clauses) def pretty(self): ...
class NotPred(Predicate): __slots__ = ('p',) def __init__(self, p): self.p = p def args(self): return (self.p,) def type_constraints(self, tcs): return
class Comparison(Predicate): __slots__ = ('op', 'x', 'y') def __init__(self, op, x, y): self.op = op self.x = x self.y = y def args(self): return (self.x, self.y) def type_constraints(self, tcs): if (self.op[0] == 'u'): tcs.integer(self.x) ...
class FunPred(Predicate): __slots__ = ('_args',) codes = {} @classmethod def check_args(cls, args): if (len(args) != len(cls.sig)): raise BadArgumentCount(len(cls.sig), len(args)) for i in xrange(len(args)): if (not isinstance(args[i], cls.sig[i])): ...
def _none(term, tcs): pass
def _one_int(term, tcs): tcs.integer(term._args[0])
def _all_ints(term, tcs): tcs.integer(term._args[0]) tcs.eq_types(*term._args)
def _one_float(term, tcs): tcs.float(term._args[0])
def _all_floats(term, tcs): tcs.float(term._args[0]) tcs.eq_types(*term._args)
class CannotBeNegativeZeroPred(FunPred): sig = (Value,) code = 'CannotBeNegativeZero' type_constraints = _one_float
class FPIdenticalPred(FunPred): sig = (Constant, Constant) code = 'fpIdentical' type_constraints = _all_floats
class FPIntegerPred(FunPred): sig = (Constant,) code = 'fpInteger' type_constraints = _one_float
class HasNInfPred(FunPred): sig = (FastMathInst,) code = 'hasNoInf' type_constraints = _none
class HasNNaNPred(FunPred): sig = (FastMathInst,) code = 'hasNoNaN' type_constraints = _none
class HasNSWPred(FunPred): sig = (WrappingBinaryOperator,) code = 'hasNSW' type_constraints = _none
class HasNSZPred(FunPred): sig = (FastMathInst,) code = 'hasNSZ' type_constraints = _none
class HasNUWPred(FunPred): sig = (WrappingBinaryOperator,) code = 'hasNUW' type_constraints = _none
class IsConstantPred(FunPred): sig = (Value,) code = 'isConstant' type_constraints = _none
class IsExactPred(FunPred): sig = (InexactBinaryOperator,) code = 'isExact' type_constraints = _none
class IntMinPred(FunPred): sig = (Constant,) code = 'isSignBit' type_constraints = _one_int
class Power2Pred(FunPred): sig = (Value,) code = 'isPowerOf2' type_constraints = _one_int
class Power2OrZPred(FunPred): sig = (Value,) code = 'isPowerOf2OrZero' type_constraints = _one_int
class ShiftedMaskPred(FunPred): sig = (Constant,) code = 'isShiftedMask' type_constraints = _one_int
class MaskZeroPred(FunPred): sig = (Value, Constant) code = 'MaskedValueIsZero' type_constraints = _all_ints
class NSWAddPred(FunPred): sig = (Value, Value) code = 'WillNotOverflowSignedAdd' type_constraints = _all_ints
class NUWAddPred(FunPred): sig = (Value, Value) code = 'WillNotOverflowUnsignedAdd' type_constraints = _all_ints
class NSWSubPred(FunPred): sig = (Value, Value) code = 'WillNotOverflowSignedSub' type_constraints = _all_ints
class NUWSubPred(FunPred): sig = (Value, Value) code = 'WillNotOverflowUnsignedSub' type_constraints = _all_ints
class NSWMulPred(FunPred): sig = (Constant, Constant) code = 'WillNotOverflowSignedMul' type_constraints = _all_ints
class NUWMulPred(FunPred): sig = (Constant, Constant) code = 'WillNotOverflowUnsignedMul' type_constraints = _all_ints
class NUWShlPred(FunPred): sig = (Constant, Constant) code = 'WillNotOverflowUnsignedShl' type_constraints = _all_ints
class OneUsePred(FunPred): sig = ((Input, Instruction),) code = 'hasOneUse' type_constraints = _none
def subterms(term, seen=None): 'Generate all subterms of the provided term.\n\n No subterm is generated twice. All terms appear after their subterms.\n ' if (seen is None): seen = set() elif (term in seen): return for a in term.args(): for s in subterms(a, seen): ...
def proper_subterms(term): seen = set() return itertools.chain.from_iterable((subterms(a, seen) for a in term.args()))
def count_uses(dag, uses=None): 'Count the number of times each subterm is referenced.\n ' if (uses is None): uses = collections.Counter() def walk(v): for a in v.args(): if (a not in uses): walk(a) uses[a] += 1 walk(dag) return uses
def constant_defs(tgt, terms=[]): 'Generate shared constant terms from the target and precondition.\n\n Terms are generated before any terms that reference them.\n ' uses = count_uses(tgt) for t in terms: count_uses(t, uses) for t in subterms(tgt): if ((uses[t] > 1) and isinstance(t,...
class BadArgumentCount(error.Error): def __init__(self, wanted, got): self.wanted = wanted self.got = got def __str__(self): return 'expected {} received {}'.format(self.wanted, self.got)
class BadArgumentKind(error.Error): def __init__(self, idx, kind): self.idx = idx self.kind = kind kinds = {Value: 'any value', Constant: 'constant', (Input, Instruction): 'register', FastMathInst: 'floating-point inst', WrappingBinaryOperator: 'add, sub, mul, or shl', InexactBinaryOperator: ...
def check(opt, type_model, encoding=config.encoding, assume_inhabited=False): 'Check that opt is a refinement for the given type_model.\n Raises Error if the opt is not a refinement. Returns false if opt\n is trivial (that is, the precondition cannot be satisfied. Otherwise,\n returns true.\n\n Keywords:\n e...
def satisfiable(expr, opt_name='<unknown opt>', stage='<unknown>'): 'Return a model satisfying the SMT expression, if any. Return None if\n the expression is unsatisfiable. Raise Error if the solver cannot determine\n satisfiability.\n ' s = z3.Solver() if (config.timeout is not None): s.set('t...
def format_z3val(val): if isinstance(val, z3.BitVecNumRef): w = val.size() u = val.as_long() s = val.as_signed_long() if (u == s): return '0x{1:0{0}x} ({1})'.format(((w + 3) / 4), u) return '0x{1:0{0}x} ({1}, {2})'.format(((w + 3) / 4), u, s) if isinstance(v...
class Error(error.Error): pass
class CounterExampleError(Error): def __init__(self, cause, model, types, src, srcv, tgtv, trans): self.cause = cause self.model = model self.types = types self.src = src self.srcv = srcv self.tgtv = tgtv self.trans = trans cause_str = {PRESAFE: 'Precon...
def _ty_sort(ty): 'Translate a Type expression to a Z3 Sort' if isinstance(ty, IntType): return z3.BitVecSort(ty.width) return {PtrType: z3.BitVecSort(64), HalfType: z3.FloatHalf(), SingleType: z3.Float32(), DoubleType: z3.Float64(), FP128Type: z3.Float128(), X86FP80Type: z3.FPSort(15, 64)}[type(t...
class MetaEncoder(type): def __init__(cls, name, bases, dict): if (not hasattr(cls, 'registry')): cls.registry = {} if (not (name.startswith('Base') or name.endswith('Mixin'))): reg_name = name if ((cls.__module__ != __name__) and (cls.__module__ != '__main__')...
class BaseSMTEncoder(): __metaclass__ = MetaEncoder def __init__(self, type_model): self.types = type_model self.fresh = 0 self.reset() self._analysis = collections.defaultdict(dict) def reset(self): self.defs = [] self.nops = [] self._safe = [] ...
def lookup(encoder): 'Return an SMT encoder with this name (case-insensitive).\n\n If passed a subclass of BaseSMTEncoder, return it unchanged.\n ' logger.debug('Looking up encoder %s', encoder) if isinstance(encoder, str): try: return BaseSMTEncoder.registry[encoder.lower()] ...
def encoders(): 'Return an iterator of name,class pairs for all known encoders.\n ' return BaseSMTEncoder.registry.iteritems()
@doubledispatch def eval(term, smt): '\n Return an SMT translation of term, using smt for subterms.\n ' raise NotImplementedError('cannot eval {} with {}'.format(type(term).__name__, type(smt).__name__))
def general_handler(fun): 'Returns a curried form a function, suitable for use as argument to\n eval.register.\n\n Usage:\n @general_handler\n def spam(term, smt, eggs):\n ...\n\n eval.register(Term, Encoder, spam(eggs))\n ' def wrapper(*args): return (lambda term, smt: fun(term, smt...
@general_handler def _handler(term, smt, op): return op(*(smt.eval(a) for a in term.args()))
@eval.register(Node, BaseSMTEncoder) def _(term, smt): raise NotImplementedError("Can't eval {} for {}".format(type(term).__name__, type(smt).__name__))
def binop(op, defined=None, nonpoison=None, poisons=None): return (lambda term, smt: smt._binary_operator(term, op, defined, nonpoison, poisons))
def fbinop(op): return (lambda term, smt: smt._float_binary_operator(term, op))
@doubledispatch def _eval_bitcast(src, tgt, v): '\n Return SMT expression converting v from src to tgt.\n\n Assumes src and tgt have the same bit width.\n ' raise NotImplementedError('Unexpected bitcast: {} -> {}'.format(src, tgt))
def _convert(op): return (lambda term, smt: op(smt.type(term.arg), smt.type(term), smt.eval(term.arg)))
@eval.register(FPTruncInst, BaseSMTEncoder) def _fptrunc(term, smt): v = smt.eval(term.arg) tgt = smt.type(term) e = (2 ** (tgt.exp - 1)) m = (2 ** e) rm = z3.get_default_rounding_mode() return smt._conditional_conv_value([(v > (- m)), (v < m)], z3.fpTpFP(rm, v, _ty_sort(tgt)), term.name)
@eval.register(FPtoSIInst, BaseSMTEncoder) def _fptosi(term, smt): v = smt.eval(term.arg) src = smt.type(term.arg) tgt = smt.type(term) m = (2 ** (tgt.width - 1)) return smt._conditional_conv_value([(v >= (- m)), (v <= (m - 1))], z3.fpToSBV(z3.RTZ(), v, _ty_sort(tgt)), term.name)
@eval.register(FPtoUIInst, BaseSMTEncoder) def _fptoui(term, smt): v = smt.eval(term.arg) src = smt.type(term.arg) tgt = smt.type(term) return smt._conditional_conv_value([(0 <= v), (v <= ((2 ** tgt.width) - 1))], z3.fpToUBV(z3.RTZ(), v, _ty_sort(tgt)), term.name)
@eval.register(SItoFPInst, BaseSMTEncoder) def _sitofp(term, smt): v = smt.eval(term.arg) src = smt.type(term.arg) tgt = smt.type(term) w = (2 ** (tgt.exp - 1)) if ((src.width - 1) > w): m = (2 ** w) conds = [((- m) < v), (v < m)] else: conds = [] return smt._condit...
@eval.register(UItoFPInst, BaseSMTEncoder) def _uitofp(term, smt): v = smt.eval(term.arg) src = smt.type(term.arg) tgt = smt.type(term) w = (2 ** (tgt.exp - 1)) if (src.width >= w): m = (2 ** w) conds = [z3.ULE(v, m)] else: conds = [] return smt._conditional_conv_va...
@eval.register(IcmpInst, BaseSMTEncoder) def _icmp(term, smt): x = smt.eval(term.x) y = smt.eval(term.y) cmp = smt._icmp_ops[term.pred](x, y) return bool_to_BitVec(cmp)
@eval.register(FcmpInst, BaseSMTEncoder) def _fcmp(term, smt): x = smt.eval(term.x) y = smt.eval(term.y) if (term.pred == ''): var = z3.BitVec(('fcmp_' + term.name), 4) ops = smt._fcmp_ops.itervalues() cmp = ops.next()(x, y) i = 1 for op in ops: cmp = z3...
@eval.register(Literal, BaseSMTEncoder) def _literal(term, smt): ty = smt.type(term) if isinstance(ty, FloatType): return z3.FPVal(term.val, _ty_sort(ty)) return z3.BitVecVal(term.val, ty.width)
@eval.register(UndefValue, BaseSMTEncoder) def _undef(term, smt): ty = smt.type(term) x = smt.fresh_var(ty) smt.add_qvar(x) return x
@eval.register(PoisonValue, BaseSMTEncoder) def _poison(term, smt): smt.add_nops(z3.BoolVal(False)) return smt.fresh_var(smt.type(term))
def _cbinop(op, safe): def handler(term, smt): x = smt.eval(term.x) y = smt.eval(term.y) smt.add_safe(safe(x, y)) return op(x, y) return handler
@eval.register(SDivCnxp, BaseSMTEncoder) def _sdiv(term, smt): if isinstance(smt.type(term), FloatType): return z3.fpDiv(z3.get_current_rounding_mode(), smt.eval(term.x), smt.eval(term.y)) x = smt.eval(term.x) y = smt.eval(term.y) smt.add_safe((y != 0)) return (x / y)
@eval.register(NegCnxp, BaseSMTEncoder) def _neg(term, smt): if isinstance(smt.type(term), FloatType): return z3.fpNeg(smt.eval(term.x)) return (- smt.eval(term.x))
@eval.register(AbsCnxp, BaseSMTEncoder) def _abs(term, smt): x = smt.eval(term._args[0]) if isinstance(smt.type(term), FloatType): return z3.fpAbs(x) return z3.If((x >= 0), x, (- x))
@general_handler def value_analysis(term, smt, name, exact, restrict): arg = term._args[0] try: return smt.get_analysis(name, arg) except KeyError: pass ty = smt.type(term) with smt.local_defined(), smt.local_nonpoison() as nx: x = smt.eval(arg) z = exact(x, ty) if ...
@eval.register(FPMantissaWidthCnxp, BaseSMTEncoder) def _mantissa(term, smt): ty = smt.type(term._args[0]) return z3.BitVecVal(ty.frac, smt.type(term).width)
@eval.register(WidthCnxp, BaseSMTEncoder) def _width(term, smt): return z3.BitVecVal(smt.type(term._args[0]).width, smt.type(term).width)
def mk_implies(premises, consequents): if (not consequents): return [] if premises: return [z3.Implies(mk_and(premises), mk_and(consequents))] return consequents
@eval.register(Comparison, BaseSMTEncoder) def _comparison(term, smt): if ((term.op == 'eq') and isinstance(smt.type(term.x), FloatType)): cmp = z3.fpEQ else: cmp = smt._icmp_ops[term.op] return cmp(smt.eval(term.x), smt.eval(term.y))
@general_handler def must_analysis(term, smt, name, op): logger.debug('Must-analysis %s of %s', name, term) args = term._args try: return smt.get_analysis(name, args) except KeyError: pass with smt.local_defined(), smt.local_nonpoison() as np: arg_smts = tuple((smt.eval(a) ...
@general_handler def has_attr(term, smt, attr): arg = term._args[0] if (attr in arg.flags): return z3.BoolVal(True) try: return smt.get_analysis(attr, arg) except KeyError: return smt.new_analysis(attr, arg)
class SMTPoison(BaseSMTEncoder): def _conditional_value(self, conds, v, name=''): self.add_nops(*conds) return v _conditional_conv_value = _conditional_value
class SMTUndef(BaseSMTEncoder): def _conditional_value(self, conds, v, name=''): if (not conds): return v self.fresh += 1 name = ('undef_{}_{}'.format(name, self.fresh) if name else ('undef_' + str(self.fresh))) u = z3.Const(name, v.sort()) self.add_qvar(u) ...
class UBCPSelectMixin(BaseSMTEncoder): 'Undefined behavior for poisoned choice, conditional poison\n ' pass
class UBCPSelect(UBCPSelectMixin, SMTUndef): pass
class UBSelectMixin(BaseSMTEncoder): 'Undefined behavior for poisoned choice, poion if either choice is poison\n ' pass
class UBSelect(UBSelectMixin, SMTUndef): pass
class NCCPSelectMixin(BaseSMTEncoder): 'Nondeterministic choice, conditional poison\n '
class NCCPSelect(NCCPSelectMixin, SMTUndef): pass
class CPSelectMixin(BaseSMTEncoder): 'Conditional poison\n '
class CPSelect(CPSelectMixin, SMTUndef): pass