Python claripy.If() Examples

The following are 30 code examples of claripy.If(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module claripy , or try the search function .
Example #1
Source File: irop.py    From angr with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def generic_compare(self, args, comparison):
        if self._vector_size is not None:
            res_comps = []
            for i in reversed(range(self._vector_count)):
                a_comp = claripy.Extract((i+1) * self._vector_size - 1,
                                          i * self._vector_size,
                                          args[0])
                b_comp = claripy.Extract((i+1) * self._vector_size - 1,
                                          i * self._vector_size,
                                          args[1])
                res_comps.append(claripy.If(comparison(a_comp, b_comp),
                                         claripy.BVV(-1, self._vector_size),
                                         claripy.BVV(0, self._vector_size)))
            return claripy.Concat(*res_comps)
        else:
            return claripy.If(comparison(args[0], args[1]), claripy.BVV(1, 1), claripy.BVV(0, 1)) 
Example #2
Source File: dirty.py    From angr with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def amd64g_check_ldmxcsr(state, mxcsr):

    rmode = state.solver.LShR(mxcsr, 13) & 3

    ew = state.solver.If(
            (mxcsr & 0x1F80) != 0x1F80,
            state.solver.BVV(EmWarn_X86_sseExns, 64),
            state.solver.If(
                mxcsr & (1 << 15) != 0,
                state.solver.BVV(EmWarn_X86_fz, 64),
                state.solver.If(
                    mxcsr & (1 << 6) != 0,
                    state.solver.BVV(EmWarn_X86_daz, 64),
                    state.solver.BVV(EmNote_NONE, 64)
                )
            )
         )

    return (ew << 32) | rmode, ()


# see canonical implementation of this in guest_amd64_helpers.c 
Example #3
Source File: dirty.py    From angr with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def x86g_dirtyhelper_loadF80le(state, addr):
    tbyte = state.memory.load(addr, size=10, endness='Iend_LE')
    sign = tbyte[79]
    exponent = tbyte[78:64]
    mantissa = tbyte[62:0]

    normalized_exponent = exponent[10:0] - 16383 + 1023
    zero_exponent = state.solver.BVV(0, 11)
    inf_exponent = state.solver.BVV(-1, 11)
    final_exponent = claripy.If(exponent == 0, zero_exponent, claripy.If(exponent == -1, inf_exponent, normalized_exponent))

    normalized_mantissa = tbyte[62:11]
    zero_mantissa = claripy.BVV(0, 52)
    inf_mantissa = claripy.BVV(-1, 52)
    final_mantissa = claripy.If(exponent == 0, zero_mantissa, claripy.If(exponent == -1, claripy.If(mantissa == 0, zero_mantissa, inf_mantissa), normalized_mantissa))

    qword = claripy.Concat(sign, final_exponent, final_mantissa)
    assert len(qword) == 64
    return qword, [] 
Example #4
Source File: dirty.py    From angr with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def x86g_dirtyhelper_storeF80le(state, addr, qword):
    sign = qword[63]
    exponent = qword[62:52]
    mantissa = qword[51:0]

    normalized_exponent = exponent.zero_extend(4) - 1023 + 16383
    zero_exponent = state.solver.BVV(0, 15)
    inf_exponent = state.solver.BVV(-1, 15)
    final_exponent = claripy.If(exponent == 0, zero_exponent, claripy.If(exponent == -1, inf_exponent, normalized_exponent))

    normalized_mantissa = claripy.Concat(claripy.BVV(1, 1), mantissa, claripy.BVV(0, 11))
    zero_mantissa = claripy.BVV(0, 64)
    inf_mantissa = claripy.BVV(-1, 64)
    final_mantissa = claripy.If(exponent == 0, zero_mantissa, claripy.If(exponent == -1, claripy.If(mantissa == 0, zero_mantissa, inf_mantissa), normalized_mantissa))

    tbyte = claripy.Concat(sign, final_exponent, final_mantissa)
    assert len(tbyte) == 80
    state.memory.store(addr, tbyte, endness='Iend_LE')
    return None, [] 
Example #5
Source File: irop.py    From angr with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _op_generic_QSub(self, args):
        """
        Saturating subtract.
        """
        components = []
        for a, b in self.vector_args(args):
            top_a = a[self._vector_size-1]
            top_b = b[self._vector_size-1]
            res = a - b
            top_r = res[self._vector_size-1]
            if self.is_signed:
                big_top_r = (~top_r).zero_extend(self._vector_size-1)
                cap = (claripy.BVV(-1, self._vector_size)//2) + big_top_r
                cap_cond = ((top_a ^ top_b) & (top_a ^ top_r)) == 1
            else:
                cap = claripy.BVV(0, self._vector_size)
                cap_cond = claripy.UGT(res, a)
            components.append(claripy.If(cap_cond, cap, res))
        return claripy.Concat(*components) 
Example #6
Source File: test_expression.py    From claripy with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_canonical():
    x1 = claripy.BVS('x', 32)
    b1 = claripy.BoolS('b')
    c1 = claripy.BoolS('c')
    x2 = claripy.BVS('x', 32)
    b2 = claripy.BoolS('b')
    c2 = claripy.BoolS('c')

    assert x1.canonicalize()[-1] is x2.canonicalize()[-1]

    y1 = claripy.If(claripy.And(b1, c1), x1, ((x1+x1)*x1)+1)
    y2 = claripy.If(claripy.And(b2, c2), x2, ((x2+x2)*x2)+1)

    one_names = frozenset.union(x1.variables, b1.variables, c1.variables)
    two_names = frozenset.union(x2.variables, b2.variables, c2.variables)

    assert frozenset.union(*[a.variables for a in y1.recursive_leaf_asts]) == one_names
    assert frozenset.union(*[a.variables for a in y2.recursive_leaf_asts]) == two_names
    assert y1.canonicalize()[-1] is y2.canonicalize()[-1] 
Example #7
Source File: test_expression.py    From claripy with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_if_stuff():
    x = claripy.BVS('x', 32)
    #y = claripy.BVS('y', 32)

    c = claripy.If(x > 10, (claripy.If(x > 10, x*3, x*2)), x*4) + 2
    cc = claripy.If(x > 10, x*3, x*4) + 2
    ccc = claripy.If(x > 10, x*3+2, x*4+2)
    cccc = x*claripy.If(x > 10, claripy.BVV(3, 32), claripy.BVV(4, 32)) + 2

    nose.tools.assert_is(c, cc)
    nose.tools.assert_is(c.ite_excavated, ccc)
    nose.tools.assert_is(ccc.ite_burrowed, cccc)

    i = c + c
    ii = claripy.If(x > 10, (x*3+2)+(x*3+2), (x*4+2)+(x*4+2))
    nose.tools.assert_is(i.ite_excavated, ii)

    cn = claripy.If(x <= 10, claripy.BVV(0x10, 32), 0x20)
    iii = c + cn
    iiii = claripy.If(x > 10, (x*3+2)+0x20, (x*4+2)+0x10)
    nose.tools.assert_is(iii.ite_excavated, iiii) 
Example #8
Source File: ccall.py    From angr with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def pc_actions_ADC(state, nbits, cc_dep1, cc_dep2, cc_ndep, platform=None):
    old_c = cc_ndep & data[platform]['CondBitMasks']['G_CC_MASK_C']
    arg_l = cc_dep1
    arg_r = cc_dep2 ^ old_c
    res = (arg_l + arg_r) + old_c

    cf = claripy.If(
            old_c != 0,
            claripy.If(res <= arg_l, claripy.BVV(1, 1), claripy.BVV(0, 1)),
            claripy.If(res < arg_l, claripy.BVV(1, 1), claripy.BVV(0, 1))
    )
    pf = calc_paritybit(res)
    af = (res ^ arg_l ^ arg_r)[data[platform]['CondBitOffsets']['G_CC_SHIFT_A']]
    zf = calc_zerobit(res)
    sf = res[nbits - 1]
    of = ((arg_l ^ arg_r ^ -1) & (arg_l ^ res))[nbits-1]

    return pc_make_rdata(data[platform]['size'], cf, pf, af, zf, sf, of, platform=platform) 
Example #9
Source File: ccall.py    From angr with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def amd64g_check_ldmxcsr(state, mxcsr):
    rmode = claripy.LShR(mxcsr, 13) & 3

    ew = claripy.If(
            (mxcsr & 0x1F80) != 0x1F80,
            claripy.BVV(EmWarn_X86_sseExns, 64),
            claripy.If(
                mxcsr & (1<<15) != 0,
                claripy.BVV(EmWarn_X86_fz, 64),
                claripy.If(
                    mxcsr & (1<<6) != 0,
                    claripy.BVV(EmWarn_X86_daz, 64),
                    claripy.BVV(EmNote_NONE, 64)
                )
            )
         )

    return (ew << 32) | rmode

#################
### ARM Flags ###
################# 
Example #10
Source File: test_analyzer.py    From pakala with GNU General Public License v3.0 5 votes vote down vote up
def test_send_back_if_impossible_block(self):
        self.state.calls.append(
            self.get_call(
                claripy.If(
                    self.env.block_number > 100000000000,
                    self.env.value + Web3.toWei(1, "ether"),
                    0,
                )
            )
        )
        self.assertFalse(self.check_state(self.state)) 
Example #11
Source File: irop.py    From angr with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _op_generic_CmpORD(self, args):
        x = args[0]
        y = args[1]
        s = self._from_size
        cond = claripy.SLT(x, y) if self.is_signed else claripy.ULT(x, y)
        return claripy.If(x == y, claripy.BVV(0x2, s), claripy.If(cond, claripy.BVV(0x8, s), claripy.BVV(0x4, s))) 
Example #12
Source File: irop.py    From angr with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _op_fgeneric_CmpEQ(self, a0, a1): # pylint: disable=no-self-use
        # for cmpps_eq stuff, i.e. Iop_CmpEQ32Fx4
        return claripy.If(claripy.fpEQ(a0, a1), claripy.BVV(-1, len(a0)), claripy.BVV(0, len(a0))) 
Example #13
Source File: irop.py    From angr with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _fgeneric_minmax(cmp_op, a, b):
        a, b = a.raw_to_fp(), b.raw_to_fp()
        return claripy.If(cmp_op(a, b), a, b) 
Example #14
Source File: irop.py    From angr with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _op_generic_StoU_saturation(self, value, min_value, max_value): #pylint:disable=no-self-use
        """
        Return unsigned saturated BV from signed BV.
        Min and max value should be unsigned.
        """
        return claripy.If(
            claripy.SGT(value, max_value),
            max_value,
            claripy.If(claripy.SLT(value, min_value), min_value, value)) 
Example #15
Source File: irop.py    From angr with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _op_generic_Perm(self, args):
        ordered_0 = list(reversed(args[0].chop(self._vector_size)))
        ordered_1 = list(reversed(args[1].chop(self._vector_size)))
        res = []
        nbits = int(math.log2(self._vector_size))
        for pword in ordered_1:
            switch = pword[nbits-1:0]
            kill = pword[self._vector_size - 1]
            switched = claripy.ite_cases([(switch == i, v) for i, v in enumerate(ordered_0[:-1])], ordered_0[-1])
            killed = claripy.If(kill == 1, 0, switched)
            res.append(killed)

        return claripy.Concat(*reversed(res)) 
Example #16
Source File: datalayer.py    From angr with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _perform_vex_expr_ITE(self, cond, ifTrue, ifFalse):
        return claripy.If(cond != 0, ifTrue, ifFalse) 
Example #17
Source File: character.py    From angr with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def run(self, char_ref):
        log.debug('Called SimProcedure java.lang.Character.isDigit with args: {}'.format(char_ref))
        char_str = self.state.memory.load(char_ref)

        constraint = claripy.StrIsDigit(char_str)

        return claripy.If(constraint, claripy.BVV(1, 32), claripy.BVV(0, 32)) 
Example #18
Source File: character.py    From angr with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def run(self, char_ref):
        log.debug('Called SimProcedure java.lang.Character.isSpaceChar with args: {}'.format(char_ref))
        char_str = self.state.memory.load(char_ref)

        # Should we add other unicode SPACE_SEPARATOR?
        constraint = claripy.If(char_str == ' ', claripy.BVV(1, 32), claripy.BVV(0, 32))

        return constraint 
Example #19
Source File: sm.py    From pakala with GNU General Public License v3.0 5 votes vote down vote up
def bool_to_bv(b):
    return claripy.If(b, BVV_1, BVV_0) 
Example #20
Source File: irop.py    From angr with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _op_generic_Clz(self, args):
        """Count the leading zeroes"""
        piece_size = len(args[0])
        wtf_expr = claripy.BVV(piece_size, piece_size)
        for a in range(piece_size):
            bit = claripy.Extract(a, a, args[0])
            wtf_expr = claripy.If(bit==1, claripy.BVV(piece_size-a-1, piece_size), wtf_expr)
        return wtf_expr 
Example #21
Source File: test_analyzer.py    From pakala with GNU General Public License v3.0 5 votes vote down vote up
def test_send_back_if_possible_block(self):
        self.state.calls.append(
            self.get_call(
                claripy.If(
                    self.env.block_number < 100000000000,
                    self.env.value + Web3.toWei(1, "ether"),
                    0,
                )
            )
        )
        self.assertTrue(self.check_state(self.state)) 
Example #22
Source File: analyzer.py    From pakala with GNU General Public License v3.0 5 votes vote down vote up
def _fill_actual_storage(self):
        try:
            storage_keys = [
                self.web3.toInt(hexstr=k)
                for k in self.web3.parity.listStorageKeys(
                    self.hex_addr, MAX_STORAGE_KEYS, None, self.web3.eth.defaultBlock
                )
            ]
        except Exception as e:
            # If we cannot list storage keys, let's read the beginning of the
            # space, and below we will mark that it's not exhaustive anyway.
            logger.warning(
                "Cannot list storage keys (%s). We will lose a bit of accuracy. "
                "Try to use a node that supports the parity_listStorageKeys RPC. ",
                e.__class__.__name__,
            )
            storage_keys = STORAGE_KEYS_WHEN_CANNOT_LIST
            self.actual_storage_exhaustive = False
        else:
            assert len(storage_keys) <= MAX_STORAGE_KEYS
            self.actual_storage_exhaustive = len(storage_keys) < MAX_STORAGE_KEYS

        self.actual_storage = {k: self._read_storage_key(k) for k in storage_keys}

        logger.info(
            "Loaded %i storage slots from the contract (%s). %i non-zero.",
            len(storage_keys),
            "exhaustive" if self.actual_storage_exhaustive else "non-exhaustive",
            sum(1 for v in self.actual_storage.values() if v != 0),
        )
        logger.debug("actual_storage: %r", self.actual_storage) 
Example #23
Source File: test_expression.py    From claripy with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_smudging():
    x = claripy.BVS('x', 32)
    y = x+1
    nose.tools.assert_true(isinstance(y.args[1], claripy.ast.BV))
    nose.tools.assert_equal(y.args[1].args[0], 1)
    nose.tools.assert_equal(y.args[1].args[1], 32)

    x = claripy.BVS('x', 32)
    y = x*1
    z = y+1
    nose.tools.assert_true(isinstance(y.args[1], claripy.ast.BV))
    nose.tools.assert_equal(y.args[1].args[0], 1)
    nose.tools.assert_equal(y.args[1].args[1], 32)

    nose.tools.assert_true(isinstance(z.args[1], claripy.ast.BV))
    nose.tools.assert_equal(z.args[1].args[0], 1)
    nose.tools.assert_equal(z.args[1].args[1], 32)

    ccc = claripy.If(x > 10, x*3+2, x*4+2)
    nose.tools.assert_true(isinstance(ccc.args[1].args[1], claripy.ast.BV))
    nose.tools.assert_equal(ccc.args[1].args[1].args[0], 2)
    nose.tools.assert_equal(ccc.args[1].args[1].args[1], 32)

    x = claripy.BVS('x', 32)
    y = x + "AAAA"
    nose.tools.assert_true(isinstance(y.args[1], claripy.ast.BV))
    nose.tools.assert_equal(y.args[1].args[0], 0x41414141)
    nose.tools.assert_equal(y.args[1].args[1], 32) 
Example #24
Source File: test_solver.py    From claripy with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def raw_composite_discrepancy(reuse_z3_solver):
    claripy._backend_z3.reuse_z3_solver = reuse_z3_solver

    a = claripy.BVS("a", 8)
    b = claripy.BVS("b", 8)
    x = claripy.BVS("x", 32)
    y = claripy.BVS("y", 32)
    z = claripy.BVS("z", 32)

    xy = x + y
    dst = claripy.BVV(0xbaaaaf50, 32) + xy
    constraints = [ ]
    constraints.append(x <= 0x1)
    constraints.append(x != 0x0)
    constraints.append(claripy.SignExt(24, claripy.If(x > 0x0, a, 0)) != 0xa)
    constraints.append(x < 0x80)
    constraints.append(y <= 0x1)
    constraints.append(x == 0x1)
    constraints.append((0xbaaaaf50 + x) == 0xbaaaaf51)
    constraints.append(y != 0x0)
    constraints.append(claripy.SignExt(24, claripy.If(y > 0x0, b, 0)) != 0xa)
    constraints.append((x + y) < 0x80)
    constraints.append(z <= 0x1)
    constraints.append((x + y) == 0x2)

    sn = claripy.Solver()
    sc = claripy.SolverComposite()

    sn.add(constraints)
    sc.add(constraints)
    print(sn.max(dst), sc.max(dst))
    print(sn.min(dst), sc.min(dst))
    assert sn.max(dst) == sc.max(dst)
    assert sn.min(dst) == sc.min(dst) 
Example #25
Source File: test_solver.py    From claripy with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_zero_division_in_cache_mixin():
    # Bug in the caching backend. See issue #49 on github.
    num = claripy.BVS('num', 256)
    denum = claripy.BVS('denum', 256)
    e = claripy.BVS('e', 256)
    s = claripy.Solver()
    s.add(e == 8)
    assert s.satisfiable()
    s.add(claripy.If(denum == 0, 0, num / denum) == e)
    assert s.satisfiable()
    # As a bonus:
    s.add(num == 16)
    assert s.satisfiable()
    s.add(denum == 3)
    assert not s.satisfiable() 
Example #26
Source File: test_balancer.py    From claripy with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_complex_case_2():
    x = claripy.BVS('x', 32)
    expr = claripy.ZeroExt(31,
                           claripy.If(claripy.BVV(0xc, 32) < x,
                                      claripy.BVV(1, 1),
                                      claripy.BVV(0, 1)
                                      )
                           ) == claripy.BVV(0, 32)
    s, r = claripy.balancer.Balancer(claripy.backends.vsa, expr).compat_ret

    assert s is True
    assert len(r) == 1
    assert r[0][0] is x 
Example #27
Source File: irop.py    From angr with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _op_generic_Ctz(self, args):
        """Count the trailing zeroes"""
        piece_size = len(args[0])
        wtf_expr = claripy.BVV(piece_size, piece_size)
        for a in reversed(range(piece_size)):
            bit = claripy.Extract(a, a, args[0])
            wtf_expr = claripy.If(bit == 1, claripy.BVV(a, piece_size), wtf_expr)
        return wtf_expr 
Example #28
Source File: ccall.py    From angr with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def calc_zerobit(p):
    return claripy.If(p == 0, claripy.BVV(1, 1), claripy.BVV(0, 1)) 
Example #29
Source File: ccall.py    From angr with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def boolean_extend(O, a, b, size):
    return claripy.If(O(a, b), claripy.BVV(1, size), claripy.BVV(0, size)) 
Example #30
Source File: ccall.py    From angr with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def pc_actions_ADD(state, nbits, arg_l, arg_r, cc_ndep, platform=None):
    data_mask, sign_mask = pc_preamble(nbits)
    res = arg_l + arg_r

    cf = claripy.If(claripy.ULT(res, arg_l), claripy.BVV(1, 1), claripy.BVV(0, 1))
    pf = calc_paritybit(res)
    af = (res ^ arg_l ^ arg_r)[data[platform]['CondBitOffsets']['G_CC_SHIFT_A']]
    zf = calc_zerobit(res)
    sf = res[nbits - 1:nbits - 1]
    of = ((arg_l ^ arg_r ^ data_mask) & (arg_l ^ res))[nbits - 1:nbits - 1]

    return pc_make_rdata(data[platform]['size'], cf, pf, af, zf, sf, of, platform=platform)