本文整理匯總了Python中z3.Solver方法的典型用法代碼示例。如果您正苦於以下問題:Python z3.Solver方法的具體用法?Python z3.Solver怎麽用?Python z3.Solver使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類z3
的用法示例。
在下文中一共展示了z3.Solver方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: solver
# 需要導入模塊: import z3 [as 別名]
# 或者: from z3 import Solver [as 別名]
def solver(self, timeout=None):
if not self.reuse_z3_solver or getattr(self._tls, 'solver', None) is None:
s = z3.Solver(ctx=self._context)
_add_memory_pressure(1024 * 1024 * 10)
if self.reuse_z3_solver:
# Store the Z3 solver to a thread-local storage if the reuse-solver option is enabled
self._tls.solver = s
else:
# Load the existing Z3 solver for this thread
s = self._tls.solver
s.reset()
# for some reason we always reset the solver anyway, so always clear it. REUSE_SOLVER is fundamentally broken
self._hash_to_constraint.clear()
# Configure timeouts
if timeout is not None:
if 'soft_timeout' in str(s.param_descrs()):
s.set('soft_timeout', timeout)
s.set('solver2_timeout', timeout)
else:
s.set('timeout', timeout)
return s
示例2: __init__
# 需要導入模塊: import z3 [as 別名]
# 或者: from z3 import Solver [as 別名]
def __init__(self, size=10):
"""
Args:
size (int): size of gate cache, in number of gates
Raises:
TranspilerError: if unable to import z3 solver
"""
if not HAS_Z3:
raise TranspilerError('z3-solver is required to use HoareOptimizer. '
'To install, run "pip install z3-solver".')
super().__init__()
self.solver = Solver()
self.variables = dict()
self.gatenum = dict()
self.gatecache = dict()
self.varnum = dict()
self.size = size
示例3: __init__
# 需要導入模塊: import z3 [as 別名]
# 或者: from z3 import Solver [as 別名]
def __init__(self, environment, logic, **options):
IncrementalTrackingSolver.__init__(self,
environment=environment,
logic=logic,
**options)
try:
self.z3 = z3.SolverFor(str(logic))
except z3.Z3Exception:
self.z3 = z3.Solver()
except z3.z3types.Z3Exception:
self.z3 = z3.Solver()
self.options(self)
self.declarations = set()
self.converter = Z3Converter(environment, z3_ctx=self.z3.ctx)
self.mgr = environment.formula_manager
self._name_cnt = 0
return
示例4: __init__
# 需要導入模塊: import z3 [as 別名]
# 或者: from z3 import Solver [as 別名]
def __init__(self, machine, produce_solution=PRODUCE_SOLUTION_CODE_COV,
known_solutions=None,
**kwargs):
"""Init a DSEPathConstraint
@machine: Machine of the targeted architecture instance
@produce_solution: (optional) if set, new solutions will be computed"""
super(DSEPathConstraint, self).__init__(machine, **kwargs)
# Dependency check
assert z3 is not None
# Init PathConstraint specifics structures
self.cur_solver = z3.Solver()
self.new_solutions = {} # solution identifier -> solution's model
self._known_solutions = set() # set of solution identifiers
self.z3_trans = Translator.to_language("z3")
self._produce_solution_strategy = produce_solution
self._previous_addr = None
self._history = None
if produce_solution == self.PRODUCE_SOLUTION_PATH_COV:
self._history = [] # List of addresses in the current path
示例5: restore_snapshot
# 需要導入模塊: import z3 [as 別名]
# 或者: from z3 import Solver [as 別名]
def restore_snapshot(self, snapshot, keep_known_solutions=True, **kwargs):
"""Restore a DSEPathConstraint snapshot
@keep_known_solutions: if set, do not forget solutions already found.
-> They will not appear in 'new_solutions'
"""
super(DSEPathConstraint, self).restore_snapshot(snapshot, **kwargs)
self.new_solutions.clear()
self.new_solutions.update(snapshot["new_solutions"])
self.cur_solver = z3.Solver()
self.cur_solver.add(snapshot["cur_constraints"])
if not keep_known_solutions:
self._known_solutions.clear()
if self._produce_solution_strategy == self.PRODUCE_SOLUTION_PATH_COV:
self._history = list(snapshot["_history"])
elif self._produce_solution_strategy == self.PRODUCE_SOLUTION_BRANCH_COV:
self._previous_addr = snapshot["_previous_addr"]
示例6: update_sha
# 需要導入模塊: import z3 [as 別名]
# 或者: from z3 import Solver [as 別名]
def update_sha(self, sha_data):
for arg, log_value, length_bytes in sha_data:
if log_value in self.log_sha_to_sym_sha:
continue
data = z3.BitVecVal(arg, length_bytes * 8)
if data.size() == 512:
data_words = svm_utils.split_bv_by_words(data)
data_words = [d.as_long() for d in data_words]
data_words = [self.log_sha_to_sym_sha.get(d, z3.BitVecVal(d, 256)) for d in data_words]
data = z3.simplify(z3.Concat(data_words))
sha_constraints, hash_vector = svm_utils.symbolic_keccak(self, data)
self.log_sha_to_sym_sha[log_value] = hash_vector
self.root_wstate.constraints.extend(sha_constraints)
solver = z3.Solver()
solver.add(self.root_wstate.constraints)
assert solver.check() == z3.sat
示例7: find_name_for_bit_at_index
# 需要導入模塊: import z3 [as 別名]
# 或者: from z3 import Solver [as 別名]
def find_name_for_bit_at_index(index, bit):
solver = z3.Solver()
NAME_LENGTH = 12 # arbitrary
name = [z3.BitVec("c%d" % i, 32) for i in range(NAME_LENGTH)]
for i in range(len(name)):
solver.add(z3.And(name[i] > 0, name[i] <= 0xff))
h1 = hash1(name)
solver.add(h1 == index)
h2 = hash2(name)
solver.add(h2 == bit)
h3 = hash3(name)
solver.add(z3.Extract(15, 0, h3) == h2) # for simplicity
if solver.check() == z3.sat:
return "".join(chr(solver.model()[c].as_long()) for c in name).encode("latin-1")
示例8: test_xor36
# 需要導入模塊: import z3 [as 別名]
# 或者: from z3 import Solver [as 別名]
def test_xor36(self):
'Test that CSE of the xor36 function is equivalent to original'
# pylint: disable=exec-used
pwd = os.path.dirname(os.path.realpath(__file__))
input_file = open(os.path.join(pwd, 'xor36_flat'), 'r')
input_string = input_file.read()
input_ast = ast.parse(input_string)
coderef = compile(ast.Expression(input_ast.body[0].value),
'<string>', 'eval')
jack = asttools.GetIdentifiers()
jack.visit(input_ast)
cse_string = cse.apply_cse(input_string)[0]
# get all assignment in one ast
assigns = cse_string[:cse_string.rfind('\n')]
cse_assign_ast = ast.parse(assigns, mode='exec')
assign_code = compile(cse_assign_ast, '<string>', mode='exec')
# get final expression in one ast
result_string = cse_string.splitlines()[-1]
result_ast = ast.Expression(ast.parse(result_string).body[0].value)
result_code = compile(result_ast, '<string>', mode='eval')
for var in list(jack.variables):
exec("%s = z3.BitVec('%s', 8)" % (var, var))
exec(assign_code)
sol = z3.Solver()
sol.add(eval(coderef) != eval(result_code))
self.assertEqual(sol.check().r, -1)
示例9: check_eq_z3
# 需要導入模塊: import z3 [as 別名]
# 或者: from z3 import Solver [as 別名]
def check_eq_z3(self, target, pattern):
'Check equivalence with z3'
# pylint: disable=exec-used
getid = asttools.GetIdentifiers()
getid.visit(target)
if getid.functions:
# not checking exprs with functions for now, because Z3
# does not seem to support function declaration with
# arbitrary number of arguments
return False
for var in self.variables:
exec("%s = z3.BitVec('%s', %d)" % (var, var, self.nbits))
target_ast = deepcopy(target)
target_ast = Unflattening().visit(target_ast)
ast.fix_missing_locations(target_ast)
code1 = compile(ast.Expression(target_ast), '<string>', mode='eval')
eval_pattern = deepcopy(pattern)
EvalPattern(self.wildcards).visit(eval_pattern)
eval_pattern = Unflattening().visit(eval_pattern)
ast.fix_missing_locations(eval_pattern)
getid.reset()
getid.visit(eval_pattern)
if getid.functions:
# same reason as before, not using Z3 if there are
# functions
return False
gvar = asttools.GetIdentifiers()
gvar.visit(eval_pattern)
if any(var.isupper() for var in gvar.variables):
# do not check if all patterns have not been replaced
return False
code2 = compile(ast.Expression(eval_pattern), '<string>', mode='eval')
sol = z3.Solver()
if isinstance(eval(code1), int) and eval(code1) == 0:
# cases where target == 0 are too permissive
return False
sol.add(eval(code1) != eval(code2))
return sol.check().r == -1
示例10: get_model
# 需要導入模塊: import z3 [as 別名]
# 或者: from z3 import Solver [as 別名]
def get_model(self, target, pattern):
'When target is constant and wildcards have no value yet'
# pylint: disable=exec-used
if target.n == 0:
# zero is too permissive
return False
getwild = asttools.GetIdentifiers()
getwild.visit(pattern)
if getwild.functions:
# not getting model for expr with functions
return False
wilds = getwild.variables
# let's reduce the model to one wildcard for now
# otherwise it adds a lot of checks...
if len(wilds) > 1:
return False
wil = wilds.pop()
if wil in self.wildcards:
if not isinstance(self.wildcards[wil], ast.Num):
return False
folded = deepcopy(pattern)
folded = Unflattening().visit(folded)
EvalPattern(self.wildcards).visit(folded)
folded = asttools.ConstFolding(folded, self.nbits).visit(folded)
return folded.n == target.n
else:
exec("%s = z3.BitVec('%s', %d)" % (wil, wil, self.nbits))
eval_pattern = deepcopy(pattern)
eval_pattern = Unflattening().visit(eval_pattern)
ast.fix_missing_locations(eval_pattern)
code = compile(ast.Expression(eval_pattern), '<string>', mode='eval')
sol = z3.Solver()
sol.add(target.n == eval(code))
if sol.check().r == 1:
model = sol.model()
for inst in model.decls():
self.wildcards[str(inst)] = ast.Num(int(model[inst].as_long()))
return True
return False
示例11: __init__
# 需要導入模塊: import z3 [as 別名]
# 或者: from z3 import Solver [as 別名]
def __init__(self,
vars = None,
funcs = None,
collection_depth : int = None,
min_collection_depth : int = 0,
validate_model : bool = True,
model_callback = None,
logic : str = None,
timeout : float = None,
do_cse : bool = True):
if collection_depth is None:
collection_depth = collection_depth_opt.value
self.vars = OrderedSet()
self.funcs = OrderedDict()
self.min_collection_depth = min_collection_depth
self.collection_depth = collection_depth
self.validate_model = validate_model
self.model_callback = model_callback
self._env = OrderedDict()
self.stk = []
self.do_cse = do_cse
with _LOCK:
ctx = z3.Context()
solver = z3.Solver(ctx=ctx) if logic is None else z3.SolverFor(logic, ctx=ctx)
if timeout is not None:
solver.set("timeout", int(timeout * 1000))
solver.set("core.validate", validate_model)
visitor = ToZ3(ctx, solver)
self.visitor = visitor
self.z3_solver = solver
self._create_vars(vars=vars or (), funcs=funcs or {})
示例12: emul
# 需要導入模塊: import z3 [as 別名]
# 或者: from z3 import Solver [as 別名]
def emul(self, ir_arch, ctx=None, step=False):
# Init
ctx_init = {}
if ctx is not None:
ctx_init.update(ctx)
solver = z3.Solver()
symb_exec = SymbolicExecutionEngine(ir_arch, ctx_init)
history = self.history[::-1]
history_size = len(history)
translator = Translator.to_language("z3")
size = self._ircfg.IRDst.size
for hist_nb, loc_key in enumerate(history, 1):
if hist_nb == history_size and loc_key == self.initial_state.loc_key:
line_nb = self.initial_state.line_nb
else:
line_nb = None
irb = self.irblock_slice(self._ircfg.blocks[loc_key], line_nb)
# Emul the block and get back destination
dst = symb_exec.eval_updt_irblock(irb, step=step)
# Add constraint
if hist_nb < history_size:
next_loc_key = history[hist_nb]
expected = symb_exec.eval_expr(ExprLoc(next_loc_key, size))
solver.add(self._gen_path_constraints(translator, dst, expected))
# Save the solver
self._solver = solver
# Return only inputs values (others could be wrongs)
return {
element: symb_exec.eval_expr(element)
for element in self.inputs
}
示例13: equiv
# 需要導入模塊: import z3 [as 別名]
# 或者: from z3 import Solver [as 別名]
def equiv(z3_expr1, z3_expr2):
s = z3.Solver()
s.add(z3.Not(z3_expr1 == z3_expr2))
return s.check() == z3.unsat
示例14: check
# 需要導入模塊: import z3 [as 別名]
# 或者: from z3 import Solver [as 別名]
def check(expr_in, expr_out):
"""Check that expr_in is always equals to expr_out"""
print("Ensure %s = %s" % (expr_in, expr_out))
solver = z3.Solver()
solver.add(trans.from_expr(expr_in) != trans.from_expr(expr_out))
result = solver.check()
if result != z3.unsat:
print("ERROR: a counter-example has been founded:")
model = solver.model()
print(model)
print("Reinjecting in the simplifier:")
to_rep = {}
expressions = expr_in.get_r().union(expr_out.get_r())
for expr in expressions:
value = model.eval(trans.from_expr(expr))
if hasattr(value, "as_long"):
new_val = ExprInt(value.as_long(), expr.size)
else:
raise RuntimeError("Unable to reinject %r" % value)
to_rep[expr] = new_val
new_expr_in = expr_in.replace_expr(to_rep)
new_expr_out = expr_out.replace_expr(to_rep)
print("Check %s = %s" % (new_expr_in, new_expr_out))
simp_in = expr_simp_explicit(new_expr_in)
simp_out = expr_simp_explicit(new_expr_out)
print("[%s] %s = %s" % (simp_in == simp_out, simp_in, simp_out))
# Either the simplification does not stand, either the test is wrong
raise RuntimeError("Bad simplification")
示例15: get_state_solver
# 需要導入模塊: import z3 [as 別名]
# 或者: from z3 import Solver [as 別名]
def get_state_solver(gstate):
solver = z3.Solver()
solver.set('timeout', 3 * 60 * 1000)
solver.add(gstate.wstate.constraints)
res = solver.check()
if res == z3.unknown: logging.info(f'{gstate.wstate.trace} gstate check timeout')
return solver if res == z3.sat else None