Instruction:
Write a Python 3 function for
decoding and execute one instruction pointed by register PC

Response:
def execute(self):
        """
        Decode, and execute one instruction pointed by register PC
        """
        if issymbolic(self.PC):
            raise ConcretizeRegister(self, 'PC', policy='ALL')

        if not self.memory.access_ok(self.PC, 'x'):
            raise InvalidMemoryAccess(self.PC, 'x')

        self._publish('will_decode_instruction', self.PC)

        insn = self.decode_instruction(self.PC)
        self._last_pc = self.PC

        self._publish('will_execute_instruction', self.PC, insn)

        # FIXME (theo) why just return here?
        if insn.address != self.PC:
            return

        name = self.canonicalize_instruction_name(insn)

        if logger.level == logging.DEBUG:
            logger.debug(self.render_instruction(insn))
            for l in self.render_registers():
                register_logger.debug(l)

        try:
            if self._concrete and 'SYSCALL' in name:
                self.emu.sync_unicorn_to_manticore()
            if self._concrete and 'SYSCALL' not in name:
                self.emulate(insn)
                if self.PC == self._break_unicorn_at:
                    logger.debug("Switching from Unicorn to Manticore")
                    self._break_unicorn_at = None
                    self._concrete = False
            else:
                implementation = getattr(self, name, None)

                if implementation is not None:
                    implementation(*insn.operands)

                else:
                    text_bytes = ' '.join('%02x' % x for x in insn.bytes)
                    logger.warning("Unimplemented instruction: 0x%016x:\t%s\t%s\t%s",
                                   insn.address, text_bytes, insn.mnemonic, insn.op_str)
                    self.backup_emulate(insn)
        except (Interruption, Syscall) as e:
            e.on_handled = lambda: self._publish_instruction_as_executed(insn)
            raise e
        else:
            self._publish_instruction_as_executed(insn)


Instruction:
Here you have a function in Python 3, explain what it does
def _publish_instruction_as_executed(self, insn):
        self._icount += 1
        self._publish('did_execute_instruction', self._last_pc, self.PC, insn)

Response: Notify listeners that an instruction has been executed.


Instruction:
Here you have a function in Python 3, explain what it does
def emulate(self, insn):

        if self._concrete:
            self.concrete_emulate(insn)
        else:
            self.backup_emulate(insn)

Response: Emulate the right instruction.


Instruction:
Here you have a function in Python 3, explain what it does
def concrete_emulate(self, insn):

        if not self.emu:
            self.emu = ConcreteUnicornEmulator(self)
            self.emu._stop_at = self._break_unicorn_at
        try:
            self.emu.emulate(insn)
        except unicorn.UcError as e:
            if e.errno == unicorn.UC_ERR_INSN_INVALID:
                text_bytes = ' '.join('%02x' % x for x in insn.bytes)
                logger.error("Unimplemented instruction: 0x%016x:\t%s\t%s\t%s",
                             insn.address, text_bytes, insn.mnemonic, insn.op_str)
            raise InstructionEmulationError(str(e))

Response: Emulate the given instruction object.


Instruction:
Given the following Python 3 function, write the documentation
def backup_emulate(self, insn):

        if not hasattr(self, 'backup_emu'):
            self.backup_emu = UnicornEmulator(self)
        try:
            self.backup_emu.emulate(insn)
        except unicorn.UcError as e:
            if e.errno == unicorn.UC_ERR_INSN_INVALID:
                text_bytes = ' '.join('%02x' % x for x in insn.bytes)
                logger.error("Unimplemented instruction: 0x%016x:\t%s\t%s\t%s",
                             insn.address, text_bytes, insn.mnemonic, insn.op_str)
            raise InstructionEmulationError(str(e))
        finally:
            # We have been seeing occasional Unicorn issues with it not clearing
            # the backing unicorn instance. Saw fewer issues with the following
            # line present.
            del self.backup_emu

Response: Emulate an instruction and return the backup unicorn instance.


Instruction:
Write a Python 3 script to
highlight the basic blocks of a Manticore trace file.

Response:
def viz_trace(view):
    """
    Given a Manticore trace file, highlight the basic blocks.
    """
    tv = TraceVisualizer(view, None)
    if tv.workspace is None:
        tv.workspace = get_workspace()
    tv.visualize()


Instruction:
Given the following Python 3 function, write the documentation
def viz_live_trace(view):
    tv = TraceVisualizer(view, None, live=True)
    if tv.workspace is None:
        tv.workspace = get_workspace()
    # update due to singleton in case we are called after a clear
    tv.live_update = True
    tv.visualize()

Response: Given a Manticore trace file highlight the basic blocks.


Instruction:
Implement a Python 3 function for
highlighting basic blocks from the Manticore workspace or trace file.

Response:
def visualize(self):
        """
        Given a Manticore workspace, or trace file, highlight the basic blocks.
        """
        if os.path.isfile(self.workspace):
            t = threading.Thread(target=self.highlight_from_file,
                                 args=(self.workspace,))
        elif os.path.isdir(self.workspace):
            t = threading.Thread(target=self.highlight_from_dir,
                                 args=(self.workspace,))
        t.start()


Instruction:
Can you write a function in Python 3 where it
parses a single token and return the next token.

Response:
def t_TOKEN(t):
    '[a-zA-Z0-9]+'
    #print t.value,t.lexer.lexdata[t.lexer.lexpos-len(t.value):],re_TYPE.match(t.lexer.lexdata,t.lexer.lexpos-len(t.value))
    if re_TYPE.match(t.value):
        t.type = 'TYPE'
    elif re_PTR.match(t.value):
        t.type = 'PTR'
    elif re_NUMBER.match(t.value):
        if t.value.startswith('0x'):
            t.value = t.value[2:]
        t.value = int(t.value, 16)
        t.type = 'NUMBER'
    elif re_REGISTER.match(t.value):
        t.type = 'REGISTER'
    elif re_SEGMENT.match(t.value):
        t.type = 'SEGMENT'
    else:
        raise Exception(f"Unknown:<{t.value}>")
    return t


Instruction:
Explain what the following Python 3 code does
def p_expression_deref(p):
    'expression : TYPE PTR LBRAKET expression RBRAKET'
    size = sizes[p[1]]
    address = p[4]
    char_list = functions['read_memory'](address, size)
    value = Operators.CONCAT(8 * len(char_list), *reversed(map(Operators.ORD, char_list)))
    p[0] = value

Response: EXPRESSION TYPE PTR LBRAKET expression RBRAKET


Instruction:
Can you generate the documentation for the following Python 3 function
def p_expression_derefseg(p):
    'expression : TYPE PTR SEGMENT COLOM LBRAKET expression RBRAKET'
    size = sizes[p[1]]
    address = p[6]
    seg = functions['read_register'](p[3])
    base, limit, _ = functions['get_descriptor'](seg)
    address = base + address
    char_list = functions['read_memory'](address, size)
    value = Operators.CONCAT(8 * len(char_list), *reversed(map(Operators.ORD, char_list)))
    p[0] = value

Response: expression : TYPE PTR SEGMENT COLOM LBRAKET expression RBRAKET


Instruction:
Can you create a Python 3 function that
builds EFLAGS and RFLAGS from flags

Response:
def _get_flags(self, reg):
        """ Build EFLAGS/RFLAGS from flags """
        def make_symbolic(flag_expr):
            register_size = 32 if reg == 'EFLAGS' else 64
            value, offset = flag_expr
            return Operators.ITEBV(register_size, value,
                                   BitVecConstant(register_size, 1 << offset),
                                   BitVecConstant(register_size, 0))

        flags = []
        for flag, offset in self._flags.items():
            flags.append((self._registers[flag], offset))

        if any(issymbolic(flag) for flag, offset in flags):
            res = reduce(operator.or_, map(make_symbolic, flags))
        else:
            res = 0
            for flag, offset in flags:
                res += flag << offset
        return res


Instruction:
Write a Python 3 function that can
set individual flags from an EFLAGS or RFLAGS value.

Response:
def _set_flags(self, reg, res):
        """ Set individual flags from a EFLAGS/RFLAGS value """
        #assert sizeof (res) == 32 if reg == 'EFLAGS' else 64
        for flag, offset in self._flags.items():
            self.write(flag, Operators.EXTRACT(res, offset, 1))


Instruction:
Given the following Python 3 function, write the documentation
def push(cpu, value, size):
        assert size in (8, 16, cpu.address_bit_size)
        cpu.STACK = cpu.STACK - size // 8
        base, _, _ = cpu.get_descriptor(cpu.read_register('SS'))
        address = cpu.STACK + base
        cpu.write_int(address, value, size)

Response: Writes a value into the stack.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def pop(cpu, size):
        assert size in (16, cpu.address_bit_size)
        base, _, _ = cpu.get_descriptor(cpu.SS)
        address = cpu.STACK + base
        value = cpu.read_int(address, size)
        cpu.STACK = cpu.STACK + size // 8
        return value

Response: Get a value from the stack.


Instruction:
How would you explain what the following Python 3 function does
def invalidate_cache(cpu, address, size):
        cache = cpu.instruction_cache
        for offset in range(size):
            if address + offset in cache:
                del cache[address + offset]

Response: invalidates the instruction cache at the given address.


Instruction:
Explain what the following Python 3 code does
def AND(cpu, dest, src):
        # XXX bypass a capstone bug that incorrectly extends and computes operands sizes
        # the bug has been fixed since capstone 4.0.alpha2 (commit de8dd26)
        if src.size == 64 and src.type == 'immediate' and dest.size == 64:
            arg1 = Operators.SEXTEND(src.read(), 32, 64)
        else:
            arg1 = src.read()
        res = dest.write(dest.read() & arg1)
        # Defined Flags: szp
        cpu._calculate_logic_flags(dest.size, res)

Response: Logical AND operation on the destination and source sets the result in the destination operand location.


Instruction:
Make a summary of the following Python 3 code
def XOR(cpu, dest, src):
        if dest == src:
            # if the operands are the same write zero
            res = dest.write(0)
        else:
            res = dest.write(dest.read() ^ src.read())
        # Defined Flags: szp
        cpu._calculate_logic_flags(dest.size, res)

Response: Logical OR operation on the destination and source sets the result in the destination and source locations.


Instruction:
How would you explain what the following Python 3 function does
def OR(cpu, dest, src):
        res = dest.write(dest.read() | src.read())
        # Defined Flags: szp
        cpu._calculate_logic_flags(dest.size, res)

Response:
Logical inclusive OR.

        Performs a bitwise inclusive OR operation between the destination (first)
        and source (second) operands and stores the result in the destination operand location.

        Each bit of the result of the OR instruction is set to 0 if both corresponding
        bits of the first and second operands are 0; otherwise, each bit is set
        to 1.

        The OF and CF flags are cleared; the SF, ZF, and PF flags are set according to the result::

            DEST  =  DEST OR SRC;

        :param cpu: current CPU.
        :param dest: destination operand.
        :param src: source operand.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def AAA(cpu):
        cpu.AF = Operators.OR(cpu.AL & 0x0F > 9, cpu.AF)
        cpu.CF = cpu.AF
        cpu.AH = Operators.ITEBV(8, cpu.AF, cpu.AH + 1, cpu.AH)
        cpu.AL = Operators.ITEBV(8, cpu.AF, cpu.AL + 6, cpu.AL)
        """
        if (cpu.AL & 0x0F > 9) or cpu.AF == 1:
            cpu.AL = cpu.AL + 6
            cpu.AH = cpu.AH + 1
            cpu.AF = True
            cpu.CF = True
        else:
            cpu.AF = False
            cpu.CF = False
        """
        cpu.AL = cpu.AL & 0x0f

Response: AAA instruction for handling the AAA instruction.


Instruction:
Here you have a function in Python 3, explain what it does
def AAD(cpu, imm=None):
        if imm is None:
            imm = 10
        else:
            imm = imm.read()

        cpu.AL += cpu.AH * imm
        cpu.AH = 0

        # Defined flags: ...sz.p.
        cpu._calculate_logic_flags(8, cpu.AL)

