Ejemplo n.º 1
0
 def offset_to_ptr(base, offset):
     """
     Return an expression representing the @base + @offset
     @base: symbolic base address
     @offset: relative offset integer to the @base address
     """
     if base.is_id(INTERNAL_INTBASE_NAME):
         ptr = ExprInt(offset, base.size)
     elif offset == 0:
         ptr = base
     else:
         ptr = base + ExprInt(offset, base.size)
     return ptr.canonize()
Ejemplo n.º 2
0
def emul_symb(ir_arch, ircfg, mdis, states_todo, states_done):
    while states_todo:
        addr, symbols, conds = states_todo.pop()
        print '*' * 40, "addr", addr, '*' * 40
        if (addr, symbols, conds) in states_done:
            print 'Known state, skipping', addr
            continue
        states_done.add((addr, symbols, conds))
        symbexec = SymbolicExecutionEngine(ir_arch)
        symbexec.symbols = symbols.copy()
        if ir_arch.pc in symbexec.symbols:
            del symbexec.symbols[ir_arch.pc]
        irblock = get_block(ir_arch, ircfg, mdis, addr)

        print 'Run block:'
        print irblock
        addr = symbexec.eval_updt_irblock(irblock)
        print 'Final state:'
        symbexec.dump(mems=False)

        assert addr is not None
        if isinstance(addr, ExprCond):
            # Create 2 states, each including complementary conditions
            cond_group_a = {addr.cond: ExprInt(0, addr.cond.size)}
            cond_group_b = {addr.cond: ExprInt(1, addr.cond.size)}
            addr_a = expr_simp(
                symbexec.eval_expr(addr.replace_expr(cond_group_a), {}))
            addr_b = expr_simp(
                symbexec.eval_expr(addr.replace_expr(cond_group_b), {}))
            if not (addr_a.is_int() or addr_a.is_loc() and addr_b.is_int()
                    or addr_b.is_loc()):
                print str(addr_a), str(addr_b)
                raise ValueError("Unsupported condition")
            if isinstance(addr_a, ExprInt):
                addr_a = int(addr_a.arg)
            if isinstance(addr_b, ExprInt):
                addr_b = int(addr_b.arg)
            states_todo.add((addr_a, symbexec.symbols.copy(),
                             tuple(list(conds) + cond_group_a.items())))
            states_todo.add((addr_b, symbexec.symbols.copy(),
                             tuple(list(conds) + cond_group_b.items())))
        elif addr == ret_addr:
            print 'Return address reached'
            continue
        elif addr.is_int():
            addr = int(addr.arg)
            states_todo.add((addr, symbexec.symbols.copy(), tuple(conds)))
        elif addr.is_loc():
            states_todo.add((addr, symbexec.symbols.copy(), tuple(conds)))
        else:
            raise ValueError("Unsupported destination")
Ejemplo n.º 3
0
def simp_zeroext_eq_cst(_, expr):
    """A.zeroExt(X) == int => A == int[:A.size]"""
    if not expr.is_op(TOK_EQUAL):
        return expr
    arg1, arg2 = expr.args
    if not arg2.is_int():
        return expr
    if not (arg1.is_op() and arg1.op.startswith("zeroExt")):
        return expr
    src = arg1.args[0]
    if int(arg2) > (1 << src.size):
        # Always false
        return ExprInt(0, expr.size)
    return ExprOp(TOK_EQUAL, src, ExprInt(int(arg2), src.size))
Ejemplo n.º 4
0
def jmp(ir, instr, reg_or_imm):
    """JMP - Change PC to a register content or an immediate.
       Note: the behavior in VLIW mode is not implemented"""

    take_jmp = ExprInt(1, 32)

    if isinstance(reg_or_imm, ExprId):
        # PC <- Rm31..1||0
        new_PC = ExprAssign(PC, reg_or_imm)
    else:
        # PC <- PC31..28||0000||(target24)23..1||0
        new_PC = ExprAssign(PC, ExprOp("+", ExprOp("&", PC, ExprInt(0xF0000000, 32)), reg_or_imm))

    return [new_PC, ExprAssign(ir.IRDst, new_PC)], []
