def createIf(index): if index == msb: return z3.Extract(msb, msb, wz3) else: return z3.If( bz3 == z3.BitVecVal(index, self.bsz), z3.Extract(index, index, wz3), createIf(index+1))
def merge_attrs(target_cls, cond, then_attrs): for then_name, then_val in then_attrs.items(): try: attr_val = target_cls.resolve_reference(then_name) except KeyError: # if the attribute does not exist it is not relevant # this is because of scoping # FIXME: Make sure this is actually the case... continue if isinstance(attr_val, StructInstance): attr_val.valid = z3.If(cond, then_val.valid, attr_val.valid) merge_attrs(attr_val, cond, then_val.locals) elif isinstance(attr_val, z3.ExprRef): if then_val.sort() != attr_val.sort(): attr_val = z3_cast(attr_val, then_val.sort()) if_expr = z3.If(cond, then_val, attr_val) target_cls.set_or_add_var(then_name, if_expr)
def recursive_if(val, opts, default=BV(0)): if len(opts) > 0: opt = opts[0] opts.remove(opt) val = z3.If(val == opt[0], opt[1], recursive_if(val, opts, default)) else: return default
def assert_input_encoding(solver, z3_bool_input, z3_real_input): """ Adds assertions to the given solver for the encoding relation between the BoolSort representation of the move and the RealSort representation of the input to the DNN """ for b, r in zip(z3_bool_input, z3_real_input): solver.add(z3.If(b, r == 0, r == 1))
def MSTORE(self, gstate, index, value): if isinstance(value, z3.BoolRef): value = z3.If(value, z3.BitVecVal(1, 256), z3.BitVecVal(0, 256)) value_bytes = svm_utils.split_bv_into_bytes(value) for i in range(32): if svm_utils.is_bv_concrete(index): gstate.mstate.memory_dict[svm_utils.get_concrete_int(index)+i] = value_bytes[i] gstate.mstate.memory = z3.Store(gstate.mstate.memory, index+i, value_bytes[i])
def test_if(self) -> None: self.assertEqual( If( [ (Greater(Variable("a"), Number(5)), Number(1)), (Greater(Variable("b"), Number(100)), Number(10)), ], Number(100), ).z3expr(), z3.If( z3.Int("a") > z3.IntVal(5), z3.IntVal(1), z3.If( z3.Int("b") > z3.IntVal(100), z3.IntVal(10), z3.IntVal(100)), ), )
def __cast_to_bits__(self, reference): if isinstance(reference, z3.ArithRef) or isinstance( reference, z3.IntNumRef): return z3.Int2BV(reference, self.longLength) elif isinstance(reference, z3.BoolRef): return z3.If(reference, 1, 0) else: return reference
def _forward(self, a, b, name="add", assign=False): # The interger addition is deterministic self._v = _Add(a.v, b.v) self._p = _Add(z3.If(a.p > b.p, a.p, b.p), _IntVal(1)) if assign: self.v, self.p = _Int(name), _Int("p_"+name) else: self.v, self.p = self._v, self._p
def z3max(x, y): if x is None: assert y is not None return y elif y is None: return x else: return z3.If(x > y, x, y)
def do_NAN(op, stack, state): prev_type = state.esil["type"] state.esil["type"] = FLOAT val, = pop_values(stack, state) stack.append(z3.If(z3.fpIsNaN(val), ONE, ZERO)) state.esil["type"] = prev_type
def strncpy(state, dst, src, num): dst = state.evalcon(dst).as_long() src = state.evalcon(src).as_long() length, last = state.memory.search(src, [BZERO]) # TODO this is not exactly right length = z3.If(num < length, num, length) state.memory.move(dst, src, length) return dst
def ITE(cond: Bool, iftrue: BV, iffalse: BV): assert iftrue.size == iffalse.size if isinstance(cond, BoolV): return iftrue if cond.value else iffalse return BVExpr( iftrue.size, z3.If(cond.z3obj, iftrue.z3obj, iffalse.z3obj) )
def strncat(state, dst, src, num): dlength, last = state.mem_search(src, [BZERO]) dlength = state.evalcon(dlength).as_long() length, last = state.mem_search(src, [BZERO]) # TODO this is not exactly right length = z3.If(num < length, num, length) state.mem_move(dst + dlength, src, length + ONE) return dst
def do_CMP(op, stack, state): arg1, arg2 = pop_values(stack, state, 2) #stack.append(arg1-arg2) state.esil["old"] = arg1 state.esil["cur"] = arg1 - arg2 if state.pcode: # pcode hax stack.append(z3.If(state.esil["cur"] == ZERO, ONE, ZERO))
def encode_internal(self, cond, left, right): if left == False and right == False: return False if left == False: return z3.And(z3.Not(cond, self._ctx), right, self._ctx) if right == False: return z3.And(cond, left, self._ctx) return z3.If(cond, left, right, self._ctx)
def calc_simplicity(): global SIMPLICITY_COSTS, SIMPLICITY_CONSTRAINTS for feature in ipa_data.FEATURES: lr = z3.Bool(f'alpha left right {feature}') cost_lr = z3.Int(f'simplicity cost alpha left right {feature}') # lc = z3.Bool(f'alpha left center {feature}') # cost_lc = z3.Int(f'simplicity cost alpha left center {feature}') # cr = z3.Bool(f'alpha center right {feature}') # cost_cr = z3.Int(f'simplicity cost alpha center right {feature}') SIMPLICITY_CONSTRAINTS.add(z3.Implies(lr, z3.Bool('left nonempty'))) SIMPLICITY_CONSTRAINTS.add(z3.Implies(lr, z3.Bool('right nonempty'))) # SIMPLICITY_CONSTRAINTS.add(z3.Implies(lc, z3.Bool('left nonempty'))) # SIMPLICITY_CONSTRAINTS.add(z3.Implies(cr, z3.Bool('right nonempty'))) weight = 2 * (FEATURE_PENALTY + FEATURE_SIMPLICITY_WEIGHT * ipa_data.FEATURE_SIMPLICITY[feature]) cost_fn_lr = z3.If(lr, weight, 0) SIMPLICITY_COSTS.add(cost_lr) SIMPLICITY_CONSTRAINTS.add(cost_lr == cost_fn_lr) # cost_fn_lc = z3.If(lc, weight, 0) # SIMPLICITY_COSTS.add(cost_lc) # SIMPLICITY_CONSTRAINTS.add(cost_lc == cost_fn_lc) # cost_fn_cr = z3.If(cr, weight, 0) # SIMPLICITY_COSTS.add(cost_cr) # SIMPLICITY_CONSTRAINTS.add(cost_cr == cost_fn_cr) for feature, position, value in product(ipa_data.FEATURES, POSITIONS, ['+', '-']): nonempty = z3.Bool(f'{position} nonempty') ident = z3.Bool(f'{feature} {position} {value}') weight = POSITION_WEIGHTS[ position] * FEATURE_PENALTY + FEATURE_SIMPLICITY_WEIGHT * ipa_data.FEATURE_SIMPLICITY[ feature] cost = z3.Int(f'simplicity cost {feature} {position} {value}') cost_fn = z3.If(ident, weight, 0) #print(f'{value}{feature} {position}: {weight}') SIMPLICITY_COSTS.add(cost) SIMPLICITY_CONSTRAINTS.add(z3.Implies(ident, nonempty)) SIMPLICITY_CONSTRAINTS.add(cost == cost_fn) SIMPLICITY_COSTS.add(z3.If(z3.Bool('left nonempty'), NONEMPTY_PENALTY, 0)) SIMPLICITY_COSTS.add(z3.If(z3.Bool('right nonempty'), NONEMPTY_PENALTY, 0)) SIMPLICITY_COSTS = frozenset(SIMPLICITY_COSTS) SIMPLICITY_CONSTRAINTS = frozenset(SIMPLICITY_CONSTRAINTS)
def cast_z3_bv(x, slv=None): """ translate expression x to its z3 form, if x.size==1 the returned formula is (If x ? 1 : 0). """ b = x.to_smtlib(slv) if z3.is_bool(b): b = z3.If(b, z3.BitVecVal(1, 1), z3.BitVecVal(0, 1)) return b
def walk_ite(self, formula, args, **kwargs): i = args[0] t = args[1] e = args[2] if self._get_type(formula).is_bool_type(): return z3.And(z3.Implies(i, t), z3.Implies(z3.Not(i), e)) else: return z3.If(i, t, e)
def constraints(self, solver, vars, model): for _person_name, _person in model.persons.items(): _cost_time = 0 for _, _task in model.tasks.items(): _cost_time += z3.If( vars["{}_assigner".format(_task.name)] == model.get_assigner_id( _person_name), _task.length, 0) #solver.add(vars["min"] >= _cost_time * (1 / _person.energy)) solver.add(vars["min"] / (1 / _person.energy) >= _cost_time)
def invariants(self): #TODO: Implement with rotation! one_rotation = zu.exactly_one(self._d0, self._d90, self._d180, self._d270) states = z3.If(z3.Or(self._d0, self._d180), z3.And(self._horiz_var == self._width, self._vert_var == self._height), z3.And(self._horiz_var == self._height, self._vert_var == self._width)) on_fab = z3.And(self._x >= 0, self._x + self._horiz_var <= self.fabric.cols, self._y >= 0, self._y + self._vert_var <= self.fabric.rows) return z3.And(one_rotation, states, on_fab)
def __init__(self, bv_size): super().__init__('bvcomp', 2, (exprtypes.BitVectorType(bv_size), exprtypes.BitVectorType(bv_size)), exprtypes.BitVectorType(1)) self.smt_function = lambda a, b: z3.If(a == b, z3.BitVecVal(1, 1), z3.BitVecVal(0, 1)) self.eval_children = lambda a, b: a.bvcomp(b) self.commutative = True self.associative = True
def filter(self, theta) -> "Table": new_table = Table(self.universe, self.columns, {}) for tup, count in self.counts.items(): new_table.counts[tup] = z3.If(theta(**dict(tup)), count, 0) # if theta(**dict(tup)): # new_table.counts[tup] = count # else: # new_table.counts[tup] = 0 return new_table
def do_WEQ(op, stack, state): reg = stack.pop() val, = pop_values(stack, state) tmp = prepare(state.registers[reg]) if state.condition != None: val = z3.If(state.condition, val, tmp) state.registers.weak_set(reg, val)
def term_to_z3(term): if ivy_logic.is_boolean(term): return formula_to_z3_int(term) if not term.args: if isinstance(term, ivy_logic.Variable): sorted = hasattr(term, 'sort') sksym = term.rep + ':' + str(term.sort) if sorted else term.rep res = z3_constants.get(sksym) if res is not None: return res # print str(term.sort) sig = lookup_native(term.sort, sorts, "sort") if sorted else S if sig == None: sig = term.sort.to_z3() # if sorted: # print type(term.sort) # print term.sort # print type(sksym) # print sksym # print sig res = z3.Const(sksym, sig) z3_constants[sksym] = res return res res = z3_constants.get(term.rep) if res is None: # if isinstance(term.rep,str): # print "{} : {}".format(term,term.rep) if term.is_numeral(): res = numeral_to_z3(term.rep) elif ivy_logic.is_enumerated( term) and ivy_logic.is_interpreted_sort(term.sort): res = enumerated_to_numeral(term) else: iso = term.rep.sort # TODO: this is dangerous sig = iso.to_z3() if iso is not None else S # print "term: {}, iso : {}, sig = {}".format(term,iso,sig) res = z3.Const(term.rep.name, sig) z3_constants[term.rep] = res elif isinstance(term, ivy_logic.Ite): return z3.If(formula_to_z3_int(term.args[0]), term_to_z3(term.args[1]), term_to_z3(term.args[2])) else: if not hasattr(term, 'rep'): print term print term.lineno fun = z3_functions.get(term.rep) if fun is None: fun = lookup_native(term.rep, functions, "function") if fun is None: sig = term.rep.sort.to_z3() fun = z3.Function(term.rep.name, *sig) z3_functions[term.rep] = fun args = [term_to_z3(arg) for arg in term.args] res = apply_z3_func(fun, args) return res
def __cast_to_numb__(self, reference): self.__add_assume__(None) if isinstance(reference, z3.BoolRef): return z3.If(reference, 1, 0) elif isinstance(reference, z3.BitVecRef) or isinstance( reference, z3.BitVecNumRef): return z3.BV2Int(reference, True) else: return reference
def _idivC(self, num, den): """Divide (signed) @num by @den (z3 values) as C would See modint.__div__ for implementation choice """ result_sign = z3.If(num * den >= 0, z3.BitVecVal(1, num.size()), z3.BitVecVal(-1, num.size()), ) return z3.UDiv(self._abs(num), self._abs(den)) * result_sign
def substitute_taint(z3_expr, taints): decl = z3_expr.decl() if decl.kind() == z3.Z3_OP_ITE: # we need to differentiate in the case of ite statements cond_expr = z3_expr.children()[0] then_expr = z3_expr.children()[1] else_expr = z3_expr.children()[2] cond_expr, _ = substitute_taint(cond_expr, taints) then_expr, then_has_undefined = substitute_taint(then_expr, taints) else_expr, else_has_undefined = substitute_taint(else_expr, taints) if then_has_undefined and else_has_undefined: # both possibilities are tainted, replace taint = z3.FreshConst(then_expr.sort(), "taint") taints.append(taint) return taint, True # return the updated ite statement return z3.If(cond_expr, then_expr, else_expr), False if decl.kind() == z3.Z3_OP_DT_CONSTRUCTOR: # datatyperefs are not fully replaced, only their members child_list = z3_expr.children() for idx, child in enumerate(child_list): child, has_undefined = substitute_taint(child, taints) if has_undefined: # variabled is tainted, replace child = z3.FreshConst(child.sort(), "taint") taints.add(child) # members might also have changed, so update child_list[idx] = child return decl(*child_list), False if z3.is_const(z3_expr): # check if variable if not z3.z3util.is_expr_val(z3_expr) and str(z3_expr) == "undefined": # the expression is tainted replace it taint = z3.FreshConst(z3_expr.sort(), "taint") taints.add(taint) return taint, True return z3_expr, False child_list = z3_expr.children() for idx, child in enumerate(child_list): # iterate through members of the expr # replace entire expression if one member is tainted child, has_undefined = substitute_taint(child, taints) if has_undefined: # the expression is tainted replace it taint = z3.FreshConst(z3_expr.sort(), "taint") taints.add(taint) return taint, has_undefined # members might also have changed, so update child_list[idx] = child if decl.kind() == z3.Z3_OP_AND: return z3.And(*child_list), False if decl.kind() == z3.Z3_OP_OR: return z3.Or(*child_list), False return decl(*child_list), False
def walk_ite(self, formula, args): i = args[0] t = args[1] e = args[2] if self._get_type(formula) == types.BOOL: return z3.And(z3.Implies(i, t), z3.Implies(z3.Not(i), e)) else: return z3.If(i, t, e)
def do_B(op, stack, state): bits, = pop_values(stack, state) mask = genmask(bits & 0x3f) old = state.esil["old"] cur = state.esil["cur"] bf = z3.ULT((old & mask), (cur & mask)) #print(bits, mask, z3.simplify(bf)) stack.append(z3.If(bf, ONE, ZERO))
def z3_in_range_of(self, x_coord: int, y_coord: int, z_coord: int) -> z3.If: return z3.If( (zabs(x_coord - self.location.x_coord) + zabs(y_coord - self.location.y_coord) + zabs(z_coord - self.location.z_coord)) <= self.radius, 1, 0, )