Response: AAD instruction for determining the base 10 value of the current AH register.


Instruction:
Explain what the following Python 3 code does
def AAM(cpu, imm=None):
        if imm is None:
            imm = 10
        else:
            imm = imm.read()

        cpu.AH = Operators.UDIV(cpu.AL, imm)
        cpu.AL = Operators.UREM(cpu.AL, imm)

        # Defined flags: ...sz.p.
        cpu._calculate_logic_flags(8, cpu.AL)

Response: AAM instruction for storing the result of an AAM instruction.


Instruction:
Implement a Python 3 function for
adding with carry. Adds the destination operand (first operand), the source operand (second operand), and the carry (CF) flag and stores the result in the destination operand. The state of the CF flag represents a carry from a previous addition. When an immediate value is used as an operand, it is sign-extended to the length of the destination operand format. The ADC instruction does not distinguish between signed or unsigned operands. Instead, the processor evaluates the result for both data types and sets the OF and CF flags to indicate a carry in the signed or unsigned result, respectively. The SF flag indicates the sign of the signed result. The ADC instruction is usually executed as part of a multibyte or multiword addition in which an ADD instruction is followed by an ADC instruction:: DEST = DEST + SRC + CF; The OF, SF, ZF, AF, CF, and PF flags are set according to the result. :param cpu: current CPU. :param dest: destination operand. :param src: source operand.

Response:
def ADC(cpu, dest, src):
        """
        Adds with carry.

        Adds the destination operand (first operand), the source operand (second operand),
        and the carry (CF) flag and stores the result in the destination operand. The state
        of the CF flag represents a carry from a previous addition. When an immediate value
        is used as an operand, it is sign-extended to the length of the destination operand
        format. The ADC instruction does not distinguish between signed or unsigned operands.
        Instead, the processor evaluates the result for both data types and sets the OF and CF
        flags to indicate a carry in the signed or unsigned result, respectively. The SF flag
        indicates the sign of the signed result. The ADC instruction is usually executed as
        part of a multibyte or multiword addition in which an ADD instruction is followed by an
        ADC instruction::

                DEST  =  DEST + SRC + CF;

        The OF, SF, ZF, AF, CF, and PF flags are set according to the result.

        :param cpu: current CPU.
        :param dest: destination operand.
        :param src: source operand.
        """
        cpu._ADD(dest, src, carry=True)


Instruction:
How would you explain what the following Python 3 function does
def ADD(cpu, dest, src):
        cpu._ADD(dest, src, carry=False)

Response: A base implementation of the ADD instruction.


Instruction:
Here you have a function in Python 3, explain what it does
def CMP(cpu, src1, src2):
        arg0 = src1.read()
        arg1 = Operators.SEXTEND(src2.read(), src2.size, src1.size)

        # Affected Flags o..szapc
        cpu._calculate_CMP_flags(src1.size, arg0 - arg1, arg0, arg1)

Response: Compares two source and destination sets the status flags of the current entry in the EFLAGS register according to the result of the comparison.


Instruction:
Here you have a function in Python 3, explain what it does
def CMPXCHG(cpu, dest, src):
        size = dest.size
        reg_name = {8: 'AL', 16: 'AX', 32: 'EAX', 64: 'RAX'}[size]
        accumulator = cpu.read_register(reg_name)
        sval = src.read()
        dval = dest.read()

        cpu.write_register(reg_name, dval)
        dest.write(Operators.ITEBV(size, accumulator == dval, sval, dval))

        # Affected Flags o..szapc
        cpu._calculate_CMP_flags(size, accumulator - dval, accumulator, dval)

Response: This function is used to compare two sets of entries in the current memory with the source memory.


Instruction:
Implement a function in Python 3 to
compare and exchanges bytes. Compares the 64-bit value in EDX:EAX (or 128-bit value in RDX:RAX if operand size is 128 bits) with the operand (destination operand). If the values are equal, the 64-bit value in ECX:EBX (or 128-bit value in RCX:RBX) is stored in the destination operand. Otherwise, the value in the destination operand is loaded into EDX:EAX (or RDX:RAX):: IF (64-Bit Mode and OperandSize = 64) THEN IF (RDX:RAX = DEST) THEN ZF = 1; DEST = RCX:RBX; ELSE ZF = 0; RDX:RAX = DEST; FI ELSE IF (EDX:EAX = DEST) THEN ZF = 1; DEST = ECX:EBX; ELSE ZF = 0; EDX:EAX = DEST; FI; FI; :param cpu: current CPU. :param dest: destination operand.