Ejemplo n.º 5
0
def simp_cond(e_s, expr):
    "Common simplifications on ExprCond"
    # eval exprcond src1/src2 with satifiable/unsatisfiable condition
    # propagation
    if (not expr.cond.is_int()) and expr.cond.size == 1:
        src1 = expr.src1.replace_expr({expr.cond: ExprInt(1, 1)})
        src2 = expr.src2.replace_expr({expr.cond: ExprInt(0, 1)})
        if src1 != expr.src1 or src2 != expr.src2:
            return ExprCond(expr.cond, src1, src2)

    # -A ? B:C => A ? B:C
    if expr.cond.is_op('-') and len(expr.cond.args) == 1:
        expr = ExprCond(expr.cond.args[0], expr.src1, expr.src2)
    # a?x:x
    elif expr.src1 == expr.src2:
        expr = expr.src1
    # int ? A:B => A or B
    elif expr.cond.is_int():
        if expr.cond.arg == 0:
            expr = expr.src2
        else:
            expr = expr.src1
    # a?(a?b:c):x => a?b:x
    elif expr.src1.is_cond() and expr.cond == expr.src1.cond:
        expr = ExprCond(expr.cond, expr.src1.src1, expr.src2)
    # a?x:(a?b:c) => a?x:c
    elif expr.src2.is_cond() and expr.cond == expr.src2.cond:
        expr = ExprCond(expr.cond, expr.src1, expr.src2.src2)
    # a|int ? b:c => b with int != 0
    elif (expr.cond.is_op('|') and
          expr.cond.args[1].is_int() and
          expr.cond.args[1].arg != 0):
        return expr.src1

    # (C?int1:int2)?(A:B) =>
    elif (expr.cond.is_cond() and
          expr.cond.src1.is_int() and
          expr.cond.src2.is_int()):
        int1 = expr.cond.src1.arg.arg
        int2 = expr.cond.src2.arg.arg
        if int1 and int2:
            expr = expr.src1
        elif int1 == 0 and int2 == 0:
            expr = expr.src2
        elif int1 == 0 and int2:
            expr = ExprCond(expr.cond.cond, expr.src2, expr.src1)
        elif int1 and int2 == 0:
            expr = ExprCond(expr.cond.cond, expr.src1, expr.src2)
    return expr
Ejemplo n.º 6
0
    def post_add_bloc(self, block, ir_blocks):
        IntermediateRepresentation.post_add_bloc(self, block, ir_blocks)
        for irb in ir_blocks:
            pc_val = None
            lr_val = None
            for assignblk in irb.irs:
                pc_val = assignblk.get(self.arch.regs.PC, pc_val)
                lr_val = assignblk.get(self.arch.regs.RA, lr_val)

            if pc_val is None or lr_val is None:
                continue
            if not expr_is_int_or_label(lr_val):
                continue
            if expr_is_label(lr_val):
                lr_val = ExprInt(lr_val.name.offset, 32)

            line = block.lines[-2]
            if lr_val.arg != line.offset + 8:
                raise ValueError("Wrong arg")

            # CALL
            lbl = block.get_next()
            new_lbl = self.gen_label()
            irs = self.call_effects(pc_val, line)
            irs.append(
                AssignBlock(
                    [ExprAff(self.IRDst, ExprId(lbl, size=self.pc.size))]))
            nblock = IRBlock(new_lbl, irs)
            nblock.lines = [line] * len(irs)
            self.blocks[new_lbl] = nblock
            irb.dst = ExprId(new_lbl, size=self.pc.size)
Ejemplo n.º 7
0
def simp_ext(_, expr):
    if expr.op.startswith('zeroExt_'):
        arg = expr.args[0]
        if expr.size == arg.size:
            return arg
        return ExprCompose(arg, ExprInt(0, expr.size - arg.size))

    if expr.op.startswith("signExt_"):
        arg = expr.args[0]
        add_size = expr.size - arg.size
        new_expr = ExprCompose(
            arg,
            ExprCond(arg.msb(), ExprInt(size2mask(add_size), add_size),
                     ExprInt(0, add_size)))
        return new_expr
    return expr
