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): return pretty.pfun('AndPred', self.clauses) def args(self): return self.clauses def type_constraints(self, tcs): return
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): return pretty.pfun('OrPred', self.clauses) def args(self): return self.clauses def type_constraints(self, tcs): return
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) else: tcs.number(self.x) tcs.eq_types(self.x, self.y) tcs.defaultable(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])): raise BadArgumentKind(i, cls.sig[i]) def __init__(self, *args): self.check_args(args) self._args = args def pretty(self): return pretty.pfun(type(self).__name__, self._args) def args(self): return self._args
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): (yield s) seen.add(term) (yield term)
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, Constant) and (not isinstance(t, Symbol))): (yield 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: 'sdiv, udiv, ashr, or lshr'} def __str__(self): return 'parameter {} expected {}'.format((self.idx + 1), self.kinds[self.kind])
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 encoding: specify an encoding using a string or SMTEncoder class\n assume_inhabited: if true, do not check whether the precondition is satisfied.\n ' logger.info('Checking refinement of %r', opt.name) encoding = smtinterp.lookup(encoding) smt = encoding(type_model) asm = smt.conjunction(opt.asm) premise = ((asm.aux + asm.safe) + asm.value) if (asm.defined or asm.nonpoison): raise Exception('Defined/Non-poison condition declared by assumption') pre = smt.conjunction(opt.pre) premise += pre.aux if (pre.defined or pre.nonpoison): raise Exception('Defined/Non-poison condition declared by precondition') src = smt(opt.src) if src.aux: raise Exception('Auxiliary condition declared by source') tgt = smt(opt.tgt) premise += tgt.aux def check_expr(stage, expr): m = satisfiable(expr, opt.name, _stage_name[stage]) if (m is not None): raise CounterExampleError(stage, m, type_model, opt.src, src.value, tgt.value, encoding) if pre.safe: check_expr(PRESAFE, mk_and((premise + [mk_not(pre.safe)]))) premise += pre.value inhabited = (assume_inhabited or (satisfiable(mk_and(premise), opt.name, 'inhabited') is not None)) if tgt.safe: check_expr(TGTSAFE, mk_and((premise + [mk_not(tgt.safe)]))) premise += src.defined if config.poison_undef: premise += src.nonpoison if tgt.defined: expr = (premise + [mk_not(tgt.defined)]) check_expr(UB, mk_forall(src.qvars, expr)) if (not config.poison_undef): premise += src.nonpoison if tgt.nonpoison: check_expr(POISON, mk_forall(src.qvars, (premise + [mk_not(tgt.nonpoison)]))) check_expr(UNEQUAL, mk_forall(src.qvars, (premise + [z3.Not((src.value == tgt.value))]))) return inhabited
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('timeout', config.timeout) s.add(expr) logger.debug('%s check for %s\n%s', stage, opt_name, s) time_start = time.time() res = s.check() time_end = time.time() solve_time = (time_end - time_start) if logger.isEnabledFor(logging.DEBUG): logger.debug('\nresult: %s\ntime: %s\nstats\n%s', res, solve_time, s.statistics()) if (config.bench_dir and (solve_time >= config.bench_threshold)): files = glob.glob((config.bench_dir + '/*.smt2')) filename = '{0}/{1:03d}.smt2'.format(config.bench_dir, len(files)) logger.debug('Writing benchmark file %r', filename) fd = open(filename, 'w') fd.write(header) fd.write('; {0} check for {1!r}\n'.format(stage, opt_name)) fd.write('; time: {0} s\n\n'.format(solve_time)) fd.write(s.to_smt2()) fd.close() if (res == z3.sat): m = s.model() logger.debug('counterexample: %s', m) return m if (res == z3.unknown): raise Error(('Model returned unknown: ' + s.reason_unknown())) return None
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(val, z3.FPRef): return str(val)
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: 'Precondition is unsafe', TGTSAFE: 'Target is unsafe', UB: 'Target introduces undefined behavior', POISON: 'Target introduces poison', UNEQUAL: 'Mismatch in values'} def __str__(self): smt = self.trans(self.types) vars = [v for v in proper_subterms(self.src) if isinstance(v, (Input, Instruction))] ty_width = 1 name_width = 1 rows = [] for v in vars: ty = str(self.types[v]) ty_width = max(ty_width, len(ty)) name = v.name name_width = max(name_width, len(name)) interp = smt(v) if z3.is_false(self.model.evaluate(mk_and(interp.nonpoison))): rows.append((ty, name, 'poison')) else: val = self.model.evaluate(smt.eval(v), model_completion=True) rows.append((ty, name, format_z3val(val))) interp = smt(self.src) if z3.is_false(self.model.evaluate(mk_and(interp.nonpoison))): srcval = 'poison' else: srcval = format_z3val(self.model.evaluate(self.srcv, True)) if (self.cause == UB): tgtval = 'undefined' elif (self.cause == POISON): tgtval = 'poison' else: tgtval = format_z3val(self.model.evaluate(self.tgtv, True)) return '{cause} for {srcty} {src}\n\nExample:\n{table}\nsource: {srcval}\ntarget: {tgtval}'.format(cause=self.cause_str[self.cause], srcty=self.types[self.src], src=self.src.name, table='\n'.join(('{0:>{1}} {2:{3}} = {4}'.format(ty, ty_width, name, name_width, val) for (ty, name, val) in rows)), srcval=srcval, tgtval=tgtval)
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(ty)]
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__')): reg_name = ((cls.__module__ + '.') + name) reg_name = reg_name.lower().replace('_', '-') if (reg_name in cls.registry): raise ValueError('Duplicate encoder key: {0}\n{1}\n{2}'.format(reg_name, cls, cls.registry[reg_name])) cls.registry[reg_name] = cls return super(MetaEncoder, cls).__init__(name, bases, dict)
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 = [] self._aux = [] self.qvars = [] def eval(self, term): 'Return the SMT translation of the term. Any side conditions are added\n to the translator context.\n ' logger.debug('eval %s', term) return eval(term, self) def __call__(self, term): 'Interpret the term in a fresh translator context.\n\n Quantified variables are guaranteed to be unique between different\n calls to the same SMTTranslator object.\n ' logger.debug('call %s', term) self.reset() v = eval(term, self) return Interp(value=v, defined=self.defs, nonpoison=self.nops, safe=self._safe, aux=self._aux, qvars=self.qvars) def _conjunction(self, clauses): context = [] for c in clauses: with self.local_safe() as s: p = self.eval(c) self.add_safe(*mk_implies(context, s)) context.append(p) return context def conjunction(self, clauses): 'Interpret a list of predicates in a fresh context.\n\n The Interp.value returned will be a list of SMT expressions.\n ' self.reset() ps = self._conjunction(clauses) return Interp(value=ps, defined=self.defs, nonpoison=self.nops, safe=self._safe, aux=self._aux, qvars=self.qvars) def add_defs(self, *defs): 'Add well-defined conditions to the current translator context.\n ' self.defs += defs @contextmanager def local_defined(self): 'Create a context with well-defined conditions independent from any prior\n conditions.\n\n Returns the list of well-defined conditions associated with the operations\n in the context.\n\n Usage:\n with smt.local_defined() as s:\n <operations>\n ' old = self.defs try: new = [] self.defs = new (yield new) finally: self.defs = old def add_nonpoison(self, *nonpoisons): 'Add non-poison conditions to current translator context.\n ' self.nops += nonpoisons add_nops = add_nonpoison @contextmanager def local_nonpoison(self): 'Create a context with nonpoison conditions independent from any prior\n conditions.\n\n Returns the list of nonpoison conditions associated with the operations in\n the context.\n\n Usage:\n with smt.local_nonpoison() as s:\n <operations>\n ' old = self.nops try: new = [] self.nops = new (yield new) finally: self.nops = old def add_safe(self, *safe): 'Add safety conditions to the current translator context.\n ' self._safe += safe @contextmanager def local_safe(self): 'Create a context with safety conditions independent from any prior\n conditions.\n\n Returns the list of safety conditions associated with the operations in\n the context.\n\n Usage:\n with smt.local_safe() as s:\n <operations>\n ' old = self._safe try: new = [] self._safe = new (yield new) finally: self._safe = old def add_aux(self, *auxs): 'Add auxiliary conditions to the current translator context.\n ' self._aux += auxs def add_qvar(self, *qvars): 'Add quantified variables to the current translator context.\n ' self.qvars += qvars def type(self, term): return self.types[term] def fresh_bool(self): self.fresh += 1 return z3.Bool(('ana_' + str(self.fresh))) def fresh_var(self, ty, prefix='undef_'): self.fresh += 1 return z3.Const((prefix + str(self.fresh)), _ty_sort(ty)) def has_analysis(self, name, key): return ((name in self._analysis) and (key in self._analysis[name])) def get_analysis(self, name, key): return self._analysis[name][key] def new_analysis(self, name, key, type=None): if (key in self._analysis[name]): raise ValueError('Attempt to recreate analysis {} for {}'.format(name, key)) self.fresh += 1 r = z3.Const('ana_{}_{}'.format(name, self.fresh), (z3.BoolSort() if (type is None) else _ty_sort(type))) self._analysis[name][key] = r return r def _conditional_value(self, conds, v, name=''): raise NotImplementedError('{} does not support floating-point'.format(type(self).__name__.lower())) def _conditional_conv_value(self, conds, v, name=''): raise NotImplementedError('{} does not support floating-point conversion'.format(type(self).__name__.lower())) def _binary_operator(self, term, op, defined, nonpoison, poisons): x = self.eval(term.x) y = self.eval(term.y) if defined: self.add_defs(*defined(x, y)) if nonpoison: self.add_nonpoison(*nonpoison(x, y)) if poisons: for f in poisons: try: b = self.get_analysis(f, term) self.add_nonpoison(z3.Implies(b, poisons[f](x, y))) except KeyError: if (f in term.flags): self.add_nonpoison(poisons[f](x, y)) return op(x, y) def _float_binary_operator(self, term, op): x = self.eval(term.x) y = self.eval(term.y) z = op(x, y) conds = [] if self.has_analysis('nnan', term): df = z3.And(z3.Not(z3.fpIsNaN(x)), z3.Not(z3.fpIsNaN(y)), z3.Not(z3.fpIsNaN(z))) conds.append(z3.Implies(self.get_analysis('nnan', term), df)) elif ('nnan' in term.flags): conds += [z3.Not(z3.fpIsNaN(x)), z3.Not(z3.fpIsNaN(y)), z3.Not(z3.fpIsNaN(z))] if self.has_analysis('ninf', term): df = z3.And(z3.Not(z3.fpIsInf(x)), z3.Not(z3.fpIsInf(y)), z3.Not(z3.fpIsInf(z))) conds.append(z3.Implies(self.get_analysis('ninf', term), df)) elif ('ninf' in term.flags): conds += [z3.Not(z3.fpIsInf(x)), z3.Not(z3.fpIsInf(y)), z3.Not(z3.fpIsInf(z))] if (self.has_analysis('nsz', term) or ('nsz' in term.flags)): b = self.fresh_bool() self.add_qvar(b) z = op(x, y) c = z3.fpIsZero(z) if self.has_analysis('nsz', term): c = z3.And(self.get_analysis('nsz', term), c) s = _ty_sort(self.type(term)) z = z3.If(c, z3.If(b, 0, z3.fpMinusZero(s)), z) if isinstance(term, FDivInst): c = [z3.Not(z3.fpIsZero(x)), z3.fpIsZero(y)] if self.has_analysis('nsz', term): c.append(self.get_analysis('nsw', term)) z = z3.If(z3.And(c), z3.If(b, z3.fpPlusInfinity(s), z3.fpMinusInfinity(s)), z) return self._conditional_value(conds, z, term.name) _icmp_ops = {'eq': operator.eq, 'ne': operator.ne, 'ugt': z3.UGT, 'uge': z3.UGE, 'ult': z3.ULT, 'ule': z3.ULE, 'sgt': operator.gt, 'sge': operator.ge, 'slt': operator.lt, 'sle': operator.le} _fcmp_ops = {'false': (lambda x, y: z3.BoolVal(False)), 'oeq': z3.fpEQ, 'ogt': z3.fpGT, 'oge': z3.fpGEQ, 'olt': z3.fpLT, 'ole': z3.fpLEQ, 'one': (lambda x, y: z3.Not(fpUEQ(x, y))), 'ord': (lambda x, y: z3.Not(z3.Or(z3.fpIsNaN(x), z3.fpIsNaN(y)))), 'ueq': fpUEQ, 'ugt': (lambda x, y: z3.Not(z3.fpLEQ(x, y))), 'uge': (lambda x, y: z3.Not(z3.fpLT(x, y))), 'ult': (lambda x, y: z3.Not(z3.fpGEQ(x, y))), 'ule': (lambda x, y: z3.Not(z3.fpGT(x, y))), 'une': z3.fpNEQ, 'uno': (lambda x, y: z3.Or(z3.fpIsNaN(x), z3.fpIsNaN(y))), 'true': (lambda x, y: z3.BoolVal(True))}
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()] except KeyError: raise error.Error(('Unknown SMT encoder: ' + encoder)) if (isinstance(encoder, type) and issubclass(encoder, BaseSMTEncoder)): return encoder raise ValueError('Argument to lookup must be string or class')
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, *args)) functools.update_wrapper(wrapper, fun) return wrapper
@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._conditional_conv_value(conds, z3.fpToFP(z3.get_default_rounding_mode(), v, _ty_sort(tgt)), term.name)
@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_value(conds, z3.fpToFPUnsigned(z3.get_default_rounding_mode(), v, _ty_sort(tgt)), term.name)
@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.If((var == i), op(x, y), cmp) i += 1 else: cmp = smt._fcmp_ops[term.pred](x, y) conds = [] if ('nnan' in term.flags): conds += [z3.Not(z3.fpIsNaN(x)), z3.Not(z3.fpIsNaN(y))] if ('ninf' in term.flags): conds += [z3.Not(z3.fpIsInf(x)), z3.Not(z3.fpIsInf(y))] return smt._conditional_value(conds, bool_to_BitVec(cmp), term.name)
@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 isinstance(arg, Constant): return z r = smt.new_analysis(name, arg, type=ty) smt.add_aux(*mk_implies(nx, [restrict(r, z)])) return r
@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) for a in args)) if all((isinstance(a, Constant) for a in args)): return op(*arg_smts) r = smt.new_analysis(name, args) np.append(r) smt.add_aux(z3.Implies(mk_and(np), op(*arg_smts))) return r
@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) return z3.If(mk_and(conds), v, u) _conditional_conv_value = _conditional_value
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