'On the fly assemble and execute instructions using NASM
Usage:
MYNAME [mode] [address]
mode: -b16 / -b32 / -b64'

def assemble(self, *arg):

    (mode, address) = normalize_argv(arg, 2)
    exec_mode = 0
    write_mode = 0
    if (to_int(mode) is not None):
        (address, mode) = (mode, None)
    (arch, bits) = peda.getarch()
    if (mode is None):
        mode = bits
    else:
        mode = to_int(mode[2:])
        if (mode not in [16, 32, 64]):
            self._missing_argument()
    if (self._is_running() and (address == peda.getreg('pc'))):
        write_mode = exec_mode = 1
    line = peda.execute_redirect('show    write')
    if (line and ('on' in line.split()[(-1)])):
        write_mode = 1
    if ((address is None) or (mode != bits)):
        write_mode = exec_mode = 0
    if write_mode:
        msg(('Instruction    will    be    written    to    0x%x' % address))
    else:
        msg('Instructions    will    be    written    to    stdout')
    msg('Type    instructions    (NASM    syntax),    one    or    more    per    line    separated    by    ";"')
    msg('End    with    a    line    saying    just    "end"')
    if (not write_mode):
        address = 3735928559
    inst_list = []
    inst_code = ''
    while True:
        inst = input(('iasm|0x%x>    ' % address))
        if (inst == 'end'):
            break
        if (inst == ''):
            continue
        bincode = peda.assemble(inst, mode)
        size = len(bincode)
        if (size == 0):
            continue
        inst_list.append((size, bincode, inst))
        if write_mode:
            peda.writemem(address, bincode)
        if exec_mode:
            peda.execute(('stepi    %d' % (inst.count(';') + 1)))
        address += size
        inst_code += bincode
        msg(('hexify:    "%s"' % to_hexstr(bincode)))
    text = Nasm.format_shellcode(''.join([x[1] for x in inst_list]), mode)
    if text:
        msg(('Assembled%s    instructions:' % ('/Executed' if exec_mode else '')))
        msg(text)
        msg(('hexify:    "%s"' % to_hexstr(inst_code)))
    return