Ejemplo n.º 8
0
    def write(self, offset, expr):
        """
        Write @expr at @offset
        @offset: integer (in bytes)
        @expr: Expr instance value
        """
        assert expr.size % 8 == 0
        assert offset <= self._mask
        for index in xrange(expr.size / 8):
            # Wrap write:
            # @32[EAX+0xFFFFFFFF] is ok and will write at 0xFFFFFFFF, 0, 1, 2
            request_offset = (offset + index) & self._mask
            # XXX TODO: only little endian here
            self._offset_to_expr[request_offset] = (index, expr)

            tmp = self.expr_simp(expr[index * 8:(index + 1) * 8])
            # Special case: Simplify slice of pointer (simplification is ok
            # here, as we won't store the simplified expression)
            if tmp.is_slice() and tmp.arg.is_mem() and tmp.start % 8 == 0:
                new_ptr = self.expr_simp(tmp.arg.ptr +
                                         ExprInt(tmp.start /
                                                 8, tmp.arg.ptr.size))
                tmp = ExprMem(new_ptr, tmp.stop - tmp.start)
            # Test if write to original value
            if tmp.is_mem():
                src_ptr, src_off = get_expr_base_offset(tmp.ptr)
                if src_ptr == self.base and src_off == request_offset:
                    del self._offset_to_expr[request_offset]
Ejemplo n.º 9
0
 def eval_exprloc(self, expr, **kwargs):
     offset = self.ir_arch.loc_db.get_location_offset(expr.loc_key)
     if offset is not None:
         ret = ExprInt(offset, expr.size)
     else:
         ret = expr
     return ret
Ejemplo n.º 10
0
    def _resolve_mem_parts(self, expr):
        """For a given ExprMem @expr, get known/unknown parts from the store.
        @expr: ExprMem instance

        Return a list of (known, value) where known is a bool representing if
        the value has been resolved from the store or not.
        """

        # Extract known parts in symbols
        assert expr.size % 8 == 0
        ptr = expr.ptr
        known = []
        ptrs = []
        for index in xrange(expr.size / 8):
            offset = self.expr_simp(ptr + ExprInt(index, ptr.size))
            ptrs.append(offset)
            mem = ExprMem(offset, 8)
            known.append(mem in self.symbols)

        reads = merge_ptr_read(known, ptrs)
        out = []
        for is_known, ptr_value, size in reads:
            mem = ExprMem(ptr_value, size)
            if is_known:
                mem = self.symbols.read(mem)
            out.append((is_known, mem))
        return out
Ejemplo n.º 11
0
def simp_cmp_int(expr_simp, expr):
    """
    ({X, 0} == int) => X == int[:]
    X + int1 == int2 => X == int2-int1
    """
    if (expr.is_op(TOK_EQUAL) and expr.args[1].is_int()
            and expr.args[0].is_compose() and len(expr.args[0].args) == 2
            and expr.args[0].args[1].is_int(0)):
        # ({X, 0} == int) => X == int[:]
        src = expr.args[0].args[0]
        int_val = int(expr.args[1])
        new_int = ExprInt(int_val, src.size)
        expr = expr_simp(ExprOp(TOK_EQUAL, src, new_int))
    elif (expr.is_op() and expr.op in [
            TOK_EQUAL,
    ] and expr.args[1].is_int() and expr.args[0].is_op("+")
          and expr.args[0].args[-1].is_int()):
        # X + int1 == int2 => X == int2-int1
        # WARNING:
        # X - 0x10 <=u 0x20 gives X in [0x10 0x30]
        # which is not equivalet to A <=u 0x10

        left, right = expr.args
        left, int_diff = left.args[:-1], left.args[-1]
        if len(left) == 1:
            left = left[0]
        else:
            left = ExprOp('+', *left)
        new_int = expr_simp(right - int_diff)
        expr = expr_simp(ExprOp(expr.op, left, new_int), )
    return expr
Ejemplo n.º 12
0
 def eval_exprloc(self, expr, **kwargs):
     offset = self.ir_arch.symbol_pool.loc_key_to_offset(expr.loc_key)
     if offset is not None:
         ret = ExprInt(offset, expr.size)
     else:
         ret = expr
     return ret
