def test_get_logic_in_is_sat(self): varA = Symbol("A", BOOL) varB = Symbol("B", BOOL) f = And(varA, Not(varB)) self.assertSat(f, logic=AUTO)
def comb_attack(self): # dis generator solver_name = 'yices' solver_obf = Solver(name=solver_name) solver_key = Solver(name=solver_name) self.solver_oracle = Solver(name=solver_name) attack_formulas = FormulaGenerator(self.oracle_cir, self.obf_cir) f = attack_formulas.dip_gen_ckt # f = simplify(f) solver_obf.add_assertion(f) f = attack_formulas.key_inequality_ckt # f = simplify(f) solver_obf.add_assertion(f) for l in self.oracle_cir.wire_objs: self.solver_oracle.add_assertion(l.formula) dip_list = [] stateful_keys = [] iteration = 0 while 1: # query dip generator if solver_obf.solve(): dip_formula = [] dip_boolean = [] for l in self.oracle_cir.input_wires: s = Symbol(l.name) if solver_obf.get_py_value(s): dip_formula.append(s) dip_boolean.append(TRUE()) else: dip_formula.append(Not(s)) dip_boolean.append(FALSE()) logging.info(dip_formula) # query oracle dip_out = self.query_oracle(dip_formula) logging.info(dip_out) # check for stateful condition if dip_formula in dip_list: # ban stateful key logging.info("found a repeated dip!") # check outputs for both keys key = None for l in self.obf_cir.output_wires: s1 = Symbol(l.name + '@dc1') s2 = Symbol(l.name + '@dc2') if solver_obf.get_py_value( s1) != solver_obf.get_py_value(s2): if solver_obf.get_py_value( s1) != self.solver_oracle.get_py_value( Symbol(l.name)): key = '0' else: key = '1' break if key == None: logging.critical( 'something is wrong when banning keys') # find assigned keys key_list = [] for l in self.obf_cir.key_wires: k = Symbol(l.name + '_' + key) if solver_obf.get_py_value(k): key_list.append(k) else: key_list.append(Not(k)) stateful_keys.append(key_list) # ban the stateful key f = Not(And(key_list)) solver_obf.add_assertion(f) solver_key.add_assertion(f) if len(stateful_keys) % 5000 == 0: logging.warning('current stateful keys: {}'.format( len(stateful_keys))) continue else: dip_list.append(dip_formula) # add dip checker f = [] f.append( attack_formulas.gen_dip_chk(iteration * 2, '_0', dip_boolean)) f.append( attack_formulas.gen_dip_chk(iteration * 2 + 1, '_1', dip_boolean)) for i in range(len(self.obf_cir.output_wires)): l = self.obf_cir.output_wires[i].name f.append( And( Iff(dip_out[i], Symbol(l + '@{}'.format(iteration * 2))), Iff(dip_out[i], Symbol(l + '@{}'.format(iteration * 2 + 1))))) f = And(f) solver_obf.add_assertion(f) solver_key.add_assertion(f) iteration += 1 logging.warning('iteration: {}'.format(iteration)) else: logging.warning('print keys') logging.warning('stateful keys: {}'.format(len(stateful_keys))) if solver_key.solve(): key = '' for l in self.obf_cir.key_wires: if solver_key.get_py_value(Symbol(l.name + '_0')): key += '1' else: key += '0' print("key=%s" % key) else: logging.critical('key solver returned UNSAT') return
def test_prenex_simple_exists(self): a, b = (Symbol(x) for x in "ab") f = And(b, Exists([b], Implies(a, b))) prenex = prenex_normal_form(f) self.assertTrue(prenex.is_exists()) self.assertValid(Iff(f, prenex), logic=BOOL)
if solver.solve([ Or(get_win_formula(Cell.o)), Equals(get_board_sum(), BV(x_turns * x_val + o_turns * o_val, VECT_WIDTH)) ]): logger.debug("found a way for o to win") result = pick_new_move(Cell.o) play_move(Cell.o, result[0], result[1]) logger.info("o wins") print_board() exit(0) # try to block x next turn (x_turns+1) after both players have played again elif solver.solve([ Or(get_win_formula(Cell.x)), And(Or(find_all_moves(Cell.o)), Or(find_all_moves(Cell.x))), Equals(get_board_sum(), BV((x_turns + 1) * x_val + o_turns * o_val, VECT_WIDTH)) ]): logger.debug( "found a way to block x winning next time with board val %d" % ((x_turns + 1) * x_val + o_turns * o_val)) if args.verbose: print_board() result = pick_new_move( Cell.x) # get the winning move for x and play for o play_move(Cell.o, result[0], result[1]) # otherwise find any next move for o elif solver.solve([ Or(find_all_moves(Cell.o)),
# We create a map from BitVectors to Reals, so that each bitvector # value (interpreted as unary number) is equal to the Real # value. # # The map is represented by an Array of type BV8 -> Real map_type = ArrayType(BV8, REAL) my_map = Symbol("my_map", map_type) # Fill-up the map, by defining all 256 values: for i in range(0, 255): my_map = my_map.Store(BV(i, 8), Real(i)) # We want to find find a value for which our relation does not work. # In other words, we ask if there is a value for the bitvector # s.t. the corresponding value in the array is different from the # unary interpretation of the bitvector. bv_var = Symbol("bv", BV8) int_var = Symbol("int", INT) real_var = Symbol("real", REAL) f = And( # Convert the BV into INT int_var.Equals(BVToNatural(bv_var)), # Convert the INT into REAL real_var.Equals(ToReal(int_var)), # Compare the value stored in the map with the REAL value my_map.Select(bv_var).NotEquals(real_var) ) print(get_model(f)) # Indeed our range only gets up to 254!!!
def test_forall(self): f = ForAll([self.x], And(self.x, self.y)) g = qelim(f, solver_name="shannon") g = g.simplify() self.assertEqual(g, FALSE())
def generate_HTS(self, module, modulesdic): hts = HTS(module.name) ts = TS("TS %s" % module.name) init = [] trans = [] invar = [] params = [] sparser = StringParser() (vars, states, inputs, outputs) = self._collect_sub_variables(module, modulesdic, path=[], varlist=[]) for var in vars: ts.add_var(self._define_var(var, module.name)) for var in states: ts.add_state_var(self._define_var(var, module.name)) for var in inputs: ts.add_input_var(self._define_var(var, module.name)) for var in outputs: ts.add_output_var(self._define_var(var, module.name)) self._check_parameters(module, modulesdic, ts.vars) for par in module.pars: hts.add_param( self._define_var((par[0], tuple(par[1:])), module.name)) for init_s in module.init: formula = sparser.parse_formula(quote_names(init_s, module.name), False) init.append(formula) for invar_s in module.invar: formula = sparser.parse_formula(quote_names(invar_s, module.name), False) invar.append(formula) for trans_s in module.trans: formula = sparser.parse_formula(quote_names(trans_s, module.name), False) trans.append(formula) for sub in module.subs: hts.add_sub(sub[0], self.generate_HTS(modulesdic[sub[1]], modulesdic), tuple([v[0] for v in sub[2]])) ts.init = And(init) ts.invar = And(invar) ts.trans = And(trans) hts.add_ts(ts) return hts
from pysmt.shortcuts import And, Symbol, LE, GE, Int, Equals, Plus, Times, is_sat from pysmt.typing import INT hello = [Symbol(s, INT) for s in "hello"] world = [Symbol(s, INT) for s in "world"] letters = set(hello + world) domains = And([And(LE(Int(1), l), GE(Int(10), l)) for l in letters]) sum_hello = Plus(hello) sum_world = Plus(world) problem = And(Equals(sum_hello, sum_world), Equals(sum_hello, Int(25))) formula = And(domains, problem) print "Serialization of the formula:" print formula print "Checking Satisfiability:" print is_sat(formula)
def compile_sts(self, name, params): sparser = StringParser() in_port, max_val, c_push, c_pop = list(params) max_val = int(max_val) if type(c_push) == str: c_push = sparser.parse_formula(c_push) if type(c_pop) == str: c_pop = sparser.parse_formula(c_pop) tracking = Symbol("%s.tracking" % name, BOOL) end = Symbol("%s.end" % name, BOOL) done = Symbol("%s.done" % name, BOOL) packet = Symbol("%s.packet" % name, BVType(in_port.symbol_type().width)) max_width = math.ceil(math.log(max_val) / math.log(2)) max_bvval = BV(max_val, max_width) zero = BV(0, max_width) one = BV(1, max_width) count = Symbol("%s.count" % name, BVType(max_width)) size = Symbol("%s.size" % name, BVType(max_width)) pos_c_push = BV2B(c_push) neg_c_push = Not(BV2B(c_push)) pos_c_pop = BV2B(c_pop) neg_c_pop = Not(BV2B(c_pop)) init = [] trans = [] invar = [] # INIT DEFINITION # # count = 0 init.append(EqualsOrIff(count, BV(0, max_width))) # tracking = False init.append(EqualsOrIff(tracking, FALSE())) # size = 0 init.append(EqualsOrIff(size, BV(0, max_width))) # end = false init.append(EqualsOrIff(end, FALSE())) # INVAR DEFINITION # # !done -> (end = (tracking & (size = count))) invar.append( Implies(Not(done), EqualsOrIff(end, And(tracking, EqualsOrIff(size, count))))) # count <= size invar.append(BVULE(count, size)) # count <= maxval invar.append(BVULE(count, max_bvval)) # size <= maxval invar.append(BVULE(size, max_bvval)) # done -> (end <-> False); invar.append(Implies(done, EqualsOrIff(end, FALSE()))) # done -> (count = 0_8); invar.append(Implies(done, EqualsOrIff(count, BV(0, max_width)))) # done -> (size = 0_8); invar.append(Implies(done, EqualsOrIff(size, BV(0, max_width)))) # done -> (packet = 0_8); invar.append( Implies(done, EqualsOrIff(packet, BV(0, in_port.symbol_type().width)))) # TRANS DEFINITION # # (!end & !done) -> next(!done); trans.append(Implies(And(Not(end), Not(done)), TS.to_next(Not(done)))) # end -> next(done); trans.append(Implies(end, TS.to_next(done))) # done -> next(done); trans.append(Implies(done, TS.to_next(done))) # tracking -> next(tracking); trans.append( Implies(Not(done), Implies(tracking, TS.to_next(tracking)))) # tracking -> (next(packet) = packet); trans.append( Implies(Not(done), Implies(tracking, EqualsOrIff(TS.to_next(packet), packet)))) # !tracking & next(tracking) -> c_push; trans.append( Implies( Not(done), Implies(And(Not(tracking), TS.to_next(tracking)), pos_c_push))) # (c_push & next(tracking)) -> ((packet = in) & (next(packet) = in); trans.append( Implies( Not(done), Implies( And(pos_c_push, TS.to_next(tracking)), And(EqualsOrIff(packet, in_port), EqualsOrIff(TS.to_next(packet), in_port))))) # (c_push & !c_pop & tracking) -> (next(count) = (count + 1_8)); trans.append( Implies( Not(done), Implies( And(pos_c_push, neg_c_pop, tracking), EqualsOrIff(TS.to_next(count), BVAdd(count, BV(1, max_width)))))) # (c_push & size < maxval) -> (next(size) = (size + 1_8)); trans.append( Implies( Not(done), Implies( And(pos_c_push, BVULT(size, max_bvval)), EqualsOrIff(TS.to_next(size), BVAdd(size, BV(1, max_width)))))) # (c_pop & size > 0) -> (next(size) = (size - 1_8)); trans.append( Implies( Not(done), Implies( And(pos_c_pop, BVUGT(size, zero)), EqualsOrIff(TS.to_next(size), BVSub(size, BV(1, max_width)))))) # (!(c_push | c_pop)) -> (next(count) = count); trans.append( Implies( Not(done), Implies(Not(Or(pos_c_push, pos_c_pop)), EqualsOrIff(count, TS.to_next(count))))) # ((c_push | c_pop) & !tracking) -> (next(count) = count); trans.append( Implies( Not(done), Implies(And(Or(pos_c_push, pos_c_pop), Not(tracking)), EqualsOrIff(count, TS.to_next(count))))) # (c_push & size = maxval) -> (next(size) = size); trans.append( Implies( Not(done), Implies(And(pos_c_push, EqualsOrIff(size, max_bvval)), EqualsOrIff(TS.to_next(size), size)))) # (!(c_push | c_pop)) -> (next(size) = size); trans.append( Implies( Not(done), Implies(Not(Or(pos_c_push, pos_c_pop)), EqualsOrIff(size, TS.to_next(size))))) # (!(c_push | c_pop)) -> (next(count) = count); trans.append( Implies( Not(done), Implies(Not(Or(pos_c_push, pos_c_pop)), EqualsOrIff(count, TS.to_next(count))))) # (c_pop & size = 0) -> (next(size) = 0); trans.append( Implies( Not(done), Implies(And(pos_c_pop, EqualsOrIff(size, zero)), EqualsOrIff(TS.to_next(size), zero)))) # (!c_push) -> (next(count) = count); trans.append( Implies(Not(done), Implies(neg_c_push, EqualsOrIff(TS.to_next(count), count)))) init = And(init) invar = And(invar) trans = And(trans) ts = TS() ts.vars, ts.init, ts.invar, ts.trans = set( [tracking, end, packet, count, size]), init, invar, trans return ts
def get_full_example_formulae(environment=None): """Return a list of Examples using the given environment.""" if environment is None: environment = get_env() with environment: x = Symbol("x", BOOL) y = Symbol("y", BOOL) p = Symbol("p", INT) q = Symbol("q", INT) r = Symbol("r", REAL) s = Symbol("s", REAL) aii = Symbol("aii", ARRAY_INT_INT) ari = Symbol("ari", ArrayType(REAL, INT)) arb = Symbol("arb", ArrayType(REAL, BV8)) abb = Symbol("abb", ArrayType(BV8, BV8)) nested_a = Symbol("a_arb_aii", ArrayType(ArrayType(REAL, BV8), ARRAY_INT_INT)) rf = Symbol("rf", FunctionType(REAL, [REAL, REAL])) rg = Symbol("rg", FunctionType(REAL, [REAL])) ih = Symbol("ih", FunctionType(INT, [REAL, INT])) ig = Symbol("ig", FunctionType(INT, [INT])) bf = Symbol("bf", FunctionType(BOOL, [BOOL])) bg = Symbol("bg", FunctionType(BOOL, [BOOL])) bv3 = Symbol("bv3", BVType(3)) bv8 = Symbol("bv8", BV8) bv16 = Symbol("bv16", BV16) result = [ # Formula, is_valid, is_sat, is_qf Example(hr="(x & y)", expr=And(x, y), is_valid=False, is_sat=True, logic=pysmt.logics.QF_BOOL), Example(hr="(x <-> y)", expr=Iff(x, y), is_valid=False, is_sat=True, logic=pysmt.logics.QF_BOOL), Example(hr="((x | y) & (! (x | y)))", expr=And(Or(x, y), Not(Or(x, y))), is_valid=False, is_sat=False, logic=pysmt.logics.QF_BOOL), Example(hr="(x & (! y))", expr=And(x, Not(y)), is_valid=False, is_sat=True, logic=pysmt.logics.QF_BOOL), Example(hr="(False -> True)", expr=Implies(FALSE(), TRUE()), is_valid=True, is_sat=True, logic=pysmt.logics.QF_BOOL), Example(hr="((x | y) & (! (x | y)))", expr=And(Or(x, y), Not(Or(x, y))), is_valid=False, is_sat=False, logic=pysmt.logics.QF_BOOL), # # LIA # Example(hr="((q < p) & (x -> y))", expr=And(GT(p, q), Implies(x, y)), is_valid=False, is_sat=True, logic=pysmt.logics.QF_IDL), Example(hr="(((p + q) = 5) & (q < p))", expr=And(Equals(Plus(p, q), Int(5)), GT(p, q)), is_valid=False, is_sat=True, logic=pysmt.logics.QF_LIA), Example(hr="((q <= p) | (p <= q))", expr=Or(GE(p, q), LE(p, q)), is_valid=True, is_sat=True, logic=pysmt.logics.QF_IDL), Example(hr="(! (p < (q * 2)))", expr=Not(LT(p, Times(q, Int(2)))), is_valid=False, is_sat=True, logic=pysmt.logics.QF_LIA), Example(hr="(p < (p - (5 - 2)))", expr=GT(Minus(p, Minus(Int(5), Int(2))), p), is_valid=False, is_sat=False, logic=pysmt.logics.QF_IDL), Example(hr="((x ? 7 : ((p + -1) * 3)) = q)", expr=Equals( Ite(x, Int(7), Times(Plus(p, Int(-1)), Int(3))), q), is_valid=False, is_sat=True, logic=pysmt.logics.QF_LIA), Example(hr="(p < (q + 1))", expr=LT(p, Plus(q, Int(1))), is_valid=False, is_sat=True, logic=pysmt.logics.QF_LIA), # # LRA # Example(hr="((s < r) & (x -> y))", expr=And(GT(r, s), Implies(x, y)), is_valid=False, is_sat=True, logic=pysmt.logics.QF_RDL), Example(hr="(((r + s) = 28/5) & (s < r))", expr=And(Equals(Plus(r, s), Real(Fraction("5.6"))), GT(r, s)), is_valid=False, is_sat=True, logic=pysmt.logics.QF_LRA), Example(hr="((s <= r) | (r <= s))", expr=Or(GE(r, s), LE(r, s)), is_valid=True, is_sat=True, logic=pysmt.logics.QF_RDL), Example(hr="(! ((r * 2.0) < (s * 2.0)))", expr=Not(LT(Div(r, Real((1, 2))), Times(s, Real(2)))), is_valid=False, is_sat=True, logic=pysmt.logics.QF_LRA), Example(hr="(! (r < (r - (5.0 - 2.0))))", expr=Not(GT(Minus(r, Minus(Real(5), Real(2))), r)), is_valid=True, is_sat=True, logic=pysmt.logics.QF_RDL), Example(hr="((x ? 7.0 : ((s + -1.0) * 3.0)) = r)", expr=Equals( Ite(x, Real(7), Times(Plus(s, Real(-1)), Real(3))), r), is_valid=False, is_sat=True, logic=pysmt.logics.QF_LRA), # # EUF # Example(hr="(bf(x) <-> bg(x))", expr=Iff(Function(bf, (x, )), Function(bg, (x, ))), is_valid=False, is_sat=True, logic=pysmt.logics.QF_UF), Example(hr="(rf(5.0, rg(r)) = 0.0)", expr=Equals(Function(rf, (Real(5), Function(rg, (r, )))), Real(0)), is_valid=False, is_sat=True, logic=pysmt.logics.QF_UFLRA), Example(hr="((rg(r) = (5.0 + 2.0)) <-> (rg(r) = 7.0))", expr=Iff(Equals(Function(rg, [r]), Plus(Real(5), Real(2))), Equals(Function(rg, [r]), Real(7))), is_valid=True, is_sat=True, logic=pysmt.logics.QF_UFLRA), Example( hr="((r = (s + 1.0)) & (rg(s) = 5.0) & (rg((r - 1.0)) = 7.0))", expr=And([ Equals(r, Plus(s, Real(1))), Equals(Function(rg, [s]), Real(5)), Equals(Function(rg, [Minus(r, Real(1))]), Real(7)) ]), is_valid=False, is_sat=False, logic=pysmt.logics.QF_UFLRA), # # BV # Example(hr="((1_32 & 0_32) = 0_32)", expr=Equals(BVAnd(BVOne(32), BVZero(32)), BVZero(32)), is_valid=True, is_sat=True, logic=pysmt.logics.QF_BV), Example(hr="((! 2_3) = 5_3)", expr=Equals(BVNot(BV("010")), BV("101")), is_valid=True, is_sat=True, logic=pysmt.logics.QF_BV), Example(hr="((! bv3) = 5_3)", expr=Equals(BVNot(bv3), BV("101")), is_valid=False, is_sat=True, logic=pysmt.logics.QF_BV), Example(hr="((7_3 xor 0_3) = 0_3)", expr=Equals(BVXor(BV("111"), BV("000")), BV("000")), is_valid=False, is_sat=False, logic=pysmt.logics.QF_BV), Example(hr="((7_3 xor bv3) = (6_3 xor bv3))", expr=Equals(BVXor(BV("111"), bv3), BVXor(BV("110"), bv3)), is_valid=False, is_sat=False, logic=pysmt.logics.QF_BV), Example(hr="((bv8::bv8) u< 0_16)", expr=BVULT(BVConcat(bv8, bv8), BVZero(16)), is_valid=False, is_sat=False, logic=pysmt.logics.QF_BV), Example(hr="((bv8::bv8) u< (bv8::9_8))", expr=BVULT(BVConcat(bv8, bv8), BVConcat(bv8, BV(9, 8))), is_valid=False, is_sat=True, logic=pysmt.logics.QF_BV), Example(hr="(1_32[0:7] = 1_8)", expr=Equals(BVExtract(BVOne(32), end=7), BVOne(8)), is_valid=True, is_sat=True, logic=pysmt.logics.QF_BV), Example(hr="(0_8 u< (((bv8 + 1_8) * 5_8) u/ 5_8))", expr=BVUGT( BVUDiv(BVMul(BVAdd(bv8, BVOne(8)), BV(5, width=8)), BV(5, width=8)), BVZero(8)), is_valid=False, is_sat=True, logic=pysmt.logics.QF_BV), Example(hr="(0_16 u<= bv16)", expr=BVUGE(bv16, BVZero(16)), is_valid=True, is_sat=True, logic=pysmt.logics.QF_BV), Example(hr="(0_16 s<= bv16)", expr=BVSGE(bv16, BVZero(16)), is_valid=False, is_sat=True, logic=pysmt.logics.QF_BV), Example( hr="((0_32 u< (5_32 u% 2_32)) & ((5_32 u% 2_32) u<= 1_32))", expr=And( BVUGT(BVURem(BV(5, width=32), BV(2, width=32)), BVZero(32)), BVULE(BVURem(BV(5, width=32), BV(2, width=32)), BVOne(32))), is_valid=True, is_sat=True, logic=pysmt.logics.QF_BV), Example(hr="((((1_32 + (- 1_32)) << 1_32) >> 1_32) = 1_32)", expr=Equals( BVLShr(BVLShl(BVAdd(BVOne(32), BVNeg(BVOne(32))), 1), 1), BVOne(32)), is_valid=False, is_sat=False, logic=pysmt.logics.QF_BV), Example(hr="((1_32 - 1_32) = 0_32)", expr=Equals(BVSub(BVOne(32), BVOne(32)), BVZero(32)), is_valid=True, is_sat=True, logic=pysmt.logics.QF_BV), # Rotations Example(hr="(((1_32 ROL 1) ROR 1) = 1_32)", expr=Equals(BVRor(BVRol(BVOne(32), 1), 1), BVOne(32)), is_valid=True, is_sat=True, logic=pysmt.logics.QF_BV), Example(hr="((bv16 ROL 1) = (bv16 ROR 2))", expr=Equals(BVRol(bv16, 1), BVRor(bv16, 2)), is_valid=False, is_sat=True, logic=pysmt.logics.QF_BV), # Extensions Example(hr="((0_5 ZEXT 11) = (0_1 SEXT 15))", expr=Equals(BVZExt(BVZero(5), 11), BVSExt(BVZero(1), 15)), is_valid=True, is_sat=True, logic=pysmt.logics.QF_BV), Example(hr="((bv8 ZEXT 19) = (bv16 SEXT 11))", expr=Equals(BVZExt(bv8, 19), BVSExt(bv16, 11)), is_valid=False, is_sat=True, logic=pysmt.logics.QF_BV), Example(hr="((bv16 - bv16) = 0_16)", expr=Equals(BVSub(bv16, bv16), BVZero(16)), is_valid=True, is_sat=True, logic=pysmt.logics.QF_BV), Example(hr="((bv16 - bv16)[0:7] = bv8)", expr=Equals(BVExtract(BVSub(bv16, bv16), 0, 7), bv8), is_valid=False, is_sat=True, logic=pysmt.logics.QF_BV), Example(hr="((bv16[0:7] bvcomp bv8) = 1_1)", expr=Equals(BVComp(BVExtract(bv16, 0, 7), bv8), BVOne(1)), is_valid=False, is_sat=True, logic=pysmt.logics.QF_BV), Example(hr="((bv16 bvcomp bv16) = 0_1)", expr=Equals(BVComp(bv16, bv16), BVZero(1)), is_valid=False, is_sat=False, logic=pysmt.logics.QF_BV), Example(hr="(bv16 s< bv16)", expr=BVSLT(bv16, bv16), is_valid=False, is_sat=False, logic=pysmt.logics.QF_BV), Example(hr="(bv16 s< 0_16)", expr=BVSLT(bv16, BVZero(16)), is_valid=False, is_sat=True, logic=pysmt.logics.QF_BV), Example(hr="((bv16 s< 0_16) | (0_16 s<= bv16))", expr=Or(BVSGT(BVZero(16), bv16), BVSGE(bv16, BVZero(16))), is_valid=True, is_sat=True, logic=pysmt.logics.QF_BV), Example(hr="(bv16 u< bv16)", expr=BVULT(bv16, bv16), is_valid=False, is_sat=False, logic=pysmt.logics.QF_BV), Example(hr="(bv16 u< 0_16)", expr=BVULT(bv16, BVZero(16)), is_valid=False, is_sat=False, logic=pysmt.logics.QF_BV), Example(hr="((bv16 | 0_16) = bv16)", expr=Equals(BVOr(bv16, BVZero(16)), bv16), is_valid=True, is_sat=True, logic=pysmt.logics.QF_BV), Example(hr="((bv16 | 5_16) = bv16)", expr=Equals(BVOr(bv16, BV(5, 16)), bv16), is_valid=False, is_sat=True, logic=pysmt.logics.QF_BV), Example(hr="((bv16 & 0_16) = 0_16)", expr=Equals(BVAnd(bv16, BVZero(16)), BVZero(16)), is_valid=True, is_sat=True, logic=pysmt.logics.QF_BV), Example(hr="((bv16 & 7_16) = 0_16)", expr=Equals(BVAnd(bv16, BV(7, 16)), BVZero(16)), is_valid=False, is_sat=True, logic=pysmt.logics.QF_BV), Example(hr="((0_16 s< bv16) & ((bv16 s/ 65535_16) s< 0_16))", expr=And(BVSLT(BVZero(16), bv16), BVSLT(BVSDiv(bv16, SBV(-1, 16)), BVZero(16))), is_valid=False, is_sat=True, logic=pysmt.logics.QF_BV), Example(hr="((0_16 s< bv16) & ((bv16 s% 1_16) s< 0_16))", expr=And(BVSLT(BVZero(16), bv16), BVSLT(BVSRem(bv16, BVOne(16)), BVZero(16))), is_valid=False, is_sat=False, logic=pysmt.logics.QF_BV), Example(hr="((bv16 u% 1_16) = 0_16)", expr=Equals(BVURem(bv16, BVOne(16)), BVZero(16)), is_valid=True, is_sat=True, logic=pysmt.logics.QF_BV), Example(hr="((bv16 u% bv16) = 0_16)", expr=Equals(BVURem(bv16, bv16), BVZero(16)), is_valid=True, is_sat=True, logic=pysmt.logics.QF_BV), Example(hr="((bv16 s% 1_16) = 0_16)", expr=Equals(BVSRem(bv16, BVOne(16)), BVZero(16)), is_valid=True, is_sat=True, logic=pysmt.logics.QF_BV), Example(hr="((bv16 s% bv16) = 0_16)", expr=Equals(BVSRem(bv16, bv16), BVZero(16)), is_valid=True, is_sat=True, logic=pysmt.logics.QF_BV), Example(hr="((bv16 s% (- 1_16)) = 0_16)", expr=Equals(BVSRem(bv16, BVNeg(BVOne(16))), BVZero(16)), is_valid=True, is_sat=True, logic=pysmt.logics.QF_BV), Example(hr="(bv16 s< (- bv16))", expr=BVSGT(BVNeg(bv16), bv16), is_valid=False, is_sat=True, logic=pysmt.logics.QF_BV), Example(hr="((bv16 a>> 0_16) = bv16)", expr=Equals(BVAShr(bv16, BVZero(16)), bv16), is_valid=True, is_sat=True, logic=pysmt.logics.QF_BV), Example( hr="((0_16 s<= bv16) & ((bv16 a>> 1_16) = (bv16 >> 1_16)))", expr=And( BVSLE(BVZero(16), bv16), Equals(BVAShr(bv16, BVOne(16)), BVLShr(bv16, BVOne(16)))), is_valid=False, is_sat=True, logic=pysmt.logics.QF_BV), # # Quantification # Example(hr="(forall y . (x -> y))", expr=ForAll([y], Implies(x, y)), is_valid=False, is_sat=True, logic=pysmt.logics.BOOL), Example(hr="(forall p, q . ((p + q) = 0))", expr=ForAll([p, q], Equals(Plus(p, q), Int(0))), is_valid=False, is_sat=False, logic=pysmt.logics.LIA), Example( hr="(forall r, s . (((0.0 < r) & (0.0 < s)) -> ((r - s) < r)))", expr=ForAll([r, s], Implies(And(GT(r, Real(0)), GT(s, Real(0))), (LT(Minus(r, s), r)))), is_valid=True, is_sat=True, logic=pysmt.logics.LRA), Example(hr="(exists x, y . (x -> y))", expr=Exists([x, y], Implies(x, y)), is_valid=True, is_sat=True, logic=pysmt.logics.BOOL), Example(hr="(exists p, q . ((p + q) = 0))", expr=Exists([p, q], Equals(Plus(p, q), Int(0))), is_valid=True, is_sat=True, logic=pysmt.logics.LIA), Example(hr="(exists r . (forall s . (r < (r - s))))", expr=Exists([r], ForAll([s], GT(Minus(r, s), r))), is_valid=False, is_sat=False, logic=pysmt.logics.LRA), Example(hr="(forall r . (exists s . (r < (r - s))))", expr=ForAll([r], Exists([s], GT(Minus(r, s), r))), is_valid=True, is_sat=True, logic=pysmt.logics.LRA), Example(hr="(x & (forall r . ((r + s) = 5.0)))", expr=And(x, ForAll([r], Equals(Plus(r, s), Real(5)))), is_valid=False, is_sat=False, logic=pysmt.logics.LRA), Example(hr="(exists x . ((x <-> (5.0 < s)) & (s < 3.0)))", expr=Exists([x], (And(Iff(x, GT(s, Real(5))), LT(s, Real(3))))), is_valid=False, is_sat=True, logic=pysmt.logics.LRA), # # UFLIRA # Example(hr="((p < ih(r, q)) & (x -> y))", expr=And(GT(Function(ih, (r, q)), p), Implies(x, y)), is_valid=False, is_sat=True, logic=pysmt.logics.QF_UFLIRA), Example( hr= "(((p - 3) = q) -> ((p < ih(r, (q + 3))) | (ih(r, p) <= p)))", expr=Implies( Equals(Minus(p, Int(3)), q), Or(GT(Function(ih, (r, Plus(q, Int(3)))), p), LE(Function(ih, (r, p)), p))), is_valid=True, is_sat=True, logic=pysmt.logics.QF_UFLIRA), Example( hr= "(((ToReal((p - 3)) = r) & (ToReal(q) = r)) -> ((p < ih(ToReal((p - 3)), (q + 3))) | (ih(r, p) <= p)))", expr=Implies( And(Equals(ToReal(Minus(p, Int(3))), r), Equals(ToReal(q), r)), Or( GT( Function( ih, (ToReal(Minus(p, Int(3))), Plus(q, Int(3)))), p), LE(Function(ih, (r, p)), p))), is_valid=True, is_sat=True, logic=pysmt.logics.QF_UFLIRA), Example( hr= "(! (((ToReal((p - 3)) = r) & (ToReal(q) = r)) -> ((p < ih(ToReal((p - 3)), (q + 3))) | (ih(r, p) <= p))))", expr=Not( Implies( And(Equals(ToReal(Minus(p, Int(3))), r), Equals(ToReal(q), r)), Or( GT( Function(ih, (ToReal(Minus( p, Int(3))), Plus(q, Int(3)))), p), LE(Function(ih, (r, p)), p)))), is_valid=False, is_sat=False, logic=pysmt.logics.QF_UFLIRA), Example( hr= """("Did you know that any string works? #yolo" & "10" & "|#somesolverskeepthe||" & " ")""", expr=And(Symbol("Did you know that any string works? #yolo"), Symbol("10"), Symbol("|#somesolverskeepthe||"), Symbol(" ")), is_valid=False, is_sat=True, logic=pysmt.logics.QF_BOOL), # # Arrays # Example(hr="((q = 0) -> (aii[0 := 0] = aii[0 := q]))", expr=Implies( Equals(q, Int(0)), Equals(Store(aii, Int(0), Int(0)), Store(aii, Int(0), q))), is_valid=True, is_sat=True, logic=pysmt.logics.QF_ALIA), Example(hr="(aii[0 := 0][0] = 0)", expr=Equals(Select(Store(aii, Int(0), Int(0)), Int(0)), Int(0)), is_valid=True, is_sat=True, logic=pysmt.logics.QF_ALIA), Example(hr="((Array{Int, Int}(0)[1 := 1] = aii) & (aii[1] = 0))", expr=And(Equals(Array(INT, Int(0), {Int(1): Int(1)}), aii), Equals(Select(aii, Int(1)), Int(0))), is_valid=False, is_sat=False, logic=pysmt.logics.get_logic_by_name("QF_ALIA*")), Example(hr="((Array{Int, Int}(0)[1 := 3] = aii) & (aii[1] = 3))", expr=And(Equals(Array(INT, Int(0), {Int(1): Int(3)}), aii), Equals(Select(aii, Int(1)), Int(3))), is_valid=False, is_sat=True, logic=pysmt.logics.get_logic_by_name("QF_ALIA*")), Example(hr="((Array{Real, Int}(10) = ari) & (ari[6/5] = 0))", expr=And(Equals(Array(REAL, Int(10)), ari), Equals(Select(ari, Real((6, 5))), Int(0))), is_valid=False, is_sat=False, logic=pysmt.logics.get_logic_by_name("QF_AUFBVLIRA*")), Example( hr= "((Array{Real, Int}(0)[1.0 := 10][2.0 := 20][3.0 := 30][4.0 := 40] = ari) & (! ((ari[0.0] = 0) & (ari[1.0] = 10) & (ari[2.0] = 20) & (ari[3.0] = 30) & (ari[4.0] = 40))))", expr=And( Equals( Array( REAL, Int(0), { Real(1): Int(10), Real(2): Int(20), Real(3): Int(30), Real(4): Int(40) }), ari), Not( And(Equals(Select(ari, Real(0)), Int(0)), Equals(Select(ari, Real(1)), Int(10)), Equals(Select(ari, Real(2)), Int(20)), Equals(Select(ari, Real(3)), Int(30)), Equals(Select(ari, Real(4)), Int(40))))), is_valid=False, is_sat=False, logic=pysmt.logics.get_logic_by_name("QF_AUFBVLIRA*")), Example( hr= "((Array{Real, Int}(0)[1.0 := 10][2.0 := 20][3.0 := 30][4.0 := 40][5.0 := 50] = ari) & (! ((ari[0.0] = 0) & (ari[1.0] = 10) & (ari[2.0] = 20) & (ari[3.0] = 30) & (ari[4.0] = 40) & (ari[5.0] = 50))))", expr=And( Equals( Array( REAL, Int(0), { Real(1): Int(10), Real(2): Int(20), Real(3): Int(30), Real(4): Int(40), Real(5): Int(50) }), ari), Not( And(Equals(Select(ari, Real(0)), Int(0)), Equals(Select(ari, Real(1)), Int(10)), Equals(Select(ari, Real(2)), Int(20)), Equals(Select(ari, Real(3)), Int(30)), Equals(Select(ari, Real(4)), Int(40)), Equals(Select(ari, Real(5)), Int(50))))), is_valid=False, is_sat=False, logic=pysmt.logics.get_logic_by_name("QF_AUFBVLIRA*")), Example( hr= "((a_arb_aii = Array{Array{Real, BV{8}}, Array{Int, Int}}(Array{Int, Int}(7))) -> (a_arb_aii[arb][42] = 7))", expr=Implies( Equals(nested_a, Array(ArrayType(REAL, BV8), Array(INT, Int(7)))), Equals(Select(Select(nested_a, arb), Int(42)), Int(7))), is_valid=True, is_sat=True, logic=pysmt.logics.get_logic_by_name("QF_AUFBVLIRA*")), Example(hr="(abb[bv8 := y_][bv8 := z_] = abb[bv8 := z_])", expr=Equals( Store(Store(abb, bv8, Symbol("y_", BV8)), bv8, Symbol("z_", BV8)), Store(abb, bv8, Symbol("z_", BV8))), is_valid=True, is_sat=True, logic=pysmt.logics.QF_ABV), Example(hr="((r / s) = (r * s))", expr=Equals(Div(r, s), Times(r, s)), is_valid=False, is_sat=True, logic=pysmt.logics.QF_NRA), Example(hr="(2.0 = (r * r))", expr=Equals(Real(2), Times(r, r)), is_valid=False, is_sat=True, logic=pysmt.logics.QF_NRA), Example(hr="((p ^ 2) = 0)", expr=Equals(Pow(p, Int(2)), Int(0)), is_valid=False, is_sat=True, logic=pysmt.logics.QF_NIA), Example(hr="((r ^ 2.0) = 0.0)", expr=Equals(Pow(r, Real(2)), Real(0)), is_valid=False, is_sat=True, logic=pysmt.logics.QF_NRA), Example(hr="((r * r * r) = 25.0)", expr=Equals(Times(r, r, r), Real(25)), is_valid=False, is_sat=True, logic=pysmt.logics.QF_NRA), Example(hr="((5.0 * r * 5.0) = 25.0)", expr=Equals(Times(Real(5), r, Real(5)), Real(25)), is_valid=False, is_sat=True, logic=pysmt.logics.QF_LRA), Example(hr="((p * p * p) = 25)", expr=Equals(Times(p, p, p), Int(25)), is_valid=False, is_sat=False, logic=pysmt.logics.QF_NIA), Example(hr="((5 * p * 5) = 25)", expr=Equals(Times(Int(5), p, Int(5)), Int(25)), is_valid=False, is_sat=True, logic=pysmt.logics.QF_LIA), Example(hr="(((1 - 1) * p * 1) = 0)", expr=Equals(Times(Minus(Int(1), Int(1)), p, Int(1)), Int(0)), is_valid=True, is_sat=True, logic=pysmt.logics.QF_LIA), # Huge Fractions: Example( hr= "((r * 1606938044258990275541962092341162602522202993782792835301376/7) = -20480000000000000000000000.0)", expr=Equals(Times(r, Real(Fraction(2**200, 7))), Real(-200**11)), is_valid=False, is_sat=True, logic=pysmt.logics.QF_LRA), Example(hr="(((r + 5.0 + s) * (s + 2.0 + r)) = 0.0)", expr=Equals( Times(Plus(r, Real(5), s), Plus(s, Real(2), r)), Real(0)), is_valid=False, is_sat=True, logic=pysmt.logics.QF_NRA), Example( hr= "(((p + 5 + q) * (p - (q - 5))) = ((p * p) + (10 * p) + 25 + (-1 * q * q)))", expr=Equals( Times(Plus(p, Int(5), q), Minus(p, Minus(q, Int(5)))), Plus(Times(p, p), Times(Int(10), p), Int(25), Times(Int(-1), q, q))), is_valid=True, is_sat=True, logic=pysmt.logics.QF_NIA), ] return result
def get_example_formulae(environment=None): if environment is None: environment = get_env() with environment: x = Symbol("x", BOOL) y = Symbol("y", BOOL) p = Symbol("p", INT) q = Symbol("q", INT) r = Symbol("r", REAL) s = Symbol("s", REAL) rf = Symbol("rf", FunctionType(REAL, [REAL, REAL])) rg = Symbol("rg", FunctionType(REAL, [REAL])) ih = Symbol("ih", FunctionType(INT, [REAL, INT])) ig = Symbol("ig", FunctionType(INT, [INT])) bv8 = Symbol("bv1", BV8) bv16 = Symbol("bv2", BV16) result = [ # Formula, is_valid, is_sat, is_qf # x /\ y Example(expr=And(x, y), is_valid=False, is_sat=True, logic=pysmt.logics.QF_BOOL), # x <-> y Example(expr=Iff(x, y), is_valid=False, is_sat=True, logic=pysmt.logics.QF_BOOL), # (x \/ y ) /\ ! ( x \/ y ) Example(expr=And(Or(x, y), Not(Or(x, y))), is_valid=False, is_sat=False, logic=pysmt.logics.QF_BOOL), # (x /\ !y) Example(expr=And(x, Not(y)), is_valid=False, is_sat=True, logic=pysmt.logics.QF_BOOL), # False -> True Example(expr=Implies(FALSE(), TRUE()), is_valid=True, is_sat=True, logic=pysmt.logics.QF_BOOL), # # LIA # # (p > q) /\ x -> y Example(expr=And(GT(p, q), Implies(x, y)), is_valid=False, is_sat=True, logic=pysmt.logics.QF_IDL), # (p + q) = 5 /\ (p > q) Example(expr=And(Equals(Plus(p, q), Int(5)), GT(p, q)), is_valid=False, is_sat=True, logic=pysmt.logics.QF_LIA), # (p >= q) \/ ( p <= q) Example(expr=Or(GE(p, q), LE(p, q)), is_valid=True, is_sat=True, logic=pysmt.logics.QF_IDL), # !( p < q * 2 ) Example(expr=Not(LT(p, Times(q, Int(2)))), is_valid=False, is_sat=True, logic=pysmt.logics.QF_LIA), # p - (5 - 2) > p Example(expr=GT(Minus(p, Minus(Int(5), Int(2))), p), is_valid=False, is_sat=False, logic=pysmt.logics.QF_IDL), # x ? 7: (p + -1) * 3 = q Example(expr=Equals( Ite(x, Int(7), Times(Plus(p, Int(-1)), Int(3))), q), is_valid=False, is_sat=True, logic=pysmt.logics.QF_LIA), Example(expr=LT(p, Plus(q, Int(1))), is_valid=False, is_sat=True, logic=pysmt.logics.QF_LIA), # # LRA # # (r > s) /\ x -> y Example(expr=And(GT(r, s), Implies(x, y)), is_valid=False, is_sat=True, logic=pysmt.logics.QF_RDL), # (r + s) = 5.6 /\ (r > s) Example(expr=And(Equals(Plus(r, s), Real(Fraction("5.6"))), GT(r, s)), is_valid=False, is_sat=True, logic=pysmt.logics.QF_LRA), # (r >= s) \/ ( r <= s) Example(expr=Or(GE(r, s), LE(r, s)), is_valid=True, is_sat=True, logic=pysmt.logics.QF_RDL), # !( (r / (1/2)) < s * 2 ) Example(expr=Not(LT(Div(r, Real((1, 2))), Times(s, Real(2)))), is_valid=False, is_sat=True, logic=pysmt.logics.QF_LRA), # ! ( r - (5 - 2) > r ) Example(expr=Not(GT(Minus(r, Minus(Real(5), Real(2))), r)), is_valid=True, is_sat=True, logic=pysmt.logics.QF_RDL), # x ? 7: (s + -1) * 3 = r Example(expr=Equals( Ite(x, Real(7), Times(Plus(s, Real(-1)), Real(3))), r), is_valid=False, is_sat=True, logic=pysmt.logics.QF_LRA), # # EUF # # rf(5, rg(2)) = 0 Example(expr=Equals(Function(rf, (Real(5), Function(rg, (r, )))), Real(0)), is_valid=False, is_sat=True, logic=pysmt.logics.QF_UFLRA), # (rg(r) = 5 + 2) <-> (rg(r) = 7) Example(expr=Iff(Equals(Function(rg, [r]), Plus(Real(5), Real(2))), Equals(Function(rg, [r]), Real(7))), is_valid=True, is_sat=True, logic=pysmt.logics.QF_UFLRA), # (r = s + 1) & (rg(s) = 5) & (rg(r - 1) = 7) Example(expr=And([ Equals(r, Plus(s, Real(1))), Equals(Function(rg, [s]), Real(5)), Equals(Function(rg, [Minus(r, Real(1))]), Real(7)) ]), is_valid=False, is_sat=False, logic=pysmt.logics.QF_UFLRA), # # BV # # bv_one & bv_zero == bv_zero Example(expr=Equals(BVAnd(BVOne(32), BVZero(32)), BVZero(32)), is_valid=True, is_sat=True, logic=pysmt.logics.QF_BV), # ~(010) == 101 Example(expr=Equals(BVNot(BV("010")), BV("101")), is_valid=True, is_sat=True, logic=pysmt.logics.QF_BV), # "111" xor "000" == "000" Example(expr=Equals(BVXor(BV("111"), BV("000")), BV("000")), is_valid=False, is_sat=False, logic=pysmt.logics.QF_BV), # bv8 :: bv8 < bv_zero Example(expr=BVULT(BVConcat(bv8, bv8), BVZero(16)), is_valid=False, is_sat=False, logic=pysmt.logics.QF_BV), # bv_one[:7] == bv_one Example(expr=Equals(BVExtract(BVOne(32), end=7), BVOne(8)), is_valid=True, is_sat=True, logic=pysmt.logics.QF_BV), # (((bv8 + bv_one) * bv(5)) / bv(5)) > bv(0) Example(expr=BVUGT( BVUDiv(BVMul(BVAdd(bv8, BVOne(8)), BV(5, width=8)), BV(5, width=8)), BVZero(8)), is_valid=False, is_sat=True, logic=pysmt.logics.QF_BV), # bv16 >=u bv(0) Example(expr=BVUGE(bv16, BVZero(16)), is_valid=True, is_sat=True, logic=pysmt.logics.QF_BV), # bv16 >=s bv(0) Example(expr=BVSGE(bv16, BVZero(16)), is_valid=False, is_sat=True, logic=pysmt.logics.QF_BV), # (BV(5) rem BV(2) > bv_zero) /\ (BV(5) rem BV(2) < bv_one) Example(expr=And( BVUGT(BVURem(BV(5, width=32), BV(2, width=32)), BVZero(32)), BVULE(BVURem(BV(5, width=32), BV(2, width=32)), BVOne(32))), is_valid=True, is_sat=True, logic=pysmt.logics.QF_BV), # ((bv_one + (- bv_one)) << 1) >> 1 == bv_one Example(expr=Equals( BVLShr(BVLShl(BVAdd(BVOne(32), BVNeg(BVOne(32))), 1), 1), BVOne(32)), is_valid=False, is_sat=False, logic=pysmt.logics.QF_BV), # bv_one - bv_one == bv_zero Example(expr=Equals(BVSub(BVOne(32), BVOne(32)), BVZero(32)), is_valid=True, is_sat=True, logic=pysmt.logics.QF_BV), # Rotations Example(expr=Equals(BVRor(BVRol(BVOne(32), 1), 1), BVOne(32)), is_valid=True, is_sat=True, logic=pysmt.logics.QF_BV), # Extensions Example(expr=Equals(BVZExt(BVZero(5), 11), BVSExt(BVZero(1), 15)), is_valid=True, is_sat=True, logic=pysmt.logics.QF_BV), # bv16 - bv16 = 0_16 Example(expr=Equals(BVSub(bv16, bv16), BVZero(16)), is_valid=True, is_sat=True, logic=pysmt.logics.QF_BV), # (bv16 - bv16)[0:7] = bv8 Example(expr=Equals(BVExtract(BVSub(bv16, bv16), 0, 7), bv8), is_valid=False, is_sat=True, logic=pysmt.logics.QF_BV), # (bv16[0,7] comp bv8) = bv1 Example(expr=Equals(BVComp(BVExtract(bv16, 0, 7), bv8), BVOne(1)), is_valid=False, is_sat=True, logic=pysmt.logics.QF_BV), # (bv16 comp bv16) = bv0 Example(expr=Equals(BVComp(bv16, bv16), BVZero(1)), is_valid=False, is_sat=False, logic=pysmt.logics.QF_BV), # (bv16 s< bv16) Example(expr=BVSLT(bv16, bv16), is_valid=False, is_sat=False, logic=pysmt.logics.QF_BV), # (bv16 s< 0_16) Example(expr=BVSLT(bv16, BVZero(16)), is_valid=False, is_sat=True, logic=pysmt.logics.QF_BV), # (bv16 u< bv16) Example(expr=BVULT(bv16, bv16), is_valid=False, is_sat=False, logic=pysmt.logics.QF_BV), # (bv16 s< 0_16) Example(expr=BVULT(bv16, BVZero(16)), is_valid=False, is_sat=False, logic=pysmt.logics.QF_BV), # (bv16 | 0_16) = bv16 Example(expr=Equals(BVOr(bv16, BVZero(16)), bv16), is_valid=True, is_sat=True, logic=pysmt.logics.QF_BV), # (bv16 & 0_16) = 0_16 Example(expr=Equals(BVAnd(bv16, BVZero(16)), BVZero(16)), is_valid=True, is_sat=True, logic=pysmt.logics.QF_BV), # 0_16 s< bv16 & ((bv16 s/ -1) s< 0) Example(expr=And(BVSLT(BVZero(16), bv16), BVSLT(BVSDiv(bv16, SBV(-1, 16)), BVZero(16))), is_valid=False, is_sat=True, logic=pysmt.logics.QF_BV), # 0_16 s< bv16 & ((bv16 s% -1) s< 0) Example(expr=And(BVSLT(BVZero(16), bv16), BVSLT(BVSRem(bv16, BVOne(16)), BVZero(16))), is_valid=False, is_sat=False, logic=pysmt.logics.QF_BV), # bv16 u% 1 = 0_16 Example(expr=Equals(BVURem(bv16, BVOne(16)), BVZero(16)), is_valid=True, is_sat=True, logic=pysmt.logics.QF_BV), # bv16 s% 1 = 0_16 Example(expr=Equals(BVSRem(bv16, BVOne(16)), BVZero(16)), is_valid=True, is_sat=True, logic=pysmt.logics.QF_BV), # bv16 s% -1 = 0_16 Example(expr=Equals(BVSRem(bv16, BVNeg(BVOne(16))), BVZero(16)), is_valid=True, is_sat=True, logic=pysmt.logics.QF_BV), # bv16 a>> 0 = bv16 Example(expr=Equals(BVAShr(bv16, BVZero(16)), bv16), is_valid=True, is_sat=True, logic=pysmt.logics.QF_BV), # 0 s<= bv16 & bv16 a>> 1 = bv16 >> 1 Example(expr=And( BVSLE(BVZero(16), bv16), Equals(BVAShr(bv16, BVOne(16)), BVLShr(bv16, BVOne(16)))), is_valid=False, is_sat=True, logic=pysmt.logics.QF_BV), # # Quantification # # forall y . x -> y Example(expr=ForAll([y], Implies(x, y)), is_valid=False, is_sat=True, logic=pysmt.logics.BOOL), # forall p,q . p + q = 0 Example(expr=ForAll([p, q], Equals(Plus(p, q), Int(0))), is_valid=False, is_sat=False, logic=pysmt.logics.LIA), # forall r,s . ((r > 0) & (s > 0)) -> (r - s < r) Example(expr=ForAll([r, s], Implies(And(GT(r, Real(0)), GT(s, Real(0))), (LT(Minus(r, s), r)))), is_valid=True, is_sat=True, logic=pysmt.logics.LRA), # exists x,y . x -> y Example(expr=Exists([x, y], Implies(x, y)), is_valid=True, is_sat=True, logic=pysmt.logics.BOOL), # exists p,q . p + q = 0 Example(expr=Exists([p, q], Equals(Plus(p, q), Int(0))), is_valid=True, is_sat=True, logic=pysmt.logics.LIA), # exists r . forall s . (r - s > r) Example(expr=Exists([r], ForAll([s], GT(Minus(r, s), r))), is_valid=False, is_sat=False, logic=pysmt.logics.LRA), # forall r . exists s . (r - s > r) Example(expr=ForAll([r], Exists([s], GT(Minus(r, s), r))), is_valid=True, is_sat=True, logic=pysmt.logics.LRA), # x /\ forall r. (r + s = 5) Example(expr=And(x, ForAll([r], Equals(Plus(r, s), Real(5)))), is_valid=False, is_sat=False, logic=pysmt.logics.LRA), # # UFLIRA # # ih(r,q) > p /\ (x -> y) Example(expr=And(GT(Function(ih, (r, q)), p), Implies(x, y)), is_valid=False, is_sat=True, logic=pysmt.logics.QF_UFLIRA), # ( (p - 3) = q ) -> ( ih(r, q + 3) > p \/ ih(r, p) <= p ) Example(expr=Implies( Equals(Minus(p, Int(3)), q), Or(GT(Function(ih, (r, Plus(q, Int(3)))), p), LE(Function(ih, (r, p)), p))), is_valid=True, is_sat=True, logic=pysmt.logics.QF_UFLIRA), # ( (ToReal(p - 3) = r) /\ (ToReal(q) = r) ) -> # ( ( ih(ToReal(p - 3), q + 3) > p ) \/ (ih(r, p) <= p) ) Example(expr=Implies( And(Equals(ToReal(Minus(p, Int(3))), r), Equals(ToReal(q), r)), Or( GT( Function(ih, (ToReal(Minus(p, Int(3))), Plus(q, Int(3)))), p), LE(Function(ih, (r, p)), p))), is_valid=True, is_sat=True, logic=pysmt.logics.QF_UFLIRA), # ! ( (ToReal(p - 3) = r /\ ToReal(q) = r) -> # ( ih(ToReal(p - 3), q + 3) > p \/ # ih(r,p) <= p ) ) Example(expr=Not( Implies( And(Equals(ToReal(Minus(p, Int(3))), r), Equals(ToReal(q), r)), Or( GT( Function( ih, (ToReal(Minus(p, Int(3))), Plus(q, Int(3)))), p), LE(Function(ih, (r, p)), p)))), is_valid=False, is_sat=False, logic=pysmt.logics.QF_UFLIRA), # Test complex names Example(expr=And( Symbol("Did you know that any string works? #yolo"), Symbol("10"), Symbol("|#somesolverskeepthe||"), Symbol(" ")), is_valid=False, is_sat=True, logic=pysmt.logics.QF_BOOL), ] return result
def generate_STS(self, lines): ts = TS("Additional system") init = TRUE() trans = TRUE() invar = TRUE() states = {} assigns = set([]) varsmap = {} def def_var(name, vtype): if name in varsmap: return varsmap[name] var = Symbol(name, vtype) ts.add_state_var(var) return var for line in lines: if line.comment: continue if line.init: if T_I not in states: states[T_I] = TRUE() if line.init.varname != "": (value, typev) = self.__get_value(line.init.value) ivar = def_var(line.init.varname, typev) state = EqualsOrIff(ivar, value) else: state = TRUE() if line.init.value == T_TRUE else FALSE() states[T_I] = And(states[T_I], state) # Optimization for the initial state assignment init = And(init, state) state = TRUE() if line.state: sname = T_S + line.state.id if (line.state.varname != ""): (value, typev) = self.__get_value(line.state.value) ivar = def_var(line.state.varname, typev) state = EqualsOrIff(ivar, value) assval = (sname, line.state.varname) if assval not in assigns: assigns.add(assval) else: Logger.error( "Double assignment for variable \"%s\" at state \"%s\"" % (line.state.varname, sname)) else: state = TRUE() if line.state.value == T_TRUE else FALSE() if sname not in states: states[sname] = TRUE() states[sname] = And(states[sname], state) stateid_width = math.ceil(math.log(len(states)) / math.log(2)) stateid_var = Symbol(self.new_state_id(), BVType(stateid_width)) init = And(init, EqualsOrIff(stateid_var, BV(0, stateid_width))) invar = And( invar, Implies(EqualsOrIff(stateid_var, BV(0, stateid_width)), states[T_I])) states[T_I] = EqualsOrIff(stateid_var, BV(0, stateid_width)) count = 1 state_items = list(states.keys()) state_items.sort() for state in state_items: if state == T_I: continue invar = And( invar, Implies(EqualsOrIff(stateid_var, BV(count, stateid_width)), states[state])) states[state] = EqualsOrIff(stateid_var, BV(count, stateid_width)) count += 1 transdic = {} for line in lines: if line.comment: continue if line.trans: if states[line.trans.start] not in transdic: transdic[states[line.trans.start]] = [] transdic[states[line.trans.start]].append( states[line.trans.end]) for transition in transdic: (start, end) = (transition, transdic[transition]) trans = And(trans, Implies(start, TS.to_next(Or(end)))) vars_ = [v for v in get_free_variables(trans) if not TS.is_prime(v)] vars_ += get_free_variables(init) vars_ += get_free_variables(invar) invar = And(invar, BVULE(stateid_var, BV(count - 1, stateid_width))) ts.set_behavior(init, trans, invar) ts.add_state_var(stateid_var) hts = HTS("ETS") hts.add_ts(ts) invar_props = [] ltl_props = [] return (hts, invar_props, ltl_props)
def test_trivial_false_and(self): x, y, z = (Symbol(name) for name in "xyz") f = And(x, y, z, Not(x)) self.assertEqual(f.simplify(), FALSE())
def test_and_flattening(self): x, y, z = (Symbol(name) for name in "xyz") f1 = And(x, y, z) f2 = And(x, And(y, z)) self.assertEqual(f2.simplify(), f1)
def get_makespan_optimal_weakly_hard_schedule(g, network, feasibility_timeout=None, optimization_timeout=10 * 60 * 1000): vprint('*computing optimal weakly-hard real-time schedule via SMT*') # SMT formulation tc = transitive_closure(g) logical_edges = get_logical_edges(g) JUMPTABLE_MAX = 6 K_MAX = 5001 # LAMBDA(i)[1] < K_MAX for all i < JUMPTABLE_MAX A, B, C, D, GAMMA, LAMBDA = (network[key] for key in ('A', 'B', 'C', 'D', 'GAMMA', 'LAMBDA')) assert (all(map(lambda x: LAMBDA(x)[1] < K_MAX, range(JUMPTABLE_MAX)))) vprint('\tinstantiating symvars...') label = [Symbol('label_%i' % i, INT) for i in range(len(logical_edges))] # first half for slot, second half for beacons chi = [Symbol('chi_%i' % i, INT) for i in range(2 * len(logical_edges))] duration = [ Symbol('duration_%i' % i, INT) for i in range(len(logical_edges)) ] zeta = [ Symbol('zeta_%i' % i, INT) for i in range(g.num_vertices() + len(logical_edges)) ] delta_e_in_r = [[ Symbol('delta_e_in_r-%i_%i' % (i, j), INT) for j in range(len(logical_edges)) ] for i in range(len(logical_edges))] delta_chi_eq_i = [[ Symbol('delta_chi_eq_i-%i_%i' % (i, j), INT) for j in range(JUMPTABLE_MAX) ] for i in range(2 * len(logical_edges))] delta_tau_before_r = [[ Symbol('delta_tau_before_r-%i_%i' % (i, j), INT) for j in range(len(logical_edges)) ] for i in range(g.num_vertices() + len(logical_edges))] vprint('\tgenerating constraint clauses...') domain = And([ And([ And(LE(Int(1), sym), LE(sym, Int(len(logical_edges)))) for sym in label ]), And([And(LE(Int(1), sym), LT(sym, Int(JUMPTABLE_MAX))) for sym in chi]), And([LE(Int(0), sym) for sym in zeta]), And([ And(LE(Int(0), sym), LE(sym, Int(1))) for sym in chain.from_iterable(delta_e_in_r + delta_chi_eq_i + delta_tau_before_r) ]) ]) one_hot = And([ And([ Equals( Plus([delta_e_in_r[e][r] for r in range(len(logical_edges))]), Int(1)) for e in range(len(logical_edges)) ]), And([ Equals( Plus([delta_chi_eq_i[chir][i] for i in range(JUMPTABLE_MAX)]), Int(1)) for chir in range(2 * len(logical_edges)) ]) ]) CFOP = And([ LT(label[logical_edges.index(r)], label[logical_edges.index(s)]) for r, s in product(logical_edges, repeat=2) if r.source() in tc.get_in_neighbors(s.source()) ]) task_partitioning_by_round = And( And([ LE(delta_tau_before_r[int(tau)][r], delta_tau_before_r[int(mu)][r]) for tau, mu, r in product(tc.vertices(), tc.vertices(), range(len(logical_edges))) if tau in tc.get_in_neighbors(mu) ]), And([ Equals(delta_tau_before_r[r + g.num_vertices()][s], Int(0)) if r < s else Equals(delta_tau_before_r[r + g.num_vertices()][s], Int(1)) for r, s in product(range(len(logical_edges)), repeat=2) ])) round_empty = And([ Implies( Equals( Plus([delta_e_in_r[e][r] for e in range(len(logical_edges))]), Int(0)), Equals(chi[len(logical_edges) + r], Int(1))) for r in range(len(logical_edges)) ]) durations = And([ Equals( duration[r], Plus( Int(A), Times(Plus(Times(Int(2), chi[r + len(logical_edges)]), Int(B)), Int(C + D * GAMMA)), Times( Ite( GE( Plus([ delta_e_in_r[e][r] for e in range(len(logical_edges)) ]), Int(1)), Int(0), Int(-1)), Int(A + (2 + B) * (C + D * GAMMA))), Plus([ Ite( Equals(delta_e_in_r[e][r], Int(1)), Plus( Int(A), Times( Plus(Times(Int(2), chi[e]), Int(B)), Int(C + D * g.edge_properties['widths'][ logical_edges[e]]))), Int(0)) for e in range(len(logical_edges)) ]))) for r in range(len(logical_edges)) ]) label_to_delta = And([ Equals( label[e], Plus([ Times(delta_e_in_r[e][i - 1], Int(i)) for i in range(1, 1 + len(logical_edges)) ])) for e in range(len(logical_edges)) ]) chi_to_delta = And([ Equals( chi[chir], Plus([ Times(delta_chi_eq_i[chir][i], Int(i)) for i in range(JUMPTABLE_MAX) ])) for chir in range(2 * len(logical_edges)) ]) order = And( And([ LT(zeta[int(tau)], Minus(zeta[int(mu)], Int(g.vertex_properties['durations'][mu]))) for tau, mu in product(g.vertices(), repeat=2) if tau in tc.get_in_neighbors(mu) ]), And([ LT(zeta[r + g.num_vertices()], Minus(zeta[r + 1 + g.num_vertices()], duration[r + 1])) for r in range(len(logical_edges) - 1) ]), And([ Implies( Equals(delta_e_in_r[e][r], Int(1)), GT( Minus(zeta[int(tau)], Int(g.vertex_properties['durations'][tau])), zeta[r + g.num_vertices()])) for tau in g.vertices() for r in range(len(logical_edges)) for e in range(len(logical_edges)) if tau in tc.get_out_neighbors(logical_edges[e].source()) ]), And([ Implies( Equals(delta_e_in_r[e][r], Int(1)), GT(Minus(zeta[r + g.num_vertices()], duration[r]), zeta[int(tau)])) for tau in g.vertices() for r in range(len(logical_edges)) for e in range(len(logical_edges)) if tau in tc.get_in_neighbors(logical_edges[e].source()) or tau == logical_edges[e].source() ])) exclusion = And([ And( Implies( Equals(delta_tau_before_r[int(tau)][r], Int(0)), GT(Minus(zeta[r + g.num_vertices()], duration[r]), zeta[int(tau)])), Implies( Equals(delta_tau_before_r[int(tau)][r], Int(1)), GT( Minus(zeta[int(tau)], Int(g.vertex_properties['durations'][tau])), zeta[g.num_vertices() + r]))) for tau in g.vertices() for r in range(len(logical_edges)) ]) deadline = And([ LE(zeta[int(tau)], Int(g.vertex_properties['deadlines'][tau])) for tau in g.vertices() if g.vertex_properties['deadlines'][tau] >= 0 ]) def sum_m(tau): return Plus([Int(0)] + [ Plus( Ite(Equals(delta_chi_eq_i[e][i], Int(1)), Int(LAMBDA(i)[0]), Int(0)), Plus([ Ite( Equals(delta_chi_eq_i[len(logical_edges) + r][i], Int(1)), Ite(Equals(delta_e_in_r[e][r], Int(1)), Int(LAMBDA(i)[0]), Int(0)), Int(0)) for r in range(len(logical_edges)) ])) for i in range(JUMPTABLE_MAX) for e in range(len(logical_edges)) if logical_edges[e].source() in tc.get_in_neighbors(tau) ]) def min_K(tau): return Min([Int(K_MAX)] + [ Min( Ite(Equals(delta_chi_eq_i[e][i], Int(1)), Int(LAMBDA(i)[1]), Int(K_MAX)), Min([ Ite( Equals(delta_chi_eq_i[len(logical_edges) + r][i], Int(1)), Ite(Equals(delta_e_in_r[e][r], Int(1)), Int(LAMBDA(i)[1]), Int(K_MAX)), Int(K_MAX)) for r in range(len(logical_edges)) ])) for i in range(JUMPTABLE_MAX) for r in range(len(logical_edges)) for e in range(len(logical_edges)) if logical_edges[e].source() in tc.get_in_neighbors(tau) ]) WH = And([ And( GE(Int(g.vertex_properties['weakly-hard'][tau][0]), Min(sum_m(tau), min_K(tau))), LE(Int(g.vertex_properties['weakly-hard'][tau][1]), min_K(tau))) for tau in g.vertices() if g.vertex_properties['weakly-hard'][tau][0] >= 0 ]) formula = And([ domain, one_hot, CFOP, task_partitioning_by_round, round_empty, durations, label_to_delta, chi_to_delta, order, exclusion, deadline, WH ]) vprint('\tchecking feasibility...') solver = Solver(name='z3', incremental=True, logic='LIA') if feasibility_timeout: solver.z3.set('timeout', feasibility_timeout) solver.add_assertion(formula) try: result = solver.solve() except SolverReturnedUnknownResultError: result = None if not result: vprint('\tsolver returned infeasible!') return [None] * 4 else: models = [solver.get_model()] vprint('\tsolver found a feasible solution, optimizing...') solver.z3.set('timeout', optimization_timeout) LB = 0 UB = max(map(lambda x: models[-1].get_py_value(x), zeta)) curr_B = UB // 2 while range(LB + 1, UB): try: result = solver.solve( [And([LT(zeta_tau, Int(curr_B)) for zeta_tau in zeta])]) except SolverReturnedUnknownResultError: vprint('\t(timeout, not necessarily unsat)') result = None if result: vprint('\tfound feasible solution of length %i, optimizing...' % curr_B) models.append(solver.get_model()) UB = curr_B else: vprint('\tnew lower bound %i, optimizing...' % curr_B) LB = curr_B curr_B = LB + int(ceil((UB - LB) / 2)) vprint('\tsolver returned optimal (under composition+P.O. abstractions)!') best_model = models[-1] zeta = list(map(lambda x: best_model.get_py_value(x), zeta)) chi = list(map(lambda x: best_model.get_py_value(x), chi)) duration = list(map(lambda x: best_model.get_py_value(x), duration)) label = list(map(lambda x: best_model.get_py_value(x), label)) return zeta, chi, duration, label
def encode(self): """ Do the job. """ self.enc = [] # getting a tree ensemble self.ensemble = TreeEnsemble(self.model, self.xgb.extended_feature_names_as_array_strings, nb_classes=self.nofcl) # self.ensemble.print_tree() # introducing class score variables csum = [] for j in range(self.nofcl): cvar = Symbol('class{0}_score'.format(j), typename=REAL) csum.append(tuple([cvar, []])) # if targeting interval-based encoding, # traverse all trees and extract all possible intervals # for each feature if self.optns.encode == 'smtbool': self.compute_intervals() # traversing and encoding each tree for i, tree in enumerate(self.ensemble.trees): # getting class id clid = i % self.nofcl # encoding the tree tvar = Symbol('tr{0}_score'.format(i + 1), typename=REAL) self.traverse(tree, tvar, prefix=[]) # this tree contributes to class with clid csum[clid][1].append(tvar) # encoding the sums for pair in csum: cvar, tvars = pair self.enc.append(Equals(cvar, Plus(tvars))) # enforce exactly one of the feature values to be chosen # (for categorical features) categories = collections.defaultdict(lambda: []) for f in self.xgb.extended_feature_names_as_array_strings: if '_' in f: categories[f.split('_')[0]].append(Symbol(name=f, typename=BOOL)) for c, feats in six.iteritems(categories): self.enc.append(ExactlyOne(feats)) # number of assertions nof_asserts = len(self.enc) # making conjunction self.enc = And(self.enc) # number of variables nof_vars = len(self.enc.get_free_variables()) if self.optns.verb: print('encoding vars:', nof_vars) print('encoding asserts:', nof_asserts) return self.enc, self.intvs, self.imaps, self.ivars
def walk_or_to_and(formula, args, **kwargs): return And(args)
def test_sample(self, sample): """ Check whether or not the encoding "predicts" the same class as the classifier given an input sample. """ # first, compute the scores for all classes as would be # predicted by the classifier # score arrays computed for each class csum = [[] for c in range(self.nofcl)] if self.optns.verb: print('testing sample:', list(sample)) sample_internal = list(self.xgb.transform(sample)[0]) # traversing all trees for i, tree in enumerate(self.ensemble.trees): # getting class id clid = i % self.nofcl # a score computed by the current tree score = scores_tree(tree, sample_internal) # this tree contributes to class with clid csum[clid].append(score) # final scores for each class cscores = [sum(scores) for scores in csum] # second, get the scores computed with the use of the encoding # asserting the sample hypos = [] if not self.intvs: for i, fval in enumerate(sample_internal): feat, vid = self.xgb.transform_inverse_by_index(i) fid = self.feats[feat] if vid == None: fvar = Symbol('f{0}'.format(fid), typename=REAL) hypos.append(Equals(fvar, Real(float(fval)))) else: fvar = Symbol('f{0}_{1}'.format(fid, vid), typename=BOOL) if int(fval) == 1: hypos.append(fvar) else: hypos.append(Not(fvar)) else: for i, fval in enumerate(sample_internal): feat, _ = self.xgb.transform_inverse_by_index(i) feat = 'f{0}'.format(self.feats[feat]) # determining the right interval and the corresponding variable for ub, fvar in zip(self.intvs[feat], self.ivars[feat]): if ub == '+' or fval < ub: hypos.append(fvar) break else: assert 0, 'No proper interval found for {0}'.format(feat) # now, getting the model escores = [] model = get_model(And(self.enc, *hypos), solver_name=self.optns.solver) for c in range(self.nofcl): v = Symbol('class{0}_score'.format(c), typename=REAL) escores.append(float(model.get_py_value(v))) assert all(map(lambda c, e: abs(c - e) <= 0.001, cscores, escores)), \ 'wrong prediction: {0} vs {1}'.format(cscores, escores) if self.optns.verb: print('xgb scores:', cscores) print('enc scores:', escores)
def run_cegis(program_path, project_path, patch_list): test_output_list = values.LIST_TEST_OUTPUT test_template = reader.collect_specification(test_output_list[0]) time_check = time.time() assertion, largest_path_condition = concolic.run_concolic_exploration( program_path, patch_list) duration = (time.time() - time_check) / 60 values.TIME_TO_EXPLORE = duration emitter.normal("\tcombining explored program paths") if not assertion: patch = patch_list[0] emitter.emit_patch(patch, message="\tfinal patch: ") return program_specification = generator.generate_program_specification() complete_specification = And(Not(assertion), program_specification) emitter.normal("\tcomputed the program specification formula") emitter.sub_title("Evaluating Patch Pool") iteration = 0 output_dir = definitions.DIRECTORY_OUTPUT counter_example_list = [] time_check = time.time() values.CONF_TIME_CHECK = None satisfied = utilities.check_budget(values.DEFAULT_TIMEOUT_CEGIS_REFINE) patch_generator = generator.generate_patch(project_path, counter_example_list) count_throw = 0 while not satisfied: iteration = iteration + 1 values.ITERATION_NO = iteration emitter.sub_sub_title("Iteration: " + str(iteration)) patch = next(patch_generator, None) if not patch: emitter.error("[error] cannot generate a patch") patch_formula = app.generator.generate_formula_from_patch(patch) emitter.emit_patch(patch, message="\tgenerated patch: ") patch_formula_extended = generator.generate_extended_patch_formula( patch_formula, largest_path_condition) violation_check = And(complete_specification, patch_formula_extended) if is_sat(violation_check): model = generator.generate_model(violation_check) # print(model) arg_list = values.ARGUMENT_LIST poc_path = values.CONF_PATH_POC values.FILE_POC_GEN = definitions.DIRECTORY_OUTPUT + "/violation-" + str( values.ITERATION_NO) gen_path = values.FILE_POC_GEN input_arg_list, input_var_list = generator.generate_new_input( violation_check, arg_list, poc_path, gen_path) klee_out_dir = output_dir + "/klee-out-repair-" + str(iteration) klee_test_file = output_dir + "/klee-test-" + str(iteration) exit_code = concolic.run_concrete_execution( program_path + ".bc", input_arg_list, True, klee_out_dir) # assert exit_code == 0 values.COUNT_PATHS_EXPLORED = values.COUNT_PATHS_EXPLORED + 1 emitter.normal("\t\tgenerating new assertion") test_assertion, count_obs = generator.generate_assertion( test_template, klee_out_dir) write_smtlib(test_assertion, klee_test_file) counter_example_list.append((klee_test_file, klee_out_dir)) emitter.highlight("\t\tnew counter-example added") patch = None emitter.highlight("\t\tremoving current patch") count_throw = count_throw + 1 else: klee_test_file = output_dir + "/klee-test-FINAL" # print(to_smtlib(violation_check, False)) write_smtlib(violation_check, klee_test_file) break satisfied = utilities.check_budget(values.DEFAULT_TIMEOUT_CEGIS_REFINE) if satisfied: emitter.warning("\t[warning] ending due to timeout of " + str(values.DEFAULT_TIMEOUT_CEGIS_REFINE) + " minutes") duration = (time.time() - time_check) / 60 values.TIME_TO_REDUCE = duration # patch_list = [patch] # definitions.FILE_PATCH_SET = definitions.DIRECTORY_OUTPUT + "/patch-set-cegis" # writer.write_patch_set(patch_list, definitions.FILE_PATCH_SET) # patch = next(patch_generator, None) # while patch is not None: # patch_formula = app.generator.generate_formula_from_patch(patch) # patch_formula_extended = generator.generate_extended_patch_formula(patch_formula, largest_path_condition) # violation_check = And(complete_specification, patch_formula_extended) # if is_unsat(violation_check): # count_final = count_final + 1 # patch = next(patch_generator, None) emitter.emit_patch(patch, message="\tfinal patch: ") values.COUNT_PATCH_END = values.COUNT_PATCH_START - count_throw
def remove_invar(self): if self.invar is not None: self.trans = And([self.trans, self.invar, TS.to_next(self.invar)]) self.init = And(self.init, self.invar) self.invar = None
def parse_string(self, lines): [none, var, state, input, output, init, invar, trans, ftrans] = range(9) section = none inits = TRUE() invars = TRUE() transs = TRUE() ftranss = {} sparser = StringParser() count = 0 vars = set([]) states = set([]) inputs = set([]) outputs = set([]) invar_props = [] ltl_props = [] for line in lines: count += 1 if (line.strip() in ["", "\n"]) or line[0] == T_COM: continue if T_VAR == line[:len(T_VAR)]: section = var continue if T_STATE == line[:len(T_STATE)]: section = state continue if T_INPUT == line[:len(T_INPUT)]: section = input continue if T_OUTPUT == line[:len(T_OUTPUT)]: section = output continue if T_INIT == line[:len(T_INIT)]: section = init continue if T_INVAR == line[:len(T_INVAR)]: section = invar continue if T_TRANS == line[:len(T_TRANS)]: section = trans continue if T_FTRANS == line[:len(T_FTRANS)]: section = ftrans continue if section in [var, state, input, output]: line = line[:-2].replace(" ", "").split(":") varname, vartype = line[0], ( line[1][:-1].split("(")) if "(" in line[1] else line[1] if varname[0] == "'": varname = varname[1:-1] vardef = self._define_var(varname, vartype) vars.add(vardef) if section == state: states.add(vardef) if section == input: inputs.add(vardef) if section == output: outputs.add(vardef) if section in [init, invar, trans]: line = line.replace(T_SC, "").strip() qline = quote_names(line, replace_ops=False) if section == init: inits = And(inits, sparser.parse_formula(qline)) if section == invar: invars = And(invars, sparser.parse_formula(qline)) if section == trans: transs = And(transs, sparser.parse_formula(qline)) if section == ftrans: strvar = line[:line.find(":=")] var = sparser.parse_formula( quote_names(strvar, replace_ops=False)) cond_ass = line[line.find(":=") + 2:].strip() ftranss[var] = [] for cond_as in cond_ass.split("{"): if cond_as == "": continue cond = cond_as[:cond_as.find(",")] ass = cond_as[cond_as.find(",") + 1:cond_as.find("}")] ftranss[var].append((sparser.parse_formula( quote_names(cond, replace_ops=False)), sparser.parse_formula( quote_names(ass, replace_ops=False)))) hts = HTS("STS") ts = TS() ts.vars = vars ts.state_vars = states ts.input_vars = inputs ts.output_vars = outputs ts.init = inits ts.invar = invars ts.trans = transs ts.ftrans = ftranss hts.add_ts(ts) return (hts, invar_props, ltl_props)
NO_OF_NODES = 2 NO_OF_COMPONENTS = 3 componentResrcWeights = [1,2,1] nodeRsrc = [3,1] c2n = [[Symbol("c2n_%s_%s" % (i, j), INT) for j in range(NO_OF_NODES)] for i in range(NO_OF_COMPONENTS)] pprint.pprint(c2n) # Range constraints: zero or one domain = [Or(Equals(c2n[i][j],Int(0)), Equals(c2n[i][j],Int(1))) for j in range(NO_OF_NODES) for i in range(NO_OF_COMPONENTS)] print ("domain") pprint.pprint(domain) constrain_c2n_values = And(domain) #Each component is deployed 0 or 1 times g_asgn_c2n = [(Plus(c2n[i][j] for j in range(NO_OF_NODES)) <= Int(1)) for i in range(NO_OF_COMPONENTS)] print("g_asgn_c2n") pprint.pprint(g_asgn_c2n) #must deploy every component md_c2n = [(Plus(c2n[i][j] for j in range(NO_OF_NODES)).Equals(Int(1))) for i in range(NO_OF_COMPONENTS)] print("md_c2n") pprint.pprint(md_c2n) #deployed constraints cannont exceed resources. rsrcConstraint = [(Plus(c2n[i][j]*componentResrcWeights[i] for i in range(NO_OF_COMPONENTS)) <= nodeRsrc[j]) for j in range(NO_OF_NODES)] print("rsrc constraint")
def play_move(p, row, col): logger.debug("adding assertion for player %s at (%d, %d)" % (p.name, row, col)) solver.add_assertion(And(Equals(board[row][col], p.value)))
def violate_right_generator(n): return And([ GT(Plus(k_seq[t:min(K_seq_len, t + K + n)]), Int(m)) for t in range(max(1, K_seq_len - (K + n) + 1)) ])
def test_boolean(self): x, y, z = Symbol("x"), Symbol("y"), Symbol("z") f = Or(And(Not(x), Iff(x, y)), Implies(x, z)) f_string = self.print_to_string(f) self.assertEqual(f_string, "(or (and (not x) (= x y)) (=> x z))")
from pysmt.shortcuts import Symbol, And, GE, LT, Plus, Equals, Int, get_model from pysmt.typing import INT hello = [Symbol(s, INT) for s in "hello"] world = [Symbol(s, INT) for s in "world"] letters = set(hello + world) domains = And([And(GE(l, Int(1)), LT(l, Int(10))) for l in letters]) print domains sum_hello = Plus(hello) # n-ary operators can take lists sum_world = Plus(world) # as arguments problem = And(Equals(sum_hello, sum_world), Equals(sum_hello, Int(25))) formula = And(domains, problem) print("Serialization of the formula:") print(formula) model = get_model(formula) if model: print(model) else: print("No solution found")
from pysmt.shortcuts import Symbol, LE, GE, And, Int from pysmt.typing import INT h = Symbol("H", INT) # domain = (1 <= h) & (10 >= h) domain = And(LE(Int(1), h), GE(Int(10), h))
def test_bv(self): mgr = get_env().formula_manager BV = mgr.BV # Constants one = BV(1, 32) zero = BV(0, 32) big = BV(127, 128) binary = BV("111") binary2 = BV("#b111") binary3 = BV(0b111, 3) # In this case we need to explicit the width self.assertEqual(binary, binary2) self.assertEqual(binary2, binary3) self.assertEqual(one, mgr.BVOne(32)) self.assertEqual(zero, mgr.BVZero(32)) # Type Equality self.assertTrue(BV32 != BV128) self.assertFalse(BV32 != BV32) self.assertFalse(BV32 == BV128) self.assertTrue(BV32 == BV32) with self.assertRaises(ValueError): # Negative numbers are not supported BV(-1, 10) with self.assertRaises(ValueError): # Number should fit in the width BV(10, 2) # Variables b128 = Symbol("b", BV128) # BV1, BV8 etc. are defined in pysmt.typing b32 = Symbol("b32", BV32) hexample = BV(0x10, 32) #s_one = BV(-1, 32) bcustom = Symbol("bc", BVType(42)) self.assertIsNotNone(hexample) self.assertIsNotNone(bcustom) #self.assertIsNotNone(s_one) self.assertEqual(bcustom.bv_width(), 42) self.assertEqual(hexample.constant_value(), 16) #self.assertEqual(str(s_one), "-1_32") not_zero32 = mgr.BVNot(zero) not_b128 = mgr.BVNot(b128) f1 = Equals(not_zero32, b32) f2 = Equals(not_b128, big) #print(f1) #print(f2) self.assertTrue(is_sat(f1, logic=QF_BV)) self.assertTrue(is_sat(f2, logic=QF_BV)) zero_and_one = mgr.BVAnd(zero, one) zero_or_one = mgr.BVOr(zero, one) zero_xor_one = mgr.BVXor(zero, one) zero_xor_one.simplify() self.assertTrue(zero_xor_one.is_bv_op()) # print(zero_and_one) # print(zero_or_one) # print(zero_xor_one) f1 = Equals(zero_and_one, b32) f2 = Equals(zero_or_one, b32) f3 = Equals(zero_xor_one, b32) f4 = Equals(zero_xor_one, one) self.assertTrue(is_sat(f1, logic=QF_BV), f1) self.assertTrue(is_sat(f2, logic=QF_BV), f2) self.assertTrue(is_sat(f3, logic=QF_BV), f3) self.assertTrue(is_valid(f4, logic=QF_BV), f4) with self.assertRaises(TypeError): mgr.BVAnd(b128, zero) f = mgr.BVAnd(b32, zero) f = mgr.BVOr(f, b32) f = mgr.BVXor(f, b32) f = Equals(f, zero) self.assertTrue(is_sat(f, logic=QF_BV), f) zero_one_64 = mgr.BVConcat(zero, one) one_zero_64 = mgr.BVConcat(one, zero) one_one_64 = mgr.BVConcat(one, one) self.assertTrue(zero_one_64.bv_width() == 64) f1 = Equals(mgr.BVXor(one_zero_64, zero_one_64), one_one_64) self.assertTrue(is_sat(f1, logic=QF_BV), f1) # MG: BV indexes grow to the left. # This is confusing and we should address this. extraction = mgr.BVExtract(zero_one_64, 32, 63) self.assertTrue(is_valid(Equals(extraction, zero))) #print(extraction) ult = mgr.BVULT(zero, one) neg = mgr.BVNeg(one) self.assertTrue(is_valid(ult, logic=QF_BV), ult) test_eq = Equals(neg, one) self.assertTrue(is_unsat(test_eq, logic=QF_BV)) # print(ult) # print(neg) f = zero addition = mgr.BVAdd(f, one) multiplication = mgr.BVMul(f, one) udiv = mgr.BVUDiv(f, one) self.assertTrue(is_valid(Equals(addition, one), logic=QF_BV), addition) self.assertTrue(is_valid(Equals(multiplication, zero), logic=QF_BV), multiplication) self.assertTrue(is_valid(Equals(udiv, zero), logic=QF_BV), udiv) # print(addition) # print(multiplication) # print(udiv) three = mgr.BV(3, 32) two = mgr.BV(2, 32) reminder = mgr.BVURem(three, two) shift_l_a = mgr.BVLShl(one, one) shift_l_b = mgr.BVLShl(one, 1) self.assertTrue(is_valid(Equals(reminder, one)), reminder) self.assertEqual(shift_l_a, shift_l_b) self.assertTrue(is_valid(Equals(shift_l_a, two))) # print(reminder) # print(shift_l_a) # print(shift_l_b) shift_r_a = mgr.BVLShr(one, one) shift_r_b = mgr.BVLShr(one, 1) self.assertEqual(shift_r_a, shift_r_b) self.assertTrue(is_valid(Equals(shift_r_a, zero))) rotate_l = mgr.BVRol(one, 3) rotate_r = mgr.BVRor(rotate_l, 3) self.assertTrue(is_valid(Equals(one, rotate_r))) # print(rotate_l) # print(rotate_r) zero_ext = mgr.BVZExt(one, 64) signed_ext = mgr.BVSExt(one, 64) signed_ext2 = mgr.BVSExt(mgr.BVNeg(one), 64) self.assertNotEqual(signed_ext2, signed_ext) self.assertTrue(is_valid(Equals(zero_ext, signed_ext), logic=QF_BV)) # print(zero_ext) # print(signed_ext) x = Symbol("x") g = And(x, mgr.BVULT(zero, one)) res = is_sat(g, logic=QF_BV) self.assertTrue(res) model = get_model(g, logic=QF_BV) self.assertTrue(model[x] == TRUE()) gt_1 = mgr.BVUGT(zero, one) gt_2 = mgr.BVULT(one, zero) self.assertEqual(gt_1, gt_2) gte_1 = mgr.BVULE(zero, one) gte_2 = mgr.BVUGE(one, zero) self.assertEqual(gte_1, gte_2) self.assertTrue(is_valid(gte_2, logic=QF_BV)) ide = Equals(mgr.BVNeg(BV(10, 32)), mgr.SBV(-10, 32)) self.assertValid(ide, logic=QF_BV) # These should work without exceptions mgr.SBV(-2, 2) mgr.SBV(-1, 2) mgr.SBV(0, 2) mgr.SBV(1, 2) # Overflow and Underflow with self.assertRaises(ValueError): mgr.SBV(2, 2) with self.assertRaises(ValueError): mgr.SBV(-3, 2) # These should work without exceptions mgr.BV(0, 2) mgr.BV(1, 2) mgr.BV(2, 2) mgr.BV(3, 2) # Overflow with self.assertRaises(ValueError): mgr.BV(4, 2) # No negative number allowed with self.assertRaises(ValueError): mgr.BV(-1, 2) # SBV should behave as BV for positive numbers self.assertEqual(mgr.SBV(10, 16), mgr.BV(10, 16)) return
def test_exists(self): f = Exists([self.x], And(self.x, self.y)) g = qelim(f, solver_name="shannon") g = g.simplify() self.assertEqual(g, self.y)
def parse_string(self, strinput): hts = HTS() ts = TS() nodemap = {} node_covered = set([]) # list of tuples of var and cond_assign_list # cond_assign_list is tuples of (condition, value) # where everything is a pysmt FNode # for btor, the condition is always True ftrans = [] initlist = [] invarlist = [] invar_props = [] ltl_props = [] prop_count = 0 # clean string input, remove special characters from names for sc, rep in special_char_replacements.items(): strinput = strinput.replace(sc, rep) def getnode(nid): node_covered.add(nid) if int(nid) < 0: return Ite(BV2B(nodemap[str(-int(nid))]), BV(0, 1), BV(1, 1)) return nodemap[nid] def binary_op(bvop, bop, left, right): if (get_type(left) == BOOL) and (get_type(right) == BOOL): return bop(left, right) return bvop(B2BV(left), B2BV(right)) def unary_op(bvop, bop, left): if (get_type(left) == BOOL): return bop(left) return bvop(left) for line in strinput.split(NL): linetok = line.split() if len(linetok) == 0: continue if linetok[0] == COM: continue (nid, ntype, *nids) = linetok if ntype == SORT: (stype, *attr) = nids if stype == BITVEC: nodemap[nid] = BVType(int(attr[0])) node_covered.add(nid) if stype == ARRAY: nodemap[nid] = ArrayType(getnode(attr[0]), getnode(attr[1])) node_covered.add(nid) if ntype == WRITE: nodemap[nid] = Store(*[getnode(n) for n in nids[1:4]]) if ntype == READ: nodemap[nid] = Select(getnode(nids[1]), getnode(nids[2])) if ntype == ZERO: nodemap[nid] = BV(0, getnode(nids[0]).width) if ntype == ONE: nodemap[nid] = BV(1, getnode(nids[0]).width) if ntype == ONES: width = getnode(nids[0]).width nodemap[nid] = BV((2**width) - 1, width) if ntype == REDOR: width = get_type(getnode(nids[1])).width zeros = BV(0, width) nodemap[nid] = BVNot(BVComp(getnode(nids[1]), zeros)) if ntype == REDAND: width = get_type(getnode(nids[1])).width ones = BV((2**width) - 1, width) nodemap[nid] = BVComp(getnode(nids[1]), ones) if ntype == CONSTD: width = getnode(nids[0]).width nodemap[nid] = BV(int(nids[1]), width) if ntype == CONST: width = getnode(nids[0]).width try: nodemap[nid] = BV(bin_to_dec(nids[1]), width) except ValueError: if not all([i == 'x' or i == 'z' for i in nids[1]]): raise RuntimeError( "If not a valid number, only support " "all don't cares or high-impedance but got {}". format(nids[1])) # create a fresh variable for this non-deterministic constant nodemap[nid] = Symbol('const_' + nids[1], BVType(width)) ts.add_state_var(nodemap[nid]) Logger.warning( "Creating a fresh symbol for unsupported X/Z constant %s" % nids[1]) if ntype == STATE: if len(nids) > 1: nodemap[nid] = Symbol(nids[1], getnode(nids[0])) else: nodemap[nid] = Symbol((SN % nid), getnode(nids[0])) ts.add_state_var(nodemap[nid]) if ntype == INPUT: if len(nids) > 1: nodemap[nid] = Symbol(nids[1], getnode(nids[0])) else: nodemap[nid] = Symbol((SN % nid), getnode(nids[0])) ts.add_input_var(nodemap[nid]) if ntype == OUTPUT: # unfortunately we need to create an extra symbol just to have the output name # we could be smarter about this, but then this parser can't be greedy original_symbol = getnode(nids[0]) output_symbol = Symbol(nids[1], original_symbol.get_type()) nodemap[nid] = EqualsOrIff(output_symbol, original_symbol) invarlist.append(nodemap[nid]) node_covered.add(nid) ts.add_output_var(output_symbol) if ntype == AND: nodemap[nid] = binary_op(BVAnd, And, getnode(nids[1]), getnode(nids[2])) if ntype == CONCAT: nodemap[nid] = BVConcat(B2BV(getnode(nids[1])), B2BV(getnode(nids[2]))) if ntype == XOR: nodemap[nid] = binary_op(BVXor, Xor, getnode(nids[1]), getnode(nids[2])) if ntype == XNOR: nodemap[nid] = BVNot( binary_op(BVXor, Xor, getnode(nids[1]), getnode(nids[2]))) if ntype == NAND: bvop = lambda x, y: BVNot(BVAnd(x, y)) bop = lambda x, y: Not(And(x, y)) nodemap[nid] = binary_op(bvop, bop, getnode(nids[1]), getnode(nids[2])) if ntype == IMPLIES: nodemap[nid] = BVOr(BVNot(getnode(nids[1])), getnode(nids[2])) if ntype == NOT: nodemap[nid] = unary_op(BVNot, Not, getnode(nids[1])) if ntype == NEG: nodemap[nid] = unary_op(BVNeg, Not, getnode(nids[1])) if ntype == UEXT: nodemap[nid] = BVZExt(B2BV(getnode(nids[1])), int(nids[2])) if ntype == SEXT: nodemap[nid] = BVSExt(B2BV(getnode(nids[1])), int(nids[2])) if ntype == OR: nodemap[nid] = binary_op(BVOr, Or, getnode(nids[1]), getnode(nids[2])) if ntype == ADD: nodemap[nid] = BVAdd(B2BV(getnode(nids[1])), B2BV(getnode(nids[2]))) if ntype == SUB: nodemap[nid] = BVSub(B2BV(getnode(nids[1])), B2BV(getnode(nids[2]))) if ntype == UGT: nodemap[nid] = BVUGT(B2BV(getnode(nids[1])), B2BV(getnode(nids[2]))) if ntype == UGTE: nodemap[nid] = BVUGE(B2BV(getnode(nids[1])), B2BV(getnode(nids[2]))) if ntype == ULT: nodemap[nid] = BVULT(B2BV(getnode(nids[1])), B2BV(getnode(nids[2]))) if ntype == ULTE: nodemap[nid] = BVULE(B2BV(getnode(nids[1])), B2BV(getnode(nids[2]))) if ntype == SGT: nodemap[nid] = BVSGT(B2BV(getnode(nids[1])), B2BV(getnode(nids[2]))) if ntype == SGTE: nodemap[nid] = BVSGE(B2BV(getnode(nids[1])), B2BV(getnode(nids[2]))) if ntype == SLT: nodemap[nid] = BVSLT(B2BV(getnode(nids[1])), B2BV(getnode(nids[2]))) if ntype == SLTE: nodemap[nid] = BVSLE(B2BV(getnode(nids[1])), B2BV(getnode(nids[2]))) if ntype == EQ: nodemap[nid] = BVComp(B2BV(getnode(nids[1])), B2BV(getnode(nids[2]))) if ntype == NEQ: nodemap[nid] = BVNot(BVComp(getnode(nids[1]), getnode(nids[2]))) if ntype == MUL: nodemap[nid] = BVMul(B2BV(getnode(nids[1])), B2BV(getnode(nids[2]))) if ntype == SLICE: nodemap[nid] = BVExtract(B2BV(getnode(nids[1])), int(nids[3]), int(nids[2])) if ntype == SLL: nodemap[nid] = BVLShl(getnode(nids[1]), getnode(nids[2])) if ntype == SRA: nodemap[nid] = BVAShr(getnode(nids[1]), getnode(nids[2])) if ntype == SRL: nodemap[nid] = BVLShr(getnode(nids[1]), getnode(nids[2])) if ntype == ITE: if (get_type(getnode(nids[2])) == BOOL) or (get_type( getnode(nids[3])) == BOOL): nodemap[nid] = Ite(BV2B(getnode(nids[1])), B2BV(getnode(nids[2])), B2BV(getnode(nids[3]))) else: nodemap[nid] = Ite(BV2B(getnode(nids[1])), getnode(nids[2]), getnode(nids[3])) if ntype == NEXT: if (get_type(getnode(nids[1])) == BOOL) or (get_type( getnode(nids[2])) == BOOL): lval = TS.get_prime(getnode(nids[1])) rval = BV2B(getnode(nids[2])) else: lval = TS.get_prime(getnode(nids[1])) rval = getnode(nids[2]) nodemap[nid] = EqualsOrIff(lval, rval) ftrans.append((lval, [(TRUE(), rval)])) if ntype == INIT: if (get_type(getnode(nids[1])) == BOOL) or (get_type( getnode(nids[2])) == BOOL): nodemap[nid] = EqualsOrIff(BV2B(getnode(nids[1])), BV2B(getnode(nids[2]))) else: nodemap[nid] = EqualsOrIff(getnode(nids[1]), getnode(nids[2])) initlist.append(getnode(nid)) if ntype == CONSTRAINT: nodemap[nid] = BV2B(getnode(nids[0])) invarlist.append(getnode(nid)) if ntype == BAD: nodemap[nid] = getnode(nids[0]) if ASSERTINFO in line: filename_lineno = os.path.basename(nids[3]) assert_name = 'embedded_assertion_%s' % filename_lineno description = "Embedded assertion at line {1} in {0}".format( *filename_lineno.split(COLON_REP)) else: assert_name = 'embedded_assertion_%i' % prop_count description = 'Embedded assertion number %i' % prop_count prop_count += 1 # Following problem format (name, description, strformula) invar_props.append( (assert_name, description, Not(BV2B(getnode(nid))))) if nid not in nodemap: Logger.error("Unknown node type \"%s\"" % ntype) # get wirename if it exists if ntype not in {STATE, INPUT, OUTPUT, BAD}: # check for wirename, if it's an integer, then it's a node ref try: a = int(nids[-1]) except: try: wire = Symbol(str(nids[-1]), getnode(nids[0])) invarlist.append(EqualsOrIff(wire, B2BV(nodemap[nid]))) ts.add_var(wire) except: pass if Logger.level(1): name = lambda x: str(nodemap[x]) if nodemap[x].is_symbol() else x uncovered = [name(x) for x in nodemap if x not in node_covered] uncovered.sort() if len(uncovered) > 0: Logger.warning("Unlinked nodes \"%s\"" % ",".join(uncovered)) if not self.symbolic_init: init = simplify(And(initlist)) else: init = TRUE() invar = simplify(And(invarlist)) # instead of trans, we're using the ftrans format -- see below ts.set_behavior(init, TRUE(), invar) # add ftrans for var, cond_assign_list in ftrans: ts.add_func_trans(var, cond_assign_list) hts.add_ts(ts) return (hts, invar_props, ltl_props)