Response:
def CMPXCHG8B(cpu, dest):
        """
        Compares and exchanges bytes.

        Compares the 64-bit value in EDX:EAX (or 128-bit value in RDX:RAX if
        operand size is 128 bits) with the operand (destination operand). If
        the values are equal, the 64-bit value in ECX:EBX (or 128-bit value in
        RCX:RBX) is stored in the destination operand.  Otherwise, the value in
        the destination operand is loaded into EDX:EAX (or RDX:RAX)::

                IF (64-Bit Mode and OperandSize = 64)
                THEN
                    IF (RDX:RAX = DEST)
                    THEN
                        ZF = 1;
                        DEST = RCX:RBX;
                    ELSE
                        ZF = 0;
                        RDX:RAX = DEST;
                    FI
                ELSE
                    IF (EDX:EAX = DEST)
                    THEN
                        ZF = 1;
                        DEST = ECX:EBX;
                    ELSE
                        ZF = 0;
                        EDX:EAX = DEST;
                    FI;
                FI;

        :param cpu: current CPU.
        :param dest: destination operand.
        """
        size = dest.size
        cmp_reg_name_l = {64: 'EAX', 128: 'RAX'}[size]
        cmp_reg_name_h = {64: 'EDX', 128: 'RDX'}[size]
        src_reg_name_l = {64: 'EBX', 128: 'RBX'}[size]
        src_reg_name_h = {64: 'ECX', 128: 'RCX'}[size]

        # EDX:EAX or RDX:RAX
        cmph = cpu.read_register(cmp_reg_name_h)
        cmpl = cpu.read_register(cmp_reg_name_l)

        srch = cpu.read_register(src_reg_name_h)
        srcl = cpu.read_register(src_reg_name_l)

        cmp0 = Operators.CONCAT(size, cmph, cmpl)
        src0 = Operators.CONCAT(size, srch, srcl)
        arg_dest = dest.read()
        cpu.ZF = arg_dest == cmp0

        dest.write(
            Operators.ITEBV(size, cpu.ZF,
                            Operators.CONCAT(size, srch, srcl),
                            arg_dest)
        )
        cpu.write_register(cmp_reg_name_l, Operators.ITEBV(size // 2, cpu.ZF, cmpl,
                                                           Operators.EXTRACT(arg_dest, 0, size // 2)))
        cpu.write_register(cmp_reg_name_h, Operators.ITEBV(size // 2, cpu.ZF, cmph,
                                                           Operators.EXTRACT(arg_dest, size // 2, size // 2)))


Instruction:
Can you generate a brief explanation for the following Python 3 code
def DAS(cpu):
        oldAL = cpu.AL
        oldCF = cpu.CF

        cpu.AF = Operators.OR((cpu.AL & 0x0f) > 9, cpu.AF)
        cpu.AL = Operators.ITEBV(8, cpu.AF, cpu.AL - 6, cpu.AL)
        cpu.CF = Operators.ITE(cpu.AF, Operators.OR(oldCF, cpu.AL > oldAL), cpu.CF)

        cpu.CF = Operators.ITE(Operators.OR(oldAL > 0x99, oldCF), True, cpu.CF)
        cpu.AL = Operators.ITEBV(8, Operators.OR(oldAL > 0x99, oldCF), cpu.AL - 0x60, cpu.AL)
        #
        """
        if (cpu.AL & 0x0f) > 9 or cpu.AF:
            cpu.AL = cpu.AL - 6;
            cpu.CF = Operators.OR(oldCF, cpu.AL > oldAL)
            cpu.AF = True
        else:
            cpu.AF  =  False

        if ((oldAL > 0x99) or oldCF):
            cpu.AL = cpu.AL - 0x60
            cpu.CF = True
        """
        cpu.ZF = cpu.AL == 0
        cpu.SF = (cpu.AL & 0x80) != 0
        cpu.PF = cpu._calculate_parity_flag(cpu.AL)

Response: This function is used to create a packed BCD result for a specific CPU.


Instruction:
Explain what the following Python 3 code does
def DIV(cpu, src):
        size = src.size
        reg_name_h = {8: 'DL', 16: 'DX', 32: 'EDX', 64: 'RDX'}[size]
        reg_name_l = {8: 'AL', 16: 'AX', 32: 'EAX', 64: 'RAX'}[size]

        dividend = Operators.CONCAT(size * 2,
                                    cpu.read_register(reg_name_h),
                                    cpu.read_register(reg_name_l))
        divisor = Operators.ZEXTEND(src.read(), size * 2)

        # TODO make symbol friendly
        if isinstance(divisor, int) and divisor == 0:
            raise DivideByZeroError()
        quotient = Operators.UDIV(dividend, divisor)

        MASK = (1 << size) - 1

        # TODO make symbol friendly
        if isinstance(quotient, int) and quotient > MASK:
            raise DivideByZeroError()
        remainder = Operators.UREM(dividend, divisor)

        cpu.write_register(reg_name_l, Operators.EXTRACT(quotient, 0, size))
        cpu.write_register(reg_name_h, Operators.EXTRACT(remainder, 0, size))

Response: This function divide the value in the instruction and stores the result in the instruction instruction. instruction instruction. instruction is used to determine the value of the instruction instruction. instruction.


Instruction:
Given the following Python 3 function, write the documentation
def IDIV(cpu, src):

        reg_name_h = {8: 'AH', 16: 'DX', 32: 'EDX', 64: 'RDX'}[src.size]
        reg_name_l = {8: 'AL', 16: 'AX', 32: 'EAX', 64: 'RAX'}[src.size]

        dividend = Operators.CONCAT(src.size * 2,
                                    cpu.read_register(reg_name_h),
                                    cpu.read_register(reg_name_l))

        divisor = src.read()
        if isinstance(divisor, int) and divisor == 0:
            raise DivideByZeroError()

        dst_size = src.size * 2

        divisor = Operators.SEXTEND(divisor, src.size, dst_size)
        mask = (1 << dst_size) - 1
        sign_mask = 1 << (dst_size - 1)

        dividend_sign = (dividend & sign_mask) != 0
        divisor_sign = (divisor & sign_mask) != 0

        if isinstance(divisor, int):
            if divisor_sign:
                divisor = ((~divisor) + 1) & mask
                divisor = -divisor

        if isinstance(dividend, int):
            if dividend_sign:
                dividend = ((~dividend) + 1) & mask
                dividend = -dividend

        quotient = Operators.SDIV(dividend, divisor)
        if (isinstance(dividend, int) and
                isinstance(dividend, int)):
            # handle the concrete case
            remainder = dividend - (quotient * divisor)
        else:
            # symbolic case -- optimize via SREM
            remainder = Operators.SREM(dividend, divisor)

        cpu.write_register(reg_name_l, Operators.EXTRACT(quotient, 0, src.size))
        cpu.write_register(reg_name_h, Operators.EXTRACT(remainder, 0, src.size))

Response: This function is used to divide the value of the source and store it in the AL AX or EAX registers. The value of the source is divided by the value of the source and stores the result in the EAX DX and EDX registers.


Instruction:
Can you generate the documentation for the following Python 3 function
def IMUL(cpu, *operands):
        dest = operands[0]
        OperandSize = dest.size
        reg_name_h = {8: 'AH', 16: 'DX', 32: 'EDX', 64: 'RDX'}[OperandSize]
        reg_name_l = {8: 'AL', 16: 'AX', 32: 'EAX', 64: 'RAX'}[OperandSize]

        arg0 = dest.read()
        arg1 = None
        arg2 = None
        res = None
        if len(operands) == 1:
            arg1 = cpu.read_register(reg_name_l)
            temp = (Operators.SEXTEND(arg0, OperandSize, OperandSize * 2) *
                    Operators.SEXTEND(arg1, OperandSize, OperandSize * 2))
            temp = temp & ((1 << (OperandSize * 2)) - 1)
            cpu.write_register(reg_name_l,
                               Operators.EXTRACT(temp, 0, OperandSize))
            cpu.write_register(reg_name_h,
                               Operators.EXTRACT(temp, OperandSize, OperandSize))
            res = Operators.EXTRACT(temp, 0, OperandSize)
        elif len(operands) == 2:
            arg1 = operands[1].read()
            arg1 = Operators.SEXTEND(arg1, OperandSize, OperandSize * 2)
            temp = Operators.SEXTEND(arg0, OperandSize, OperandSize * 2) * arg1
            temp = temp & ((1 << (OperandSize * 2)) - 1)
            res = dest.write(Operators.EXTRACT(temp, 0, OperandSize))
        else:
            arg1 = operands[1].read()
            arg2 = operands[2].read()
            temp = (Operators.SEXTEND(arg1, OperandSize, OperandSize * 2) *
                    Operators.SEXTEND(arg2, operands[2].size, OperandSize * 2))
            temp = temp & ((1 << (OperandSize * 2)) - 1)
            res = dest.write(Operators.EXTRACT(temp, 0, OperandSize))

        cpu.CF = (Operators.SEXTEND(res, OperandSize, OperandSize * 2) != temp)
        cpu.OF = cpu.CF

Response: This function performs a signed multiplication of two values in the specified CPU.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def INC(cpu, dest):
        arg0 = dest.read()
        res = dest.write(arg0 + 1)
        res &= (1 << dest.size) - 1
        SIGN_MASK = 1 << (dest.size - 1)
        cpu.AF = ((arg0 ^ 1) ^ res) & 0x10 != 0
        cpu.ZF = res == 0
        cpu.SF = (res & SIGN_MASK) != 0
        cpu.OF = res == SIGN_MASK
        cpu.PF = cpu._calculate_parity_flag(res)

Response: Increments by 1. The destination operand is a register or memory location.


Instruction:
Here you have a function in Python 3, explain what it does
def SBB(cpu, dest, src):
        cpu._SUB(dest, src, carry=True)

Response: Integer subtraction with borrow.


Instruction:
Can you tell what is the following Python 3 function doing
def SUB(cpu, dest, src):
        cpu._SUB(dest, src, carry=False)

Response:
Subtract.

        Subtracts the second operand (source operand) from the first operand
        (destination operand) and stores the result in the destination operand.
        The destination operand can be a register or a memory location; the
        source operand can be an immediate, register, or memory location.
        (However, two memory operands cannot be used in one instruction.) When
        an immediate value is used as an operand, it is sign-extended to the
        length of the destination operand format.
        The SUB instruction does not distinguish between signed or unsigned
        operands. Instead, the processor evaluates the result for both
        data types and sets the OF and CF flags to indicate a borrow in the
        signed or unsigned result, respectively. The SF flag indicates the sign
        of the signed result::

            DEST  =  DEST - SRC;

        :param cpu: current CPU.
        :param dest: destination operand.
        :param src: source operand.


Instruction:
Can you create a Python 3 function that
exchanges and adds. Exchanges the first operand (destination operand) with the second operand (source operand), then loads the sum of the two values into the destination operand. The destination operand can be a register or a memory location; the source operand is a register. This instruction can be used with a LOCK prefix:: TEMP = SRC + DEST SRC = DEST DEST = TEMP :param cpu: current CPU. :param dest: destination operand. :param src: source operand.

Response:
def XADD(cpu, dest, src):
        """
        Exchanges and adds.

        Exchanges the first operand (destination operand) with the second operand
        (source operand), then loads the sum of the two values into the destination
        operand. The destination operand can be a register or a memory location;
        the source operand is a register.
        This instruction can be used with a LOCK prefix::

                TEMP  =  SRC + DEST
                SRC  =  DEST
                DEST  =  TEMP

        :param cpu: current CPU.
        :param dest: destination operand.
        :param src: source operand.
        """
        MASK = (1 << dest.size) - 1
        SIGN_MASK = 1 << (dest.size - 1)

        arg0 = dest.read()
        arg1 = src.read()
        temp = (arg1 + arg0) & MASK
        src.write(arg0)
        dest.write(temp)

        # Affected flags: oszapc
        tempCF = Operators.OR(Operators.ULT(temp, arg0), Operators.ULT(temp, arg1))
        cpu.CF = tempCF
        cpu.AF = ((arg0 ^ arg1) ^ temp) & 0x10 != 0
        cpu.ZF = temp == 0
        cpu.SF = (temp & SIGN_MASK) != 0
        cpu.OF = (((arg0 ^ arg1 ^ SIGN_MASK) & (temp ^ arg1)) & SIGN_MASK) != 0
        cpu.PF = cpu._calculate_parity_flag(temp)


Instruction:
Given the following Python 3 function, write the documentation
def BSWAP(cpu, dest):
        parts = []
        arg0 = dest.read()
        for i in range(0, dest.size, 8):
            parts.append(Operators.EXTRACT(arg0, i, 8))

        dest.write(Operators.CONCAT(8 * len(parts), *parts))

Response:
Byte swap.

        Reverses the byte order of a 32-bit (destination) register: bits 0 through
        7 are swapped with bits 24 through 31, and bits 8 through 15 are swapped
        with bits 16 through 23. This instruction is provided for converting little-endian
        values to big-endian format and vice versa.
        To swap bytes in a word value (16-bit register), use the XCHG instruction.
        When the BSWAP instruction references a 16-bit register, the result is
        undefined::

            TEMP  =  DEST
            DEST[7..0]  =  TEMP[31..24]
            DEST[15..8]  =  TEMP[23..16]
            DEST[23..16]  =  TEMP[15..8]
            DEST[31..24]  =  TEMP[7..0]

        :param cpu: current CPU.
        :param dest: destination operand.


Instruction:
Here you have a function in Python 3, explain what it does
def CMOVAE(cpu, dest, src):
        dest.write(Operators.ITEBV(dest.size, cpu.CF == False, src.read(), dest.read()))

Response: Conditional move - Above or not below.


Instruction:
Can you tell what is the following Python 3 function doing
def CMOVZ(cpu, dest, src):
        dest.write(Operators.ITEBV(dest.size, cpu.ZF, src.read(), dest.read()))

Response: Conditional move - Equal or zero.


Instruction:
Can you tell what is the following Python 3 function doing
def CMOVP(cpu, dest, src):
        dest.write(Operators.ITEBV(dest.size, cpu.PF, src.read(), dest.read()))

Response: Conditional move - Parity even.


Instruction:
Here you have a function in Python 3, explain what it does
def CMOVNP(cpu, dest, src):
        dest.write(Operators.ITEBV(dest.size, cpu.PF == False, src.read(), dest.read()))

Response: Conditional move - Not parity odd.


Instruction:
Can you generate the documentation for the following Python 3 function
def CMOVNO(cpu, dest, src):
        dest.write(Operators.ITEBV(dest.size, cpu.OF == False, src.read(), dest.read()))

Response: Conditional move - Not overflow.


Instruction:
Here you have a function in Python 3, explain what it does
def CMOVNS(cpu, dest, src):
        dest.write(Operators.ITEBV(dest.size, cpu.SF == False, src.read(), dest.read()))

Response: Conditional move - Not sign ( non - negative.


Instruction:
Write a Python 3 function for
loading the status flags into the AH register.

Response:
def LAHF(cpu):
        """
        Loads status flags into AH register.

        Moves the low byte of the EFLAGS register (which includes status flags
        SF, ZF, AF, PF, and CF) to the AH register. Reserved bits 1, 3, and 5
        of the EFLAGS register are set in the AH register::

                AH  =  EFLAGS(SF:ZF:0:AF:0:PF:1:CF);

        :param cpu: current CPU.
        :param dest: destination operand.
        :param src: source operand.
        """
        used_regs = (cpu.SF, cpu.ZF, cpu.AF, cpu.PF, cpu.CF)
        is_expression = any(issymbolic(x) for x in used_regs)

        def make_flag(val, offset):
            if is_expression:
                return Operators.ITEBV(8, val,
                                       BitVecConstant(8, 1 << offset),
                                       BitVecConstant(8, 0))
            else:
                return val << offset

        cpu.AH = (make_flag(cpu.SF, 7) |
                  make_flag(cpu.ZF, 6) |
                  make_flag(0, 5) |
                  make_flag(cpu.AF, 4) |
                  make_flag(0, 3) |
                  make_flag(cpu.PF, 2) |
                  make_flag(1, 1) |
                  make_flag(cpu.CF, 0))


Instruction:
Create a Python 3 function for
loading the effective address of the source operand and store it in the destination operand.

Response:
def LEA(cpu, dest, src):
        """
        Loads effective address.

        Computes the effective address of the second operand (the source operand) and stores it in the first operand
        (destination operand). The source operand is a memory address (offset part) specified with one of the processors
        addressing modes; the destination operand is a general-purpose register. The address-size and operand-size
        attributes affect the action performed by this instruction. The operand-size
        attribute of the instruction is determined by the chosen register; the address-size attribute is determined by the
        attribute of the code segment.

        :param cpu: current CPU.
        :param dest: destination operand.
        :param src: source operand.
        """
        dest.write(Operators.EXTRACT(src.address(), 0, dest.size))


Instruction:
Make a summary of the following Python 3 code
def MOVBE(cpu, dest, src):
        size = dest.size
        arg0 = dest.read()
        temp = 0
        for pos in range(0, size, 8):
            temp = (temp << 8) | (arg0 & 0xff)
            arg0 = arg0 >> 8
        dest.write(arg0)

Response: This function moves data after swapping bytes.


Instruction:
Explain what the following Python 3 code does
def SAHF(cpu):

        eflags_size = 32
        val = cpu.AH & 0xD5 | 0x02

        cpu.EFLAGS = Operators.ZEXTEND(val, eflags_size)

Response: Stores AH into flags.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def SETA(cpu, dest):
        dest.write(Operators.ITEBV(dest.size, Operators.OR(cpu.CF, cpu.ZF) == False, 1, 0))

Response: Sets the destination operand to 0 or 1 depending on the status flags of the current CPU.


Instruction:
Here you have a function in Python 3, explain what it does
def SETB(cpu, dest):
        dest.write(Operators.ITEBV(dest.size, cpu.CF, 1, 0))

Response: Sets byte if below.


Instruction:
How would you code a function in Python 3 to
set byte if below or equal.

Response:
def SETBE(cpu, dest):
        """
        Sets byte if below or equal.

        :param cpu: current CPU.
        :param dest: destination operand.
        """
        dest.write(Operators.ITEBV(dest.size, Operators.OR(cpu.CF, cpu.ZF), 1, 0))


Instruction:
Write a Python 3 script to
set if carry. :param cpu: current CPU. :param dest: destination operand.

Response:
def SETC(cpu, dest):
        """
        Sets if carry.

        :param cpu: current CPU.
        :param dest: destination operand.
        """
        dest.write(Operators.ITEBV(dest.size, cpu.CF, 1, 0))


Instruction:
Write a Python 3 function that can
set byte if equal.

Response:
def SETE(cpu, dest):
        """
        Sets byte if equal.

        :param cpu: current CPU.
        :param dest: destination operand.
        """
        dest.write(Operators.ITEBV(dest.size, cpu.ZF, 1, 0))


Instruction:
Make a summary of the following Python 3 code
def SETGE(cpu, dest):
        dest.write(Operators.ITEBV(dest.size, cpu.SF == cpu.OF, 1, 0))

Response: Sets byte if greater or equal.


Instruction:
Write a Python 3 function for
setting byte if not above or equal.

Response:
def SETNAE(cpu, dest):
        """
        Sets byte if not above or equal.

        :param cpu: current CPU.
        :param dest: destination operand.
        """
        dest.write(Operators.ITEBV(dest.size, cpu.CF, 1, 0))


Instruction:
How would you implement a function in Python 3 that
sets byte if not below.

Response:
def SETNB(cpu, dest):
        """
        Sets byte if not below.

        :param cpu: current CPU.
        :param dest: destination operand.
        """
        dest.write(Operators.ITEBV(dest.size, cpu.CF == False, 1, 0))


Instruction:
Explain what the following Python 3 code does
def SETNBE(cpu, dest):
        dest.write(Operators.ITEBV(dest.size, Operators.AND(cpu.CF == False, cpu.ZF == False), 1, 0))

Response: Sets byte if not below or equal.


Instruction:
Can you tell what is the following Python 3 function doing
def SETNG(cpu, dest):
        dest.write(Operators.ITEBV(dest.size, Operators.OR(cpu.ZF, cpu.SF != cpu.OF), 1, 0))

Response: Sets byte if not greater.


Instruction:
Here you have a function in Python 3, explain what it does
def SETNLE(cpu, dest):
        dest.write(Operators.ITEBV(dest.size, Operators.AND(cpu.ZF == False, cpu.SF == cpu.OF), 1, 0))

Response: Sets byte if not less or equal.


Instruction:
Make a summary of the following Python 3 code
def SETNO(cpu, dest):
        dest.write(Operators.ITEBV(dest.size, cpu.OF == False, 1, 0))

Response: Sets byte if not overflow.


Instruction:
Create a Python 3 function for
setting byte if not sign.

Response:
def SETNS(cpu, dest):
        """
        Sets byte if not sign.

        :param cpu: current CPU.
        :param dest: destination operand.
        """
        dest.write(Operators.ITEBV(dest.size, cpu.SF == False, 1, 0))


Instruction:
Implement a Python 3 function for
setting byte if not zero.

Response:
def SETNZ(cpu, dest):
        """
        Sets byte if not zero.

        :param cpu: current CPU.
        :param dest: destination operand.
        """
        dest.write(Operators.ITEBV(dest.size, cpu.ZF == False, 1, 0))


Instruction:
Can you generate the documentation for the following Python 3 function
def SETO(cpu, dest):
        dest.write(Operators.ITEBV(dest.size, cpu.OF, 1, 0))

Response: Sets byte if overflow.


Instruction:
Explain what the following Python 3 code does
def SETP(cpu, dest):
        dest.write(Operators.ITEBV(dest.size, cpu.PF, 1, 0))

Response: Sets byte if parity.


Instruction:
How would you explain what the following Python 3 function does
def SETPE(cpu, dest):
        dest.write(Operators.ITEBV(dest.size, cpu.PF, 1, 0))

Response: Sets byte if parity even.


Instruction:
Write a Python 3 script to
set byte if parity odd.

Response:
def SETPO(cpu, dest):
        """
        Sets byte if parity odd.

        :param cpu: current CPU.
        :param dest: destination operand.
        """
        dest.write(Operators.ITEBV(dest.size, cpu.PF == False, 1, 0))


Instruction:
Given the following Python 3 function, write the documentation
def SETS(cpu, dest):
        dest.write(Operators.ITEBV(dest.size, cpu.SF, 1, 0))

Response: Sets byte if sign.


Instruction:
Can you generate the documentation for the following Python 3 function
def SETZ(cpu, dest):
        dest.write(Operators.ITEBV(dest.size, cpu.ZF, 1, 0))

Response: Sets byte if zero.


Instruction:
Can you tell what is the following Python 3 function doing
def XCHG(cpu, dest, src):
        temp = dest.read()
        dest.write(src.read())
        src.write(temp)

Response: This instruction is used to set the contents of the destination and source memory locations for the specified CPU.


Instruction:
Can you tell what is the following Python 3 function doing
def LEAVE(cpu):
        cpu.STACK = cpu.FRAME
        cpu.FRAME = cpu.pop(cpu.address_bit_size)

Response: This function is called by the ENTER instruction to release the stack frame allocated by the calling procedure s stack.


Instruction:
Implement a function in Python 3 to
push a value onto the stack.

Response:
def PUSH(cpu, src):
        """
        Pushes a value onto the stack.

        Decrements the stack pointer and then stores the source operand on the top of the stack.

        :param cpu: current CPU.
        :param src: source operand.
        """
        # http://stackoverflow.com/questions/11291151/how-push-imm-encodes
        size = src.size
        v = src.read()
        if size != 64 and size != cpu.address_bit_size // 2:
            v = Operators.SEXTEND(v, size, cpu.address_bit_size)
            size = cpu.address_bit_size
        cpu.push(v, size)


Instruction:
Create a Python 3 function to
pop stack into EFLAGS register.

Response:
def POPF(cpu):
        """
        Pops stack into EFLAGS register.

        :param cpu: current CPU.
        """
        mask = (0x00000001 |
                0x00000004 |
                0x00000010 |
                0x00000040 |
                0x00000080 |
                0x00000400 |
                0x00000800)
        val = cpu.pop(16)
        eflags_size = 32
        cpu.EFLAGS = Operators.ZEXTEND(val & mask, eflags_size)


Instruction:
Write a Python 3 script to
pop stack into EFLAGS register.

Response:
def POPFQ(cpu):
        """
        Pops stack into EFLAGS register.

        :param cpu: current CPU.
        """
        mask = 0x00000001 | 0x00000004 | 0x00000010 | 0x00000040 | 0x00000080 | 0x00000400 | 0x00000800
        cpu.EFLAGS = (cpu.EFLAGS & ~mask) | cpu.pop(64) & mask


Instruction:
How would you code a function in Python 3 to
call to interrupt procedure. The INT n instruction generates a call to the interrupt or exception handler specified with the destination operand. The INT n instruction is the general mnemonic for executing a software-generated call to an interrupt handler. The INTO instruction is a special mnemonic for calling overflow exception (#OF), interrupt vector number 4. The overflow interrupt checks the OF flag in the EFLAGS register and calls the overflow interrupt handler if the OF flag is set to 1. :param cpu: current CPU. :param op0: destination operand.

Response:
def INT(cpu, op0):
        """
        Calls to interrupt procedure.

        The INT n instruction generates a call to the interrupt or exception handler specified
        with the destination operand. The INT n instruction is the  general mnemonic for executing
        a software-generated call to an interrupt handler. The INTO instruction is a special
        mnemonic for calling overflow exception (#OF), interrupt vector number 4. The overflow
        interrupt checks the OF flag in the EFLAGS register and calls the overflow interrupt handler
        if the OF flag is set to 1.

        :param cpu: current CPU.
        :param op0: destination operand.
        """
        if op0.read() != 0x80:
            logger.warning("Unsupported interrupt")
        raise Interruption(op0.read())


Instruction:
Write a Python 3 script to
jump short if above.

Response:
def JA(cpu, target):
        """
        Jumps short if above.

        :param cpu: current CPU.
        :param target: destination operand.
        """
        cpu.PC = Operators.ITEBV(cpu.address_bit_size, Operators.AND(cpu.CF == False, cpu.ZF == False), target.read(), cpu.PC)


Instruction:
Here you have a function in Python 3, explain what it does
def JB(cpu, target):
        cpu.PC = Operators.ITEBV(cpu.address_bit_size, cpu.CF == True, target.read(), cpu.PC)

Response: Jumps short if below.


Instruction:
Explain what the following Python 3 code does
def JBE(cpu, target):
        cpu.PC = Operators.ITEBV(cpu.address_bit_size, Operators.OR(cpu.CF, cpu.ZF), target.read(), cpu.PC)

Response: Jumps short if below or equal.


Instruction:
Can you generate the documentation for the following Python 3 function
def JC(cpu, target):
        cpu.PC = Operators.ITEBV(cpu.address_bit_size, cpu.CF, target.read(), cpu.PC)

Response: Jumps short if carry.


Instruction:
Write a Python 3 function that can
jump short if CX register is 0.

Response:
def JCXZ(cpu, target):
        """
        Jumps short if CX register is 0.

        :param cpu: current CPU.
        :param target: destination operand.
        """
        cpu.PC = Operators.ITEBV(cpu.address_bit_size, cpu.CX == 0, target.read(), cpu.PC)


Instruction:
Here you have a function in Python 3, explain what it does
def JECXZ(cpu, target):
        cpu.PC = Operators.ITEBV(cpu.address_bit_size, cpu.ECX == 0, target.read(), cpu.PC)

Response: Jumps short if ECX register is 0.


Instruction:
Implement a Python 3 function for
jumping short if RCX register is 0.

Response:
def JRCXZ(cpu, target):
        """
        Jumps short if RCX register is 0.

        :param cpu: current CPU.
        :param target: destination operand.
        """
        cpu.PC = Operators.ITEBV(cpu.address_bit_size, cpu.RCX == 0, target.read(), cpu.PC)


Instruction:
Can you implement a function in Python 3 that
jumps short if greater.

Response:
def JG(cpu, target):
        """
        Jumps short if greater.

        :param cpu: current CPU.
        :param target: destination operand.
        """
        cpu.PC = Operators.ITEBV(cpu.address_bit_size, Operators.AND(cpu.ZF == False, cpu.SF == cpu.OF), target.read(), cpu.PC)


Instruction:
Write a Python 3 function that can
jump short if greater or equal.

Response:
def JGE(cpu, target):
        """
        Jumps short if greater or equal.

        :param cpu: current CPU.
        :param target: destination operand.
        """
        cpu.PC = Operators.ITEBV(cpu.address_bit_size, (cpu.SF == cpu.OF), target.read(), cpu.PC)


Instruction:
Here you have a function in Python 3, explain what it does
def JNB(cpu, target):
        cpu.PC = Operators.ITEBV(cpu.address_bit_size, cpu.CF == False, target.read(), cpu.PC)

Response: Jumps short if not below.


Instruction:
Write a Python 3 function for
jumping short if not equal.

Response:
def JNE(cpu, target):
        """
        Jumps short if not equal.

        :param cpu: current CPU.
        :param target: destination operand.
        """
        cpu.PC = Operators.ITEBV(cpu.address_bit_size, False == cpu.ZF, target.read(), cpu.PC)


Instruction:
Create a Python 3 function to
jump short if not greater than target.

Response:
def JNG(cpu, target):
        """
        Jumps short if not greater.

        :param cpu: current CPU.
        :param target: destination operand.
        """
        cpu.PC = Operators.ITEBV(cpu.address_bit_size, Operators.OR(cpu.ZF, cpu.SF != cpu.OF), target.read(), cpu.PC)


Instruction:
Write a Python 3 script to
jump short if not overflow.

Response:
def JNO(cpu, target):
        """
        Jumps short if not overflow.

        :param cpu: current CPU.
        :param target: destination operand.
        """
        cpu.PC = Operators.ITEBV(cpu.address_bit_size, False == cpu.OF, target.read(), cpu.PC)


Instruction:
Make a summary of the following Python 3 code
def JNP(cpu, target):
        cpu.PC = Operators.ITEBV(cpu.address_bit_size, False == cpu.PF, target.read(), cpu.PC)

Response: Jumps short if not parity.


Instruction:
Here you have a function in Python 3, explain what it does
def JNS(cpu, target):
        cpu.PC = Operators.ITEBV(cpu.address_bit_size, False == cpu.SF, target.read(), cpu.PC)

Response: Jumps short if not sign.


Instruction:
Implement a Python 3 function for
jumping short if overflow.

Response:
def JO(cpu, target):
        """
        Jumps short if overflow.

        :param cpu: current CPU.
        :param target: destination operand.
        """
        cpu.PC = Operators.ITEBV(cpu.address_bit_size, cpu.OF, target.read(), cpu.PC)


Instruction:
Write a Python 3 function that can
jump short if parity.

Response:
def JP(cpu, target):
        """
        Jumps short if parity.

        :param cpu: current CPU.
        :param target: destination operand.
        """
        cpu.PC = Operators.ITEBV(cpu.address_bit_size, cpu.PF, target.read(), cpu.PC)


Instruction:
Write a Python 3 function for
jumping short if sign.

Response:
def JS(cpu, target):
        """
        Jumps short if sign.

        :param cpu: current CPU.
        :param target: destination operand.
        """
        cpu.PC = Operators.ITEBV(cpu.address_bit_size, cpu.SF, target.read(), cpu.PC)


Instruction:
Write a Python 3 script to
jump short if zero.

Response:
def JZ(cpu, target):
        """
        Jumps short if zero.

        :param cpu: current CPU.
        :param target: destination operand.
        """
        cpu.PC = Operators.ITEBV(cpu.address_bit_size, cpu.ZF, target.read(), cpu.PC)


Instruction:
Create a Python 3 function for
jumping to the target CS and PC

Response:
def LJMP(cpu, cs_selector, target):
        """
        We are just going to ignore the CS selector for now.
        """
        logger.info("LJMP: Jumping to: %r:%r", cs_selector.read(), target.read())
        cpu.CS = cs_selector.read()
        cpu.PC = target.read()


Instruction:
How would you implement a function in Python 3 that
loops according to ECX counter. Performs a loop operation using the ECX or CX register as a counter. Each time the LOOP instruction is executed, the count register is decremented, then checked for 0. If the count is 0, the loop is terminated and program execution continues with the instruction following the LOOP instruction. If the count is not zero, a near jump is performed to the destination (target) operand, which is presumably the instruction at the beginning of the loop. If the address-size attribute is 32 bits, the ECX register is used as the count register; otherwise the CX register is used:: IF address_bit_size = 32 THEN Count is ECX; ELSE (* address_bit_size = 16 *) Count is CX; FI; Count = Count - 1; IF (Count 0) = 1 THEN EIP = EIP + SignExtend(DEST); IF OperandSize = 16 THEN EIP = EIP AND 0000FFFFH; FI; ELSE Terminate loop and continue program execution at EIP; FI; :param cpu: current CPU. :param dest: destination operand.

Response:
def LOOP(cpu, dest):
        """
        Loops according to ECX counter.

        Performs a loop operation using the ECX or CX register as a counter.
        Each time the LOOP instruction is executed, the count register is decremented,
        then checked for 0. If the count is 0, the loop is terminated and program
        execution continues with the instruction following the LOOP instruction.
        If the count is not zero, a near jump is performed to the destination
        (target) operand, which is presumably the instruction at the beginning
        of the loop. If the address-size attribute is 32 bits, the ECX register
        is used as the count register; otherwise the CX register is used::

                IF address_bit_size  =  32
                THEN
                    Count is ECX;
                ELSE (* address_bit_size  =  16 *)
                    Count is CX;
                FI;
                Count  =  Count - 1;

                IF (Count  0)  =  1
                THEN
                    EIP  =  EIP + SignExtend(DEST);
                    IF OperandSize  =  16
                    THEN
                        EIP  =  EIP AND 0000FFFFH;
                    FI;
                ELSE
                    Terminate loop and continue program execution at EIP;
                FI;

        :param cpu: current CPU.
        :param dest: destination operand.
        """
        counter_name = {16: 'CX', 32: 'ECX', 64: 'RCX'}[cpu.address_bit_size]
        counter = cpu.write_register(counter_name, cpu.read_register(counter_name) - 1)
        cpu.PC = Operators.ITEBV(cpu.address_bit_size, counter == 0, (cpu.PC + dest.read()) & ((1 << dest.size) - 1), cpu.PC + cpu.instruction.size)


Instruction:
Implement a function in Python 3 to
loop if ECX counter is nonzero.

Response:
def LOOPNZ(cpu, target):
        """
        Loops if ECX counter is nonzero.

        :param cpu: current CPU.
        :param target: destination operand.
        """
        counter_name = {16: 'CX', 32: 'ECX', 64: 'RCX'}[cpu.address_bit_size]
        counter = cpu.write_register(counter_name, cpu.read_register(counter_name) - 1)
        cpu.PC = Operators.ITEBV(cpu.address_bit_size, counter != 0, (cpu.PC + target.read()) & ((1 << target.size) - 1), cpu.PC + cpu.instruction.size)


Instruction:
Create a Python 3 function to
rotate through carry left. Shifts (rotates) the bits of the first operand (destination operand) the number of bit positions specified in the second operand (count operand) and stores the result in the destination operand. The destination operand can be a register or a memory location; the count operand is an unsigned integer that can be an immediate or a value in the CL register. In legacy and compatibility mode, the processor restricts the count to a number between 0 and 31 by masking all the bits in the count operand except the 5 least-significant bits. The RCL instruction shifts the CF flag into the least-significant bit and shifts the most-significant bit into the CF flag. :param cpu: current CPU. :param dest: destination operand. :param src: count operand.

Response:
def RCL(cpu, dest, src):
        """
        Rotates through carry left.

        Shifts (rotates) the bits of the first operand (destination operand) the number of bit positions specified in the
        second operand (count operand) and stores the result in the destination operand. The destination operand can be
        a register or a memory location; the count operand is an unsigned integer that can be an immediate or a value in
        the CL register. In legacy and compatibility mode, the processor restricts the count to a number between 0 and 31
        by masking all the bits in the count operand except the 5 least-significant bits.

        The RCL instruction shifts the CF flag into the least-significant bit and shifts the most-significant bit into the CF flag.

        :param cpu: current CPU.
        :param dest: destination operand.
        :param src: count operand.
        """
        OperandSize = dest.size
        count = src.read()
        countMask = {8: 0x1f,
                     16: 0x1f,
                     32: 0x1f,
                     64: 0x3f}[OperandSize]
        tempCount = Operators.ZEXTEND((count & countMask) % (src.size + 1), OperandSize)

        value = dest.read()

        if isinstance(tempCount, int) and tempCount == 0:
            # this is a no-op
            new_val = value
            dest.write(new_val)
        else:
            carry = Operators.ITEBV(OperandSize, cpu.CF, 1, 0)
            right = value >> (OperandSize - tempCount)
            new_val = (value << tempCount) | (carry << (tempCount - 1)) | (right >> 1)
            dest.write(new_val)

            def sf(v, size):
                return (v & (1 << (size - 1))) != 0
            cpu.CF = sf(value << (tempCount - 1), OperandSize)
            cpu.OF = Operators.ITE(tempCount == 1,
                                   sf(new_val, OperandSize) != cpu.CF,
                                   cpu.OF)


Instruction:
Write a Python 3 function for
rotating through carry right instruction and store the result in dest.

Response:
def RCR(cpu, dest, src):
        """
        Rotates through carry right (RCR).

        Shifts (rotates) the bits of the first operand (destination operand) the number of bit positions specified in the
        second operand (count operand) and stores the result in the destination operand. The destination operand can be
        a register or a memory location; the count operand is an unsigned integer that can be an immediate or a value in
        the CL register. In legacy and compatibility mode, the processor restricts the count to a number between 0 and 31
        by masking all the bits in the count operand except the 5 least-significant bits.

        Rotate through carry right (RCR) instructions shift all the bits toward less significant bit positions, except
        for the least-significant bit, which is rotated to the most-significant bit location. The RCR instruction shifts the
        CF flag into the most-significant bit and shifts the least-significant bit into the CF flag.

        :param cpu: current CPU.
        :param dest: destination operand.
        :param src: count operand.
        """
        OperandSize = dest.size
        count = src.read()
        countMask = {8: 0x1f,
                     16: 0x1f,
                     32: 0x1f,
                     64: 0x3f}[OperandSize]
        tempCount = Operators.ZEXTEND((count & countMask) % (src.size + 1), OperandSize)

        value = dest.read()
        if isinstance(tempCount, int) and tempCount == 0:
            # this is a no-op
            new_val = value
            dest.write(new_val)
        else:
            carry = Operators.ITEBV(OperandSize, cpu.CF, 1, 0)
            left = value >> (tempCount - 1)
            right = value << (OperandSize - tempCount)

            new_val = (left >> 1) | (carry << (OperandSize - tempCount)) | (right << 1)

            dest.write(new_val)

            cpu.CF = Operators.ITE(tempCount != 0, (left & 1) == 1, cpu.CF)
            # for RCR these are calculated before rotation starts
            s_MSB = ((new_val >> (OperandSize - 1)) & 0x1) == 1
            s_MSB2 = ((new_val >> (OperandSize - 2)) & 0x1) == 1
            cpu.OF = Operators.ITE(tempCount == 1,
                                   s_MSB ^ s_MSB2, cpu.OF)


Instruction:
Write a Python 3 function that can
rotate left shift the bits of the first operand and store the result in the destination operand.

Response:
def ROL(cpu, dest, src):
        """
        Rotates left (ROL).

        Shifts (rotates) the bits of the first operand (destination operand) the number of bit positions specified in the
        second operand (count operand) and stores the result in the destination operand. The destination operand can be
        a register or a memory location; the count operand is an unsigned integer that can be an immediate or a value in
        the CL register. In legacy and compatibility mode, the processor restricts the count to a number between 0 and 31
        by masking all the bits in the count operand except the 5 least-significant bits.

        The rotate left shift all the bits toward more-significant bit positions, except for the most-significant bit, which
        is rotated to the least-significant bit location.

        :param cpu: current CPU.
        :param dest: destination operand.
        :param src: count operand.
        """
        OperandSize = dest.size
        count = src.read()
        countMask = {8: 0x1f,
                     16: 0x1f,
                     32: 0x1f,
                     64: 0x3f}[OperandSize]
        tempCount = Operators.ZEXTEND((count & countMask) % (OperandSize), OperandSize)

        value = dest.read()
        newValue = (value << tempCount) | (value >> (OperandSize - tempCount))
        dest.write(newValue)

        cpu.CF = Operators.ITE(tempCount != 0, (newValue & 1) == 1, cpu.CF)
        s_MSB = ((newValue >> (OperandSize - 1)) & 0x1) == 1
        cpu.OF = Operators.ITE(tempCount == 1, s_MSB ^ cpu.CF, cpu.OF)


Instruction:
How would you implement a function in Python 3 that
shifts arithmetic right and shift logical right.

Response:
def SAR(cpu, dest, src):
        """
        Shift arithmetic right.

        The shift arithmetic right (SAR) and shift logical right (SHR) instructions shift the bits of the destination operand to
        the right (toward less significant bit locations). For each shift count, the least significant bit of the destination
        operand is shifted into the CF flag, and the most significant bit is either set or cleared depending on the instruction
        type. The SHR instruction clears the most significant bit. the SAR instruction sets or clears the most significant bit
        to correspond to the sign (most significant bit) of the original value in the destination operand. In effect, the SAR
        instruction fills the empty bit position's shifted value with the sign of the unshifted value

        :param cpu: current CPU.
        :param dest: destination operand.
        :param src: source operand.
        """
        OperandSize = dest.size
        countMask = {8: 0x1f,
                     16: 0x1f,
                     32: 0x1f,
                     64: 0x3f}[OperandSize]

        count = src.read() & countMask
        value = dest.read()

        res = Operators.SAR(OperandSize, value, Operators.ZEXTEND(count, OperandSize))
        dest.write(res)

        SIGN_MASK = (1 << (OperandSize - 1))

        # We can't use this one as the 'true' expression gets eagerly calculated even on count == 0		 +        cpu.CF = Operators.ITE(count!=0, ((value >> Operators.ZEXTEND(count-1, OperandSize)) & 1) !=0, cpu.CF)
        # cpu.CF = Operators.ITE(count!=0, ((value >> Operators.ZEXTEND(count-1, OperandSize)) & 1) !=0, cpu.CF)

        if issymbolic(count):
            # We can't use this one as the EXTRACT op needs the offset arguments to be concrete
            #    cpu.CF = Operators.ITE(count!=0, Operands.EXTRACT(value,count-1,1) !=0, cpu.CF)
            cpu.CF = Operators.ITE(Operators.AND(count != 0, count <= OperandSize), ((value >> Operators.ZEXTEND(count - 1, OperandSize)) & 1) != 0, cpu.CF)
        else:
            if count != 0:
                if count > OperandSize:
                    count = OperandSize
                cpu.CF = Operators.EXTRACT(value, count - 1, 1) != 0

        # on count == 0 AF is unaffected, for count > 0, AF is undefined.
        # in either case, do not touch AF
        cpu.ZF = Operators.ITE(count != 0, res == 0, cpu.ZF)
        cpu.SF = Operators.ITE(count != 0, (res & SIGN_MASK) != 0, cpu.SF)
        cpu.OF = Operators.ITE(count == 1, False, cpu.OF)
        cpu.PF = Operators.ITE(count != 0, cpu._calculate_parity_flag(res), cpu.PF)


Instruction:
Write a Python 3 function that can
shift logical right instruction.

Response:
def SHR(cpu, dest, src):
        """
        Shift logical right.

        The shift arithmetic right (SAR) and shift logical right (SHR)
        instructions shift the bits of the destination operand to the right
        (toward less significant bit locations). For each shift count, the
        least significant bit of the destination operand is shifted into the CF
        flag, and the most significant bit is either set or cleared depending
        on the instruction type. The SHR instruction clears the most
        significant bit.

        :param cpu: current CPU.
        :param dest: destination operand.
        :param src: count operand.
        """
        OperandSize = dest.size
        count = Operators.ZEXTEND(src.read() & (OperandSize - 1), OperandSize)
        value = dest.read()

        res = dest.write(value >> count)  # UNSIGNED Operators.UDIV2 !! TODO Check

        MASK = (1 << OperandSize) - 1
        SIGN_MASK = 1 << (OperandSize - 1)

        if issymbolic(count):
            cpu.CF = Operators.ITE(count != 0,
                                   ((value >> Operators.ZEXTEND(count - 1, OperandSize)) & 1) != 0,
                                   cpu.CF)
        else:
            if count != 0:
                cpu.CF = Operators.EXTRACT(value, count - 1, 1) != 0

        cpu.ZF = Operators.ITE(count != 0, res == 0, cpu.ZF)
        cpu.SF = Operators.ITE(count != 0, (res & SIGN_MASK) != 0, cpu.SF)
        # OF is only defined for count == 1, but in practice (unit tests from real cpu) it's calculated for count != 0
        cpu.OF = Operators.ITE(count != 0, ((value >> (OperandSize - 1)) & 0x1) == 1, cpu.OF)
        cpu.PF = Operators.ITE(count != 0, cpu._calculate_parity_flag(res), cpu.PF)


Instruction:
Explain what the following Python 3 code does
def SHLD(cpu, dest, src, count):
        OperandSize = dest.size
        tempCount = Operators.ZEXTEND(count.read(), OperandSize) & (OperandSize - 1)
        arg0 = dest.read()
        arg1 = src.read()

        MASK = ((1 << OperandSize) - 1)
        t0 = (arg0 << tempCount)
        t1 = arg1 >> (OperandSize - tempCount)
        res = Operators.ITEBV(OperandSize, tempCount == 0, arg0, t0 | t1)
        res = res & MASK
        dest.write(res)
        if isinstance(tempCount, int) and tempCount == 0:
            pass
        else:
            SIGN_MASK = 1 << (OperandSize - 1)
            lastbit = 0 != ((arg0 << (tempCount - 1)) & SIGN_MASK)

            cpu._set_shiftd_flags(OperandSize, arg0, res, lastbit, tempCount)

Response: Double precision shift right.


Instruction:
Here you have a function in Python 3, explain what it does
def _getMemoryBit(cpu, bitbase, bitoffset):
        assert bitbase.type == 'memory'
        assert bitbase.size >= bitoffset.size
        addr = bitbase.address()
        offt = Operators.SEXTEND(bitoffset.read(), bitoffset.size, bitbase.size)
        offt_is_neg = offt >= (1 << (bitbase.size - 1))
        offt_in_bytes = offt // 8
        bitpos = offt % 8

        new_addr = addr + Operators.ITEBV(bitbase.size, offt_is_neg, -offt_in_bytes, offt_in_bytes)
        return (new_addr, bitpos)

Response: Calculate the address and bit offset for a memory entry.


Instruction:
Write a Python 3 function for
biting scan forward. Searches the source operand (second operand) for the least significant set bit (1 bit). If a least significant 1 bit is found, its bit index is stored in the destination operand (first operand). The source operand can be a register or a memory location; the destination operand is a register. The bit index is an unsigned offset from bit 0 of the source operand. If the contents source operand are 0, the contents of the destination operand is undefined:: IF SRC = 0 THEN ZF = 1; DEST is undefined; ELSE ZF = 0; temp = 0; WHILE Bit(SRC, temp) = 0 DO temp = temp + 1; DEST = temp; OD; FI; :param cpu: current CPU. :param dest: destination operand. :param src: source operand.

Response:
def BSF(cpu, dest, src):
        """
        Bit scan forward.

        Searches the source operand (second operand) for the least significant
        set bit (1 bit). If a least significant 1 bit is found, its bit index
        is stored in the destination operand (first operand). The source operand
        can be a register or a memory location; the destination operand is a register.
        The bit index is an unsigned offset from bit 0 of the source operand.
        If the contents source operand are 0, the contents of the destination
        operand is undefined::

                    IF SRC  =  0
                    THEN
                        ZF  =  1;
                        DEST is undefined;
                    ELSE
                        ZF  =  0;
                        temp  =  0;
                        WHILE Bit(SRC, temp)  =  0
                        DO
                            temp  =  temp + 1;
                            DEST  =  temp;
                        OD;
                    FI;

        :param cpu: current CPU.
        :param dest: destination operand.
        :param src: source operand.
        """
        value = src.read()
        flag = Operators.EXTRACT(value, 0, 1) == 1
        res = 0
        for pos in range(1, src.size):
            res = Operators.ITEBV(dest.size, flag, res, pos)
            flag = Operators.OR(flag, Operators.EXTRACT(value, pos, 1) == 1)

        cpu.ZF = value == 0
        dest.write(Operators.ITEBV(dest.size, cpu.ZF, dest.read(), res))


Instruction:
Given the following Python 3 function, write the documentation
def BSR(cpu, dest, src):
        value = src.read()
        flag = Operators.EXTRACT(value, src.size - 1, 1) == 1
        res = 0

        for pos in reversed(range(0, src.size)):
            res = Operators.ITEBV(dest.size, flag, res, pos)
            flag = Operators.OR(flag, (Operators.EXTRACT(value, pos, 1) == 1))

        cpu.PF = cpu._calculate_parity_flag(res)
        cpu.ZF = value == 0
        dest.write(Operators.ITEBV(dest.size, cpu.ZF, dest.read(), res))

Response: Bit scan for the most significant set bit in the source and destination memory locations.


Instruction:
Write a Python 3 function for
biting test and complement.

Response:
def BTC(cpu, dest, src):
        """
        Bit test and complement.

        Selects the bit in a bit string (specified with the first operand, called
        the bit base) at the bit-position designated by the bit offset operand
        (second operand), stores the value of the bit in the CF flag, and complements
        the selected bit in the bit string.

        :param cpu: current CPU.
        :param dest: bit base operand.
        :param src: bit offset operand.
        """
        if dest.type == 'register':
            value = dest.read()
            pos = src.read() % dest.size
            cpu.CF = value & (1 << pos) == 1 << pos
            dest.write(value ^ (1 << pos))
        elif dest.type == 'memory':
            addr, pos = cpu._getMemoryBit(dest, src)
            base, size, ty = cpu.get_descriptor(cpu.DS)
            addr += base
            value = cpu.read_int(addr, 8)
            cpu.CF = value & (1 << pos) == 1 << pos
            value = value ^ (1 << pos)
            cpu.write_int(addr, value, 8)
        else:
            raise NotImplementedError(f"Unknown operand for BTC: {dest.type}")


Instruction:
Given the following Python 3 function, write the documentation
def CMPS(cpu, dest, src):
        src_reg = {8: 'SI', 32: 'ESI', 64: 'RSI'}[cpu.address_bit_size]
        dest_reg = {8: 'DI', 32: 'EDI', 64: 'RDI'}[cpu.address_bit_size]

        base, _, ty = cpu.get_descriptor(cpu.DS)

        src_addr = cpu.read_register(src_reg) + base
        dest_addr = cpu.read_register(dest_reg) + base
        size = dest.size

        # Compare
        arg1 = cpu.read_int(dest_addr, size)
        arg0 = cpu.read_int(src_addr, size)
        res = (arg0 - arg1) & ((1 << size) - 1)

        cpu._calculate_CMP_flags(size, res, arg0, arg1)

        #Advance EDI/ESI pointers
        increment = Operators.ITEBV(cpu.address_bit_size, cpu.DF, -size // 8, size // 8)
        cpu.write_register(src_reg, cpu.read_register(src_reg) + increment)
        cpu.write_register(dest_reg, cpu.read_register(dest_reg) + increment)

Response: Sets the status of the two sources in memory.


Instruction:
Can you tell what is the following Python 3 function doing
def LODS(cpu, dest, src):
        src_reg = {8: 'SI', 32: 'ESI', 64: 'RSI'}[cpu.address_bit_size]
        base, _, ty = cpu.get_descriptor(cpu.DS)

        src_addr = cpu.read_register(src_reg) + base
        size = dest.size

        arg0 = cpu.read_int(src_addr, size)
        dest.write(arg0)

        increment = Operators.ITEBV(cpu.address_bit_size, cpu.DF, -size // 8, size // 8)
        cpu.write_register(src_reg, cpu.read_register(src_reg) + increment)

Response: Load a string from the source operand into the destination operand.


Instruction:
Can you generate the documentation for the following Python 3 function
def MOVS(cpu, dest, src):
        base, size, ty = cpu.get_descriptor(cpu.DS)
        src_addr = src.address() + base
        dest_addr = dest.address() + base

        src_reg = src.mem.base
        dest_reg = dest.mem.base
        size = dest.size

        # Copy the data
        dest.write(src.read())

        #Advance EDI/ESI pointers
        increment = Operators.ITEBV(cpu.address_bit_size, cpu.DF, -size // 8, size // 8)
        cpu.write_register(src_reg, cpu.read_register(src_reg) + increment)
        cpu.write_register(dest_reg, cpu.read_register(dest_reg) + increment)

Response: Moves data from string to string.


Instruction:
Make a summary of the following Python 3 code
def SCAS(cpu, dest, src):
        dest_reg = dest.reg
        mem_reg = src.mem.base  # , src.type, src.read()
        size = dest.size
        arg0 = dest.read()
        arg1 = src.read()
        res = arg0 - arg1
        cpu._calculate_CMP_flags(size, res, arg0, arg1)

        increment = Operators.ITEBV(cpu.address_bit_size, cpu.DF, -size // 8, size // 8)
        cpu.write_register(mem_reg, cpu.read_register(mem_reg) + increment)

Response: Sets the status flags of the current object based on the contents of the source object.


Instruction:
How would you implement a function in Python 3 that
stores a byte word doubleword from the AL AX or EAX register of the source operand into the destination operand.

Response:
def STOS(cpu, dest, src):
        """
        Stores String.

        Stores a byte, word, or doubleword from the AL, AX, or EAX register,
        respectively, into the destination operand. The destination operand is
        a memory location, the address of which is read from either the ES:EDI
        or the ES:DI registers (depending on the address-size attribute of the
        instruction, 32 or 16, respectively). The ES segment cannot be overridden
        with a segment override prefix.

        :param cpu: current CPU.
        :param dest: destination operand.
        :param src: source operand.
        """
        size = src.size
        dest.write(src.read())
        dest_reg = dest.mem.base
        increment = Operators.ITEBV({'RDI': 64, 'EDI': 32, 'DI': 16}[dest_reg], cpu.DF, -size // 8, size // 8)
        cpu.write_register(dest_reg, cpu.read_register(dest_reg) + increment)


Instruction:
How would you explain what the following Python 3 function does
def ANDN(cpu, dest, src1, src2):
        value = ~src1.read() & src2.read()
        dest.write(value)
        cpu.ZF = value == 0
        cpu.SF = (value & (1 << dest.size)) != 0
        cpu.OF = False
        cpu.CF = False

Response: Performs a bitwise AND of the two sources in the source table.


Instruction:
Explain what the following Python 3 code does
def SARX(cpu, dest, src, count):
        OperandSize = dest.size
        count = count.read()
        countMask = {8: 0x1f,
                     16: 0x1f,
                     32: 0x1f,
                     64: 0x3f}[OperandSize]
        tempCount = count & countMask
        tempDest = value = src.read()

        sign = value & (1 << (OperandSize - 1))
        while tempCount != 0:
            cpu.CF = (value & 0x1) != 0  # LSB
            value = (value >> 1) | sign
            tempCount = tempCount - 1
        res = dest.write(value)

Response: The shift arithmetic right.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _PUNPCKL(cpu, dest, src, item_size):
        assert dest.size == src.size
        size = dest.size
        dest_value = dest.read()
        src_value = src.read()
        mask = (1 << item_size) - 1
        res = 0
        count = 0
        for pos in range(0, size // item_size):
            if count >= size:
                break
            item0 = Operators.ZEXTEND((dest_value >> (pos * item_size)) & mask, size)
            item1 = Operators.ZEXTEND((src_value >> (pos * item_size)) & mask, size)
            res |= item0 << count
            count += item_size
            res |= item1 << count
            count += item_size

        dest.write(res)

Response: Generic PUNPCKL Generic PUNPCKLGeneric.


Instruction:
Can you tell what is the following Python 3 function doing
def PSHUFW(cpu, op0, op1, op3):
        size = op0.size
        arg0 = op0.read()
        arg1 = op1.read()
        arg3 = Operators.ZEXTEND(op3.read(), size)
        assert size == 64
        arg0 |= ((arg1 >> ((arg3 >> 0) & 3 * 16)) & 0xffff)
        arg0 |= ((arg1 >> ((arg3 >> 2) & 3 * 16)) & 0xffff) << 16
        arg0 |= ((arg1 >> ((arg3 >> 4) & 3 * 16)) & 0xffff) << 32
        arg0 |= ((arg1 >> ((arg3 >> 6) & 3 * 16)) & 0xffff) << 48
        op0.write(arg0)

Response:
Packed shuffle words.

        Copies doublewords from source operand (second operand) and inserts them in the destination operand
        (first operand) at locations selected with the order operand (third operand).

        :param cpu: current CPU.
        :param op0: destination operand.
        :param op1: source operand.
        :param op3: order operand.


Instruction:
Write a Python 3 function for
packing shuffle doublewords. Copies doublewords from source operand (second operand) and inserts them in the destination operand (first operand) at locations selected with the order operand (third operand). :param cpu: current CPU. :param op0: destination operand. :param op1: source operand. :param op3: order operand.

Response:
def PSHUFD(cpu, op0, op1, op3):
        """
        Packed shuffle doublewords.

        Copies doublewords from source operand (second operand) and inserts them in the destination operand
        (first operand) at locations selected with the order operand (third operand).

        :param cpu: current CPU.
        :param op0: destination operand.
        :param op1: source operand.
        :param op3: order operand.
         """
        size = op0.size
        arg0 = op0.read()
        arg1 = op1.read()
        order = Operators.ZEXTEND(op3.read(), size)

        arg0 = arg0 & 0xffffffffffffffffffffffffffffffff00000000000000000000000000000000
        arg0 |= ((arg1 >> (((order >> 0) & 3) * 32)) & 0xffffffff)
        arg0 |= ((arg1 >> (((order >> 2) & 3) * 32)) & 0xffffffff) << 32
        arg0 |= ((arg1 >> (((order >> 4) & 3) * 32)) & 0xffffffff) << 64
        arg0 |= ((arg1 >> (((order >> 6) & 3) * 32)) & 0xffffffff) << 96

        op0.write(arg0)


Instruction:
Make a summary of the following Python 3 code
def PMOVMSKB(cpu, op0, op1):
        arg0 = op0.read()
        arg1 = op1.read()

        res = 0
        for i in reversed(range(7, op1.size, 8)):
            res = (res << 1) | ((arg1 >> i) & 1)
        op0.write(Operators.EXTRACT(res, 0, op0.size))

Response: Moves byte mask to general - purpose register.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def PSRLDQ(cpu, dest, src):
        # TODO(yan): Verify the correctness of truncating SRC like this ( tests
        # use '-1' as the value
        temp = Operators.EXTRACT(src.read(), 0, 8)
        temp = Operators.ITEBV(src.size, temp > 15, 16, temp)
        dest.write(dest.read() >> (temp * 8))

Response: Packs the destination and source memory registers right by the number of bytes specified in the count operand.


Instruction:
How would you code a function in Python 3 to
move with zero - extend.

Response:
def MOVZX(cpu, op0, op1):
        """
        Moves with zero-extend.

        Copies the contents of the source operand (register or memory location) to the destination
        operand (register) and zero extends the value to 16 or 32 bits. The size of the converted value
        depends on the operand-size attribute::

                OP0  =  ZeroExtend(OP1);

        :param cpu: current CPU.
        :param op0: destination operand.
        :param op1: source operand.
        """
        op0.write(Operators.ZEXTEND(op1.read(), op0.size))


Instruction:
Make a summary of the following Python 3 code
def MOVSX(cpu, op0, op1):
        op0.write(Operators.SEXTEND(op1.read(), op1.size, op0.size))

Response: Moving with sign - extension.


Instruction:
Make a summary of the following Python 3 code
def CQO(cpu):
        res = Operators.SEXTEND(cpu.RAX, 64, 128)
        cpu.RAX = Operators.EXTRACT(res, 0, 64)
        cpu.RDX = Operators.EXTRACT(res, 64, 64)

Response: CQO - set the RAX and RDX bits of the current CPU.


Instruction:
Implement a Python 3 function for
setting CPU. EAX to sign - extend of EAX

Response:
def CDQ(cpu):
        """
        EDX:EAX = sign-extend of EAX
        """
        cpu.EDX = Operators.EXTRACT(Operators.SEXTEND(cpu.EAX, 32, 64), 32, 32)


Instruction:
Create a Python 3 function for
converting word to doubleword.

Response:
def CWDE(cpu):
        """
        Converts word to doubleword.

        ::
            DX = sign-extend of AX.

        :param cpu: current CPU.
        """
        bit = Operators.EXTRACT(cpu.AX, 15, 1)
        cpu.EAX = Operators.SEXTEND(cpu.AX, 16, 32)
        cpu.EDX = Operators.SEXTEND(bit, 1, 32)


Instruction:
Implement a function in Python 3 to
read the current value of the time - stamp counter into the RAX and RAX registers.

Response:
def RDTSC(cpu):
        """
        Reads time-stamp counter.

        Loads the current value of the processor's time-stamp counter into the
        EDX:EAX registers.  The time-stamp counter is contained in a 64-bit
        MSR. The high-order 32 bits of the MSR are loaded into the EDX
        register, and the low-order 32 bits are loaded into the EAX register.
        The processor increments the time-stamp counter MSR every clock cycle
        and resets it to 0 whenever the processor is reset.

        :param cpu: current CPU.
        """
        val = cpu.icount
        cpu.RAX = val & 0xffffffff
        cpu.RDX = (val >> 32) & 0xffffffff


Instruction:
Can you tell what is the following Python 3 function doing
def SYSCALL(cpu):
        cpu.RCX = cpu.RIP
        cpu.R11 = cpu.RFLAGS
        raise Syscall()

Response:
This function is used to generate the call to interrupt or exception handler specified
       .


Instruction:
Can you tell what is the following Python 3 function doing
def MOVLPD(cpu, dest, src):
        value = src.read()
        if src.size == 64 and dest.size == 128:
            value = (dest.read() & 0xffffffffffffffff0000000000000000) | Operators.ZEXTEND(value, 128)
        dest.write(value)

Response: This instruction moves a double - precision floating - point value from one CPU to another.


Instruction:
Implement a function in Python 3 to
move high packed double-precision floating-point value. Moves a double-precision floating-point value from the source operand (second operand) and the destination operand (first operand). The source and destination operands can be an XMM register or a 64-bit memory location. This instruction allows double-precision floating-point values to be moved to and from the high quadword of an XMM register and memory. It cannot be used for register to register or memory to memory moves. When the destination operand is an XMM register, the low quadword of the register remains unchanged. :param cpu: current CPU. :param dest: destination operand. :param src: source operand.

Response:
def MOVHPD(cpu, dest, src):
        """
        Moves high packed double-precision floating-point value.

        Moves a double-precision floating-point value from the source operand (second operand) and the
        destination operand (first operand). The source and destination operands can be an XMM register
        or a 64-bit memory location. This instruction allows double-precision floating-point values to be moved
        to and from the high quadword of an XMM register and memory. It cannot be used for register to
        register or memory to memory moves. When the destination operand is an XMM register, the low quadword
        of the register remains unchanged.

        :param cpu: current CPU.
        :param dest: destination operand.
        :param src: source operand.
        """
        if src.size == 128:
            assert dest.size == 64
            dest.write(Operators.EXTRACT(src.read(), 64, 64))
        else:
            assert src.size == 64 and dest.size == 128
            value = Operators.EXTRACT(dest.read(), 0, 64)  # low part
            dest.write(Operators.CONCAT(128, src.read(), value))


Instruction:
Create a Python 3 function to
pack subtract. Performs a SIMD subtract of the packed integers of the source operand (second operand) from the packed integers of the destination operand (first operand), and stores the packed integer results in the destination operand. The source operand can be an MMX(TM) technology register or a 64-bit memory location, or it can be an XMM register or a 128-bit memory location. The destination operand can be an MMX or an XMM register. The PSUBB instruction subtracts packed byte integers. When an individual result is too large or too small to be represented in a byte, the result is wrapped around and the low 8 bits are written to the destination element. :param cpu: current CPU. :param dest: destination operand. :param src: source operand.

Response:
def PSUBB(cpu, dest, src):
        """
        Packed subtract.

        Performs a SIMD subtract of the packed integers of the source operand (second operand) from the packed
        integers of the destination operand (first operand), and stores the packed integer results in the
        destination operand. The source operand can be an MMX(TM) technology register or a 64-bit memory location,
        or it can be an XMM register or a 128-bit memory location. The destination operand can be an MMX or an XMM
        register.
        The PSUBB instruction subtracts packed byte integers. When an individual result is too large or too small
        to be represented in a byte, the result is wrapped around and the low 8 bits are written to the
        destination element.

        :param cpu: current CPU.
        :param dest: destination operand.
        :param src: source operand.
        """
        result = []
        value_a = dest.read()
        value_b = src.read()
        for i in reversed(range(0, dest.size, 8)):
            a = Operators.EXTRACT(value_a, i, 8)
            b = Operators.EXTRACT(value_b, i, 8)
            result.append((a - b) & 0xff)
        dest.write(Operators.CONCAT(8 * len(result), *result))


Instruction:
Here you have a function in Python 3, explain what it does
def POR(cpu, dest, src):
        res = dest.write(dest.read() | src.read())

Response: Performs a bitwise OR operation on the source and destination memory locations.


Instruction:
Can you implement a function in Python 3 that
performs a bitwise OR operation on the source and destination memory locations.

Response:
def XORPS(cpu, dest, src):
        """
        Performs a bitwise logical OR operation on the source operand (second operand) and the destination operand
        (first operand) and stores the result in the destination operand. The source operand can be an MMX technology
        register or a 64-bit memory location or it can be an XMM register or a 128-bit memory location. The destination
        operand can be an MMX technology register or an XMM register. Each bit of the result is set to 1 if either
        or both of the corresponding bits of the first and second operands are 1; otherwise, it is set to 0.
        """
        res = dest.write(dest.read() ^ src.read())


Instruction:
Can you tell what is the following Python 3 function doing
def VORPD(cpu, dest, src, src2):
        res = dest.write(src.read() | src2.read())

Response: A logical OR operation on the source and destination memory locations.


Instruction:
Make a summary of the following Python 3 code
def VORPS(cpu, dest, src, src2):
        res = dest.write(src.read() | src2.read())

Response: Performs a bitwise OR operation on the source and second source operands and stores the result in the destination operand.


Instruction:
Can you tell what is the following Python 3 function doing
def MOVQ(cpu, dest, src):
        # mmx to mmx or mmx to mem
        if dest.size == src.size and dest.size == 64:
            dest.write(src.read())
        # two xmm regs
        elif dest.size == src.size and dest.size == 128:
            src_lo = Operators.EXTRACT(src.read(), 0, 64)
            dest.write(Operators.ZEXTEND(src_lo, 128))
        # mem to xmm
        elif dest.size == 128 and src.size == 64:
            dest.write(Operators.ZEXTEND(src.read(), dest.size))
        # xmm to mem
        elif dest.size == 64 and src.size == 128:
            dest.write(Operators.EXTRACT(src.read(), 0, dest.size))
        else:
            msg = 'Invalid size in MOVQ'
            logger.error(msg)
            raise Exception(msg)

Response: This function moves a quadword from one memory location to another.


Instruction:
Make a summary of the following Python 3 code
def MOVSD(cpu, dest, src):
        assert dest.type != 'memory' or src.type != 'memory'
        value = Operators.EXTRACT(src.read(), 0, 64)
        if dest.size > src.size:
            value = Operators.ZEXTEND(value, dest.size)
        dest.write(value)

Response: Move Scalar Double - Precision Floating - Point Value


Instruction:
Can you generate the documentation for the following Python 3 function
def MOVSS(cpu, dest, src):
        if dest.type == 'register' and src.type == 'register':
            assert dest.size == 128 and src.size == 128
            dest.write(dest.read() & ~0xffffffff | src.read() & 0xffffffff)
        elif dest.type == 'memory':
            assert src.type == 'register'
            dest.write(Operators.EXTRACT(src.read(), 0, dest.size))
        else:
            assert src.type == 'memory' and dest.type == 'register'
            assert src.size == 32 and dest.size == 128
            dest.write(Operators.ZEXTEND(src.read(), 128))

Response: This function moves a scalar single - precision floating - point value from one memory location to another.


Instruction:
Write a Python 3 script to
extract Packed Floating - Point Values from the source and write them to the destination.

Response:
def VEXTRACTF128(cpu, dest, src, offset):
        """Extract Packed Floating-Point Values

        Extracts 128-bits of packed floating-point values from the source
        operand (second operand) at an 128-bit offset from imm8[0] into the
        destination operand (first operand). The destination may be either an
        XMM register or an 128-bit memory location.
        """
        offset = offset.read()
        dest.write(Operators.EXTRACT(src.read(), offset * 128, (offset + 1) * 128))


Instruction:
Implement a function in Python 3 to
pack Shift Left Logical Double Quadword

Response:
def PSLLDQ(cpu, dest, src):
        """ Packed Shift Left Logical Double Quadword
        Shifts the destination operand (first operand) to the left by the number
         of bytes specified in the count operand (second operand). The empty low-order
         bytes are cleared (set to all 0s). If the value specified by the count
         operand is greater than 15, the destination operand is set to all 0s.
         The destination operand is an XMM register. The count operand is an 8-bit
         immediate.

            TEMP  =  COUNT;
            if (TEMP > 15) TEMP  =  16;
            DEST  =  DEST << (TEMP * 8);
        """
        count = Operators.ZEXTEND(src.read(), dest.size * 2)
        byte_count = Operators.ITEBV(src.size * 2, count > 15, 16, count)
        bit_count = byte_count * 8
        val = Operators.ZEXTEND(dest.read(), dest.size * 2)
        val = val << (Operators.ZEXTEND(bit_count, dest.size * 2))
        dest.write(Operators.EXTRACT(val, 0, dest.size))


Instruction:
Here you have a function in Python 3, explain what it does
def PSRLQ(cpu, dest, src):

        count = src.read()
        count = Operators.ITEBV(src.size, Operators.UGT(count, 63), 64, count)
        count = Operators.EXTRACT(count, 0, 64)
        if dest.size == 64:
            dest.write(dest.read() >> count)
        else:
            hi = Operators.EXTRACT(dest.read(), 64, 64) >> count
            low = Operators.EXTRACT(dest.read(), 0, 64) >> count
            dest.write(Operators.CONCAT(128, hi, low))

Response:
Shift Packed Data Right Logical
            - > destination


Instruction:
Can you tell what is the following Python 3 function doing
def VPSHUFB(cpu, op0, op1, op3):
        size = op0.size
        arg0 = op0.read()
        arg1 = op1.read()
        arg3 = Operators.ZEXTEND(op3.read(), size)

        arg0 |= Operators.ITEBV(size, Operators.EXTRACT(arg3, 7, 1) == 1, 0, (arg1 >> ((arg3 >> 0) & 7 * 8)) & 0xff)
        arg0 |= Operators.ITEBV(size, Operators.EXTRACT(arg3, 15, 1) == 1, 0, ((arg1 >> ((arg3 >> 8) & 7 * 8)) & 0xff) << 8)
        arg0 |= Operators.ITEBV(size, Operators.EXTRACT(arg3, 23, 1) == 1, 0, ((arg1 >> ((arg3 >> 16) & 7 * 8)) & 0xff) << 16)
        arg0 |= Operators.ITEBV(size, Operators.EXTRACT(arg3, 31, 1) == 1, 0, ((arg1 >> ((arg3 >> 24) & 7 * 8)) & 0xff) << 24)
        arg0 |= Operators.ITEBV(size, Operators.EXTRACT(arg3, 39, 1) == 1, 0, ((arg1 >> ((arg3 >> 32) & 7 * 8)) & 0xff) << 32)
        arg0 |= Operators.ITEBV(size, Operators.EXTRACT(arg3, 47, 1) == 1, 0, ((arg1 >> ((arg3 >> 40) & 7 * 8)) & 0xff) << 40)
        arg0 |= Operators.ITEBV(size, Operators.EXTRACT(arg3, 55, 1) == 1, 0, ((arg1 >> ((arg3 >> 48) & 7 * 8)) & 0xff) << 48)
        arg0 |= Operators.ITEBV(size, Operators.EXTRACT(arg3, 63, 1) == 1, 0, ((arg1 >> ((arg3 >> 56) & 7 * 8)) & 0xff) << 56)
        arg0 |= Operators.ITEBV(size, Operators.EXTRACT(arg3, 71, 1) == 1, 0, ((arg1 >> ((arg3 >> 64) & 7 * 8)) & 0xff) << 64)
        arg0 |= Operators.ITEBV(size, Operators.EXTRACT(arg3, 79, 1) == 1, 0, ((arg1 >> ((arg3 >> 72) & 7 * 8)) & 0xff) << 72)
        arg0 |= Operators.ITEBV(size, Operators.EXTRACT(arg3, 87, 1) == 1, 0, ((arg1 >> ((arg3 >> 80) & 7 * 8)) & 0xff) << 80)
        arg0 |= Operators.ITEBV(size, Operators.EXTRACT(arg3, 95, 1) == 1, 0, ((arg1 >> ((arg3 >> 88) & 7 * 8)) & 0xff) << 88)
        arg0 |= Operators.ITEBV(size, Operators.EXTRACT(arg3, 103, 1) == 1, 0, ((arg1 >> ((arg3 >> 96) & 7 * 8)) & 0xff) << 96)
        arg0 |= Operators.ITEBV(size, Operators.EXTRACT(arg3, 111, 1) == 1, 0, ((arg1 >> ((arg3 >> 104) & 7 * 8)) & 0xff) << 104)
        arg0 |= Operators.ITEBV(size, Operators.EXTRACT(arg3, 119, 1) == 1, 0, ((arg1 >> ((arg3 >> 112) & 7 * 8)) & 0xff) << 112)
        arg0 |= Operators.ITEBV(size, Operators.EXTRACT(arg3, 127, 1) == 1, 0, ((arg1 >> ((arg3 >> 120) & 7 * 8)) & 0xff) << 120)
        op0.write(arg0)

Response:
Packed shuffle bytes.

        Copies bytes from source operand (second operand) and inserts them in the destination operand
        (first operand) at locations selected with the order operand (third operand).

        :param cpu: current CPU.
        :param op0: destination operand.
        :param op1: source operand.
        :param op3: order operand.


Instruction:
Given the following Python 3 function, write the documentation
def XLATB(cpu):
        cpu.AL = cpu.read_int(cpu.RBX + Operators.ZEXTEND(cpu.AL, 64), 8)

Response: A table look - up translation.


Instruction:
Create a Python 3 function for
tabling look-up translation. Locates a byte entry in a table in memory, using the contents of the AL register as a table index, then copies the contents of the table entry back into the AL register. The index in the AL register is treated as an unsigned integer. The XLAT and XLATB instructions get the base address of the table in memory from either the DS:EBX or the DS:BX registers. In 64-bit mode, operation is similar to that in legacy or compatibility mode. AL is used to specify the table index (the operand size is fixed at 8 bits). RBX, however, is used to specify the table's base address:: IF address_bit_size = 16 THEN AL = (DS:BX + ZeroExtend(AL)); ELSE IF (address_bit_size = 32) AL = (DS:EBX + ZeroExtend(AL)); FI; ELSE (address_bit_size = 64) AL = (RBX + ZeroExtend(AL)); FI; :param cpu: current CPU. :param dest: destination operand.

Response:
def XLATB(cpu):
        """
        Table look-up translation.

        Locates a byte entry in a table in memory, using the contents of the
        AL register as a table index, then copies the contents of the table entry
        back into the AL register. The index in the AL register is treated as
        an unsigned integer. The XLAT and XLATB instructions get the base address
        of the table in memory from either the DS:EBX or the DS:BX registers.
        In 64-bit mode, operation is similar to that in legacy or compatibility mode.
        AL is used to specify the table index (the operand size is fixed at 8 bits).
        RBX, however, is used to specify the table's base address::

                IF address_bit_size = 16
                THEN
                    AL = (DS:BX + ZeroExtend(AL));
                ELSE IF (address_bit_size = 32)
                    AL = (DS:EBX + ZeroExtend(AL)); FI;
                ELSE (address_bit_size = 64)
                    AL = (RBX + ZeroExtend(AL));
                FI;

        :param cpu: current CPU.
        :param dest: destination operand.
        """
        cpu.AL = cpu.read_int(cpu.EBX + Operators.ZEXTEND(cpu.AL, 32), 8)


Instruction:
Can you generate the documentation for the following Python 3 function
def constrain(self, constraint):
        constraint = self.migrate_expression(constraint)
        self._constraints.add(constraint)

Response: Add a constraint to the set of constraints.


Instruction:
Can you tell what is the following Python 3 function doing
def new_symbolic_buffer(self, nbytes, **options):
        label = options.get('label')
        avoid_collisions = False
        if label is None:
            label = 'buffer'
            avoid_collisions = True
        taint = options.get('taint', frozenset())
        expr = self._constraints.new_array(name=label, index_max=nbytes, value_bits=8, taint=taint, avoid_collisions=avoid_collisions)
        self._input_symbols.append(expr)

        if options.get('cstring', False):
            for i in range(nbytes - 1):
                self._constraints.add(expr[i] != 0)

        return expr

Response: Create and return a symbolic buffer of length nbytes.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def new_symbolic_value(self, nbits, label=None, taint=frozenset()):
        assert nbits in (1, 4, 8, 16, 32, 64, 128, 256)
        avoid_collisions = False
        if label is None:
            label = 'val'
            avoid_collisions = True

        expr = self._constraints.new_bitvec(nbits, name=label, taint=taint, avoid_collisions=avoid_collisions)
        self._input_symbols.append(expr)
        return expr

Response: Create and return a symbolic value that is nbits bits wide.