Ejemplo n.º 13
0
    def bytes_without_jmp(self):
        """
        Clear all jump instructions.

        jmp -> nop
        jxx -> nop
        call xxx -> push ret_addr
        """

        buf = ''

        from miasm2.arch.x86.arch import mn_x86
        from miasm2.arch.x86.arch import conditional_branch
        from miasm2.arch.x86.arch import unconditional_branch
        from miasm2.expression.expression import ExprInt

        branch_name = conditional_branch + unconditional_branch
        call_name = ['CALL']

        for ins in self.instructions:
            ins_x86 = mn_x86.dis(ins.bytes, 32)

            if ins_x86.name in branch_name:
                buf += '\x90'  #  NOP
            elif ins_x86.name in call_name:
                ret_addr = ExprInt(ins.addr + ins.size, 32)
                ins_x86.args = [ret_addr]
                ins_x86.name = 'PUSH'
                buf += mn_x86.asm(ins_x86)[0]
            else:
                buf += ins.bytes

        return buf
Ejemplo n.º 14
0
def symexec(handler):
    inst_bytes = handler.bytes_without_jmp
    machine = Machine("x86_32")
    cont = Container.from_string(inst_bytes)
    bs = cont.bin_stream
    mdis = machine.dis_engine(bs, symbol_pool=cont.symbol_pool)

    end_offset = len(inst_bytes)

    mdis.dont_dis = [end_offset]

    asm_block = mdis.dis_block(0)
    # print asm_block
    ira = machine.ira(mdis.symbol_pool)
    ira.add_block(asm_block)

    symb = SymbolicExecutionEngine(ira, symbols_init)

    cur_addr = symb.emul_ir_block(0)
    count = 0
    while cur_addr != ExprInt(end_offset, 32):  # execute to end
        cur_addr = symb.emul_ir_block(cur_addr)

        count += 1
        if count > 1000:
            print '[!] to many loop at %s' % handler.name
            break

    return symb
Ejemplo n.º 15
0
Archivo: dse.py Proyecto: vbrandl/miasm
    def _func_read(self, expr_mem):
        if not expr_mem.ptr.is_int():
            return expr_mem
        dst_addr = int(expr_mem.ptr)

        if not self.dse_memory_range:
            # Trivial case (optimization)
            return super(ESETrackModif, self)._func_read(expr_mem)

        # Split access in atomic accesses
        out = []
        for addr in xrange(dst_addr, dst_addr + (expr_mem.size / 8)):
            if addr in self.dse_memory_range:
                # Symbolize memory access
                out.append(self.dse_memory_to_expr(addr))
            else:
                # Get concrete value
                atomic_access = ExprMem(ExprInt(addr, expr_mem.ptr.size), 8)
                out.append(super(ESETrackModif, self)._func_read(atomic_access))

        if len(out) == 1:
            # Trivial case (optimization)
            return out[0]

        # Simplify for constant merging (ex: {ExprInt(1, 8), ExprInt(2, 8)})
        return self.expr_simp(ExprCompose(*out))
