import subprocess
import pwnypack.target
import tempfile
import os
from enum import Enum


__all__ = [
    'asm',
]


class Asm(object):
    class Format(Enum):
        bin = 'bin'
        ith = 'ith'
        srec = 'srec'
        aout = 'aout'
        aoutb = 'aoutb'
        coff = 'coff'
        elf32 = 'elf32'
        elf64 = 'elf64'
        elfx32 = 'elfx32'
        as86 = 'as86'
        obj = 'obj'
        win32 = 'win32'
        win64 = 'win64'
        rdf = 'rdf'
        ieee = 'ieee'
        macho32 = 'macho32'
        macho64 = 'macho64'
        dbg = 'dbg'

    @classmethod
    def __call__(cls, code, fmt=Format.bin, bits=None, target=None):
        if not isinstance(fmt, cls.Format):
            fmt = cls.Format(fmt)

        if bits is None:
            if target is None:
                target = pwnypack.target.target
            bits = target.bits

        tmp = tempfile.NamedTemporaryFile(delete=False)
        tmp.write(('bits %d\n%s' % (bits, code)).encode('utf-8'))
        tmp.close()

        try:
            p = subprocess.Popen(
                [
                    'nasm',
                    '-o',
                    '/dev/stdout',
                    '-f',
                    fmt.value,
                    tmp.name,
                ],
                stdin=subprocess.PIPE,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
            )
            stdout, stderr = p.communicate()
            if p.returncode:
                raise SyntaxError(stderr.decode('utf-8'))
            return stdout
        finally:
            os.unlink(tmp.name)

asm = Asm()

@@ -34,16 +34,37 @@
 .target%0A
+import pwnypack.main%0A
 import t
@@ -1645,8 +1645,938 @@
 = Asm()%0A
+%0A%0A@pwnypack.main.register('asm')%0Adef asm_app(parser, cmd, args):%0A    %22%22%22%0A    Assemble code from commandline or stdin.%0A    %22%22%22%0A%0A    parser.add_argument('source', help='the code to assemble, read from stdin if omitted', nargs='?')%0A    parser.add_argument(%0A        '--target', '-t',%0A        choices=%5B'x86', 'x86_64'%5D,%0A        default=pwnypack.target.target.arch.name,%0A        help='the target architecture',%0A    )%0A    parser.add_argument(%0A        '--output-format', '-F',%0A        choices=asm.Format.__members__.keys(),%0A        default=asm.Format.bin.name,%0A        help='the output format',%0A    )%0A    args = parser.parse_args(args)%0A%0A    target = pwnypack.target.Target(arch=pwnypack.target.Architecture.__members__%5Bargs.target%5D)%0A    fmt = asm.Format(asm.Format.__members__%5Bargs.output_format%5D)%0A%0A    return asm(%0A        pwnypack.main.string_value_or_stdin(args.source).replace(';', '%5Cn'),%0A        fmt=fmt,%0A        target=target,%0A    )%0A

Add asm commandline app.