Ejemplo n.º 16
0
def miasm_dis(r2_op, r2_address, r2_buffer, r2_length):
    """Disassemble an instruction using miasm."""

    # Cast radare2 variables
    rasmop = ffi.cast("RAsmOp_r2m2*", r2_op)
    opcode = ffi.cast("char*", r2_buffer)

    # Prepare the opcode
    opcode = ffi.unpack(opcode, r2_length)

    # Get the miasm2 machine
    machine = miasm_machine()
    if machine is None:
        return

    # Disassemble the opcode
    loc_db = LocationDB()
    try:
        mode = machine.dis_engine().attrib
        instr = machine.mn().dis(opcode, mode)
        instr.offset = r2_address
        if instr.dstflow():
            # Remember ExprInt arguments sizes
            args_size = list()
            for i in range(len(instr.args)):
                if isinstance(instr.args[i], ExprInt):
                    args_size.append(instr.args[i].size)
                else:
                    args_size.append(None)

            # Adjust arguments values using the instruction offset
            instr.dstflow2label(loc_db)

            # Convert ExprLoc to ExprInt
            for i in range(len(instr.args)):
                if args_size[i] is None:
                    continue
                if isinstance(instr.args[i], ExprLoc):
                    addr = loc_db.get_location_offset(instr.args[i].loc_key)
                    instr.args[i] = ExprInt(addr, args_size[i])

        dis_str = str(instr)
        dis_len = instr.l
    except Exception:
        dis_str = "/!\ Can't disassemble using miasm /!\\"
        dis_len = 2  # GV: seems fischy !

    # Remaining bytes
    buf_hex = opcode[0:dis_len].encode("hex")

    # Check buffer sizes
    if len(dis_str)-1 > 256:
        dis_str = "/!\ Disassembled instruction is too long /!\\"
    if len(buf_hex)-1 > 256:
        buf_hex = buf_hex[:255]

    # Fill the RAsmOp structure
    rasmop.size = dis_len
    set_rbuf(rasmop.buf_asm, dis_str)
    set_rbuf(rasmop.buf_hex, buf_hex)
Ejemplo n.º 17
0
Archivo: dse.py Proyecto: vbrandl/miasm
    def prepare(self):
        """Prepare the environment for attachment with a jitter"""
        # Disassembler
        self.mdis = self.machine.dis_engine(bin_stream_vm(self.jitter.vm),
                                            lines_wd=1,
                                            loc_db=self.loc_db)

        # Symbexec engine
        ## Prepare symbexec engines
        self.symb = self.SYMB_ENGINE(self.jitter.cpu, self.jitter.vm,
                                     self.ir_arch, {})
        self.symb.enable_emulated_simplifications()
        self.symb_concrete = EmulatedSymbExec(
            self.jitter.cpu, self.jitter.vm,
            self.ir_arch, {}
        )
        ### Avoid side effects on jitter while using 'symb_concrete'
        self.symb_concrete.func_write = None

        ## Update registers value
        self.symb.symbols[self.ir_arch.IRDst] = ExprInt(
            getattr(self.jitter.cpu, self.ir_arch.pc.name),
            self.ir_arch.IRDst.size
        )

        # Avoid memory write
        self.symb.func_write = None

        # Activate callback on each instr
        self.jitter.jit.set_options(max_exec_per_call=1, jit_maxline=1)
        self.jitter.exec_cb = self.callback

        # Clean jit cache to avoid multi-line basic blocks already jitted
        self.jitter.jit.clear_jitted_blocks()
Ejemplo n.º 18
0
def simp_cond_int(expr_simp, expr):
    if (expr.cond.is_op(TOK_EQUAL) and expr.cond.args[1].is_int()
            and expr.cond.args[0].is_compose()
            and len(expr.cond.args[0].args) == 2
            and expr.cond.args[0].args[1].is_int(0)):
        # ({X, 0} == int) => X == int[:]
        src = expr.cond.args[0].args[0]
        int_val = int(expr.cond.args[1])
        new_int = ExprInt(int_val, src.size)
        expr = expr_simp(
            ExprCond(ExprOp(TOK_EQUAL, src, new_int), expr.src1, expr.src2))
    elif (expr.cond.is_op() and expr.cond.op in [
            TOK_EQUAL, TOK_INF_SIGNED, TOK_INF_EQUAL_SIGNED, TOK_INF_UNSIGNED,
            TOK_INF_EQUAL_UNSIGNED
    ] and expr.cond.args[1].is_int() and expr.cond.args[0].is_op("+")
          and expr.cond.args[0].args[-1].is_int()):
        # X + int1 == int2 => X == int2-int1
        left, right = expr.cond.args
        left, int_diff = left.args[:-1], left.args[-1]
        if len(left) == 1:
            left = left[0]
        else:
            left = ExprOp('+', *left)
        new_int = expr_simp(right - int_diff)
        expr = expr_simp(
            ExprCond(ExprOp(expr.cond.op, left, new_int), expr.src1,
                     expr.src2))
    return expr
Ejemplo n.º 19
0
    def reduce_op_memberof(self, node, _):
        """Reduce -> operator"""

        if not node.expr.is_op('->'):
            return None
        assert len(node.args) == 2
        out = []
        assert isinstance(node.args[1].expr, ExprId)
        field = node.args[1].expr.name
        src, src_type = node.args[0].info
        assert isinstance(src_type, (ObjCPtr, ObjCArray))
        struct_dst = src_type.objtype
        assert isinstance(struct_dst, ObjCStruct)

        found = False
        for name, objtype, offset, _ in struct_dst.fields:
            if name != field:
                continue
            expr = src + ExprInt(offset, src.size)
            if isinstance(objtype, (ObjCArray, ObjCStruct, ObjCUnion)):
                pass
            else:
                expr = ExprMem(expr, objtype.size * 8)
            assert not found
            found = True
            out = (expr, objtype)
        assert found
        return out
Ejemplo n.º 20
0
 def decode(self, v):
     v = v & self.lmask
     v <<= 2
     v = cpu.sign_ext(v, 16+2, 32)
     # Add pipeline offset
     self.expr = ExprInt(v + 4, 32)
     return True
Ejemplo n.º 21
0
    def post_add_block(self, block, ir_blocks):
        IntermediateRepresentation.post_add_block(self, block, ir_blocks)
        new_irblocks = []
        for irb in ir_blocks:
            pc_val = None
            lr_val = None
            for assignblk in irb.irs:
                pc_val = assignblk.get(self.arch.regs.PC, pc_val)
                lr_val = assignblk.get(self.arch.regs.RA, lr_val)

            if pc_val is None or lr_val is None:
                new_irblocks.append(irb)
                continue
            if not expr_is_int_or_label(lr_val):
                new_irblocks.append(irb)
                continue
            if expr_is_label(lr_val):
                lr_val = ExprInt(lr_val.name.offset, 32)

            instr = block.lines[-2]
            if lr_val.arg != instr.offset + 8:
                raise ValueError("Wrong arg")

            # CALL
            lbl = block.get_next()
            new_lbl = self.gen_label()
            irs = self.call_effects(pc_val, instr)
            irs.append(
                AssignBlock(
                    [ExprAff(self.IRDst, ExprId(lbl, size=self.pc.size))],
                    instr))
            new_irblocks.append(IRBlock(new_lbl, irs))
            new_irblocks.append(irb.set_dst(ExprId(new_lbl,
                                                   size=self.pc.size)))
        return new_irblocks
Ejemplo n.º 22
0
Archivo: sem.py Proyecto: manwefm/miasm
def csinc(ir, instr, arg1, arg2, arg3, arg4):
    e = []
    cond_expr = cond2expr[arg4.name]
    e.append(
        ExprAssign(arg1, ExprCond(cond_expr, arg2,
                                  arg3 + ExprInt(1, arg3.size))))
    return e, []
Ejemplo n.º 23
0
    def post_add_asmblock_to_ircfg(self, block, ircfg, ir_blocks):
        IntermediateRepresentation.post_add_asmblock_to_ircfg(self, block, ircfg, ir_blocks)
        new_irblocks = []
        for irb in ir_blocks:
            pc_val = None
            lr_val = None
            for assignblk in irb:
                pc_val = assignblk.get(self.arch.regs.PC, pc_val)
                lr_val = assignblk.get(self.arch.regs.RA, lr_val)

            if pc_val is None or lr_val is None:
                new_irblocks.append(irb)
                continue
            if lr_val.is_loc():
                offset = self.loc_db.get_location_offset(lr_val.loc_key)
                if offset is not None:
                    lr_val = ExprInt(offset, 32)
            if not lr_val.is_int():
                continue

            instr = block.lines[-2]
            if int(lr_val) != instr.offset + 8:
                raise ValueError("Wrong arg")

            # CALL
            lbl = block.get_next()
            new_lbl = self.gen_label()
            call_assignblks, extra_irblocks = self.call_effects(pc_val, instr)
            ir_blocks += extra_irblocks
            irs.append(AssignBlock([ExprAff(self.IRDst,
                                            ExprId(lbl, size=self.pc.size))],
                                   instr))
            new_irblocks.append(IRBlock(new_lbl, call_assignblks))
            new_irblocks.append(irb.set_dst(ExprId(new_lbl, size=self.pc.size)))
        return new_irblocks
Ejemplo n.º 24
0
Archivo: sem.py Proyecto: manwefm/miasm
def fmov(ir, instr, arg1, arg2):
    if arg2.is_int():
        # Transform int to signed floating-point constant with 3-bit exponent
        # and normalized 4 bits of precision
        # VFPExpandImm() of ARM Architecture Reference Manual
        imm8 = int(arg2)
        N = arg1.size
        assert N in [32, 64]
        E = 8 if N == 32 else 11
        F = N - E - 1
        # sign = imm8<7>;
        sign = (imm8 >> 7) & 1
        # exp = NOT(imm8<6>):Replicate(imm8<6>,E-3):imm8<5:4>;
        exp = (((imm8 >> 6) & 1) ^ 1) << (E - 3 + 2)
        if (imm8 >> 6) & 1:
            tmp = (1 << (E - 3)) - 1
        else:
            tmp = 0
        exp |= tmp << 2
        exp |= (imm8 >> 4) & 3
        # frac = imm8<3:0>:Zeros(F-4);
        frac = (imm8 & 0xf) << (F - 4)
        value = frac
        value |= exp << (4 + F - 4)
        value |= sign << (4 + F - 4 + 1 + E - 3 + 2)
        arg2 = ExprInt(value, N)
    e = [ExprAssign(arg1, arg2)]
    return e, []
Ejemplo n.º 25
0
Archivo: sem.py Proyecto: manwefm/miasm
def fcmpe(ir, instr, arg1, arg2):
    e = []
    e.append(ExprAssign(nf, ExprOp('fcom_c0', arg1, arg2)))
    e.append(ExprAssign(cf, ~ExprOp('fcom_c0', arg1, arg2)))
    e.append(ExprAssign(zf, ExprOp('fcom_c3', arg1, arg2)))
    e.append(ExprAssign(of, ExprInt(0, 1)))
    return e, []
Ejemplo n.º 26
0
 def check(self):
     value = self.dse.eval_expr(self._regs.EBX)
     # EBX = TEST
     # ADD EBX, 6
     # INC EBX
     # -> EBX_final = TEST + 7
     assert value == self._testid + ExprInt(7, self._regs.EBX.size)
Ejemplo n.º 27
0
    def test_ExprSlice_strcst(self):
        from miasm2.expression.expression import ExprInt, ExprSlice
        import miasm2.expression.stp  # /!\ REALLY DIRTY HACK
        args = [ExprInt(i, 32) for i in xrange(9)]

        self.assertEqual(args[0][1:2].strcst(),
                         r'(0bin00000000000000000000000000000000)[1:1]')
        self.assertRaises(ValueError, args[0].__getitem__, slice(1, 7, 2))
Ejemplo n.º 28
0
def sbvck3(ir, instr, r0, rn, rm):
    """SBVCK3 - Check substraction overflow"""

    # if(Overflow(Rn-Rm)) R0<-1 else R0<-0 (Signed)

    # Substract registers
    reg_sub = ExprOp("+", rn, rm)

    # Get the register storing the highest value
    max_rn_rm = ExprCond(ExprOp(">", rn, rm), rn, rm)

    # Check for an overflow
    overflow_test = ExprOp(">", reg_sub, max_rn_rm)

    # Return the result
    condition = ExprCond(overflow_test, ExprInt(1, 32), ExprInt(0, 32))
    return [ExprAff(r0, condition)], []
Ejemplo n.º 29
0
def jsr(reg):
    """JSR - Jump to the register, and store the return address."""

    # LP <- PC + 2; PC <- Rm31..1||0
    LP = ExprLoc(ir.get_next_break_loc_key(instr), 32)
    take_jmp = ExprInt(1, 32)
    PC = reg
    ir.IRDst = reg
Ejemplo n.º 30
0
def bra(disp12):
    """BRA - Branch to an address."""

    # PC <- PC + SignExt((disp12)11..1||0)
    dst = disp12
    PC = dst
    take_jmp = ExprInt(1, 32)
    ir.IRDst = dst