예제 #1
0
def test_dataop():
    return
    with open("simulatorTests/dataop.asm") as f:
        bytecode, bcinfos, assertInfos, errors = ASMparser(f)

    interpreter = BCInterpreter(bytecode, bcinfos, assertInfos)
    runt(interpreter)
예제 #2
0
def process(ws, msg_in):
    """
    Output: List of messages to send.
    """
    force_update_all = False
    retval = []
    if ws in interpreters and not hasattr(interpreters[ws], 'history__'):
        interpreters[ws].history__ = []

    try:
        for msg in msg_in:
            data = json.loads(msg)

            if ws in interpreters:
                interpreters[ws].history__.append(data)

            if data[0] != 'assemble' and ws not in interpreters:
                if data[0] != "interrupt":
                    retval.append([
                        "error",
                        "Veuillez assembler le code avant d'effectuer cette opération."
                    ])
            elif data[0] == 'assemble':
                code = ''.join(s for s in data[1].replace("\t", " ")
                               if s in string.printable)
                if ws in interpreters:
                    del interpreters[ws]

                bytecode, bcinfos, line2addr, assertions, errors = ASMparser(
                    code.splitlines())
                if errors:
                    retval.extend(errors)
                    retval.append(["edit_mode"])
                else:
                    interpreters[ws] = BCInterpreter(bytecode, bcinfos,
                                                     assertions)
                    force_update_all = True
                    interpreters[ws].code__ = copy(code)
                    interpreters[ws].last_step__ = time.time()
                    interpreters[ws].next_report__ = 0
                    interpreters[ws].animate_speed__ = 0.1
                    interpreters[ws].num_exec__ = 0
                    interpreters[ws].user_asked_stop__ = False
                    retval.append(["line2addr", line2addr])
            elif data[0] == 'stepback':
                interpreters[ws].stepBack()
                force_update_all = True
            elif data[0] == 'stepinto':
                interpreters[ws].step('into')
            elif data[0] == 'stepforward':
                interpreters[ws].step('forward')
                interpreters[ws].user_asked_stop__ = False
                interpreters[ws].last_step__ = time.time()
                try:
                    interpreters[ws].animate_speed__ = int(data[1]) / 1000
                except (ValueError, TypeError):
                    interpreters[ws].animate_speed__ = 0
                    retval.append([
                        "animate_speed",
                        str(interpreters[ws].animate_speed__)
                    ])
            elif data[0] == 'stepout':
                interpreters[ws].step('out')
                interpreters[ws].user_asked_stop__ = False
                interpreters[ws].last_step__ = time.time()
                try:
                    interpreters[ws].animate_speed__ = int(data[1]) / 1000
                except (ValueError, TypeError):
                    interpreters[ws].animate_speed__ = 0
                    retval.append([
                        "animate_speed",
                        str(interpreters[ws].animate_speed__)
                    ])
            elif data[0] == 'run':
                if interpreters[ws].shouldStop == False and (
                        interpreters[ws].user_asked_stop__ == False):
                    interpreters[ws].user_asked_stop__ = True
                else:
                    interpreters[ws].user_asked_stop__ = False
                    interpreters[ws].step('run')
                    interpreters[ws].last_step__ = time.time()
                    try:
                        anim_speed = int(data[1]) / 1000
                    except (ValueError, TypeError):
                        anim_speed = 0
                        retval.append(["animate_speed", str(anim_speed)])
                    interpreters[ws].animate_speed__ = anim_speed
            elif data[0] == 'stop':
                del interpreters[ws]
            elif data[0] == 'reset':
                interpreters[ws].reset()
            elif data[0] == 'breakpointsinstr':
                interpreters[ws].setBreakpointInstr(data[1])
            elif data[0] == 'breakpointsmem':
                try:
                    interpreters[ws].toggleBreakpointMem(
                        int(data[1], 16), data[2])
                except ValueError:
                    retval.append(["error", "Adresse mémoire invalide"])
                else:
                    bpm = interpreters[ws].getBreakpointsMem()
                    retval.extend(
                        [["membp_r", ["0x{:08x}".format(x) for x in bpm['r']]],
                         ["membp_w", ["0x{:08x}".format(x) for x in bpm['w']]],
                         [
                             "membp_rw",
                             ["0x{:08x}".format(x) for x in bpm['rw']]
                         ],
                         ["membp_e",
                          ["0x{:08x}".format(x) for x in bpm['e']]]])
            elif data[0] == 'update':
                if data[1][0].upper() == 'R':
                    reg_id = int(data[1][1:])
                    try:
                        interpreters[ws].setRegisters(
                            {reg_id: int(data[2], 16)})
                    except (ValueError, TypeError):
                        retval.append([
                            "error",
                            "Valeur invalide: {}".format(repr(data[2]))
                        ])
                elif data[1].upper() in ('N', 'Z', 'C', 'V', 'I', 'F', 'SN',
                                         'SZ', 'SC', 'SV', 'SI', 'SF'):
                    flag_id = data[1].upper()
                    try:
                        val = not interpreters[ws].getFlags()[flag_id]
                    except KeyError:
                        pass
                    else:
                        interpreters[ws].setFlags({flag_id: val})
                elif data[1][:2].upper() == 'BP':
                    _, mode, bank, reg_id = data[1].split('_')
                    try:
                        reg_id = int(reg_id[1:])
                    except (ValueError, TypeError):
                        retval.append([
                            "error",
                            "Registre invalide: {}".format(repr(reg_id[1:]))
                        ])
                    # bank, reg name, mode [r,w,rw]
                    interpreters[ws].setBreakpointRegister(
                        bank.lower(), reg_id, mode)
            elif data[0] == "interrupt":
                mode = ["FIQ", "IRQ"][data[2] == "IRQ"]  # FIQ/IRQ
                try:
                    cycles_premier = int(data[4])
                except (TypeError, ValueError):
                    cycles_premier = 50
                    retval.append(['interrupt_cycles_first', 50])
                try:
                    cycles = int(data[3])
                except (TypeError, ValueError):
                    cycles = 50
                    retval.append(['interrupt_cycles', 50])
                try:
                    notactive = bool(data[1])
                except (TypeError, ValueError):
                    notactive = 0
                    retval.append(['interrupt_active', 0])
                interpreters[ws].setInterrupt(mode, not notactive,
                                              cycles_premier, cycles, 0)
            elif data[0] == 'memchange':
                try:
                    val = bytearray([int(data[2], 16)])
                except (ValueError, TypeError):
                    retval.append(
                        ["error", "Valeur invalide: {}".format(repr(data[2]))])
                    val = interpreters[ws].getMemory(data[1])
                    retval.append(["mempartial", [[data[1], val]]])
                else:
                    interpreters[ws].setMemory(data[1], val)
            else:
                print("<{}> Unknown message: {}".format(ws, data))
    except Exception as e:
        traceback.print_exc()
        retval.append(["error", str(e)])

        if not DEBUG:
            ex = traceback.format_exc()
            print("Handling loop crashed:\n{}".format(ex))
            try:
                code = interpreters[ws].code__
            except (KeyError, AttributeError):
                code = ""
            try:
                hist = interpreters[ws].history__
            except (KeyError, AttributeError):
                hist = []
            try:
                cmd = msg
            except NameError:
                cmd = ""
            body = """<html><head></head>
(Handling loop crash)
<h4>Traceback:</h4>
<pre>{ex}</pre>
<h4>Code:</h4>
<pre>{code}</pre>
<h4>Operation history:</h4>
<pre>{hist}</pre>
<h4>Current command:</h4>
<pre>{cmd}</pre>
</html>""".format(code=code,
                  ex=ex,
                  hist="<br/>".join(str(x) for x in hist),
                  cmd=cmd)
            sendEmail(body)
            print("Email sent!")

    del msg_in[:]

    if ws in interpreters:
        retval.extend(updateDisplay(interpreters[ws], force_update_all))
    return retval
예제 #3
0
        armRef = unicorn.Uc(unicorn.UC_ARCH_ARM, unicorn.UC_MODE_ARM)

        armRef.mem_map(
            CODE_START_ADDR, 1024 *
            (4 + 2 +
             1))  # 4 KB for code, 2 KB for data, 1 KB buffer (just in case)
        contiguousMem = bytearray([0]) * (1024 * (4 + 2))
        contiguousMem[0:len(bytecode['INTVEC'])] = bytecode['INTVEC']
        contiguousMem[0x80:0x80 + len(bytecode['CODE'])] = bytecode['CODE']
        contiguousMem[4096:4096 + len(bytecode['DATA'])] = bytecode['DATA']
        armRef.mem_write(CODE_START_ADDR, bytes(contiguousMem))
        initializeQemu(armRef)

        # Setting up epater simulator
        armEpater = BCInterpreter(bytecode,
                                  bcinfos,
                                  assertInfos,
                                  pcInitAddr=CODE_START_ADDR)
        armEpater.sim.fetchAndDecode()  # Fetch the first instruction

        memLengths = {
            "INTVEC": len(bytecode['INTVEC']),
            "CODE": len(bytecode['CODE']),
            "DATA": len(bytecode['DATA'])
        }
        contextRef = Context("qemu", armRef, memLengths)
        contextEpater = Context("epater", armEpater, memLengths)

        cycle = 0
        errorCount = 0
        pcRef = CODE_START_ADDR
        contextRef.update()
예제 #4
0
파일: main.py 프로젝트: etiennedub/epater
import math

from assembler import parse as ASMparser
from bytecodeinterpreter import BCInterpreter
from procsimulator import Simulator

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='EPATER, ARM emulator')
    parser.add_argument('inputfile', help="Fichier assembleur")
    args = parser.parse_args()

    with open(args.inputfile) as f:
        bytecode, bcinfos, line2addr, assertions, errors = ASMparser(f)
    print("Parsed source code!")
    print(bytecode)

    interpreter = BCInterpreter(bytecode, bcinfos, assertions)
    with open(args.inputfile) as f:
        lines = f.readlines()
        a = time.time()
        for i in range(100000):
            if i < 7:
                print(i, lines[interpreter.getCurrentLine()][:-1])
            interpreter.step()
            b = interpreter.getCurrentLine(), interpreter.getChanges()
            if i < 7:
                print(interpreter.getCurrentLine(), interpreter.getChanges())
                print("################")
        print("...")
    print("Time execute {} instructions : {}".format(i, time.time() - a))
예제 #5
0
def test_shifts():
    with open("simulatorTests/shifttest1.asm") as f:
        bytecode, bcinfos, assertInfos, errors = ASMparser(f)

    interpreter = BCInterpreter(bytecode, bcinfos, assertInfos)
    runt(interpreter)
예제 #6
0
파일: main.py 프로젝트: mgard/epater
import time
import math

from assembler import parse as ASMparser
from bytecodeinterpreter import BCInterpreter
from procsimulator import Simulator

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='EPATER, ARM emulator')
    parser.add_argument('inputfile', help="Fichier assembleur")
    args = parser.parse_args()

    with open(args.inputfile) as f:
        bytecode, bcinfos = ASMparser(f)

    interpreter = BCInterpreter(bytecode, bcinfos)
    print(interpreter.getCurrentLine(), interpreter.getRegisters())
    interpreter.stepforward()
    print(interpreter.getCurrentLine(), interpreter.getRegisters())
    interpreter.stepforward()
    print(interpreter.getCurrentLine(), interpreter.getRegisters())
    interpreter.stepforward()
    print(interpreter.getCurrentLine(), interpreter.getRegisters())
    interpreter.stepforward()
    print(interpreter.getCurrentLine(), interpreter.getRegisters())





예제 #7
0
파일: main.py 프로젝트: phcwj/epater
import math

from assembler import parse as ASMparser
from bytecodeinterpreter import BCInterpreter

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='EPATER, ARM emulator')
    parser.add_argument('inputfile', help="Fichier assembleur")
    args = parser.parse_args()

    with open(args.inputfile) as f:
        bytecode, bcinfos, line2addr, assertions, _, errors = ASMparser(f)
    print("Parsed source code!")

    a = time.time()
    interpreter = BCInterpreter(bytecode, bcinfos, assertions)
    with open(args.inputfile) as f:
        lines = f.readlines()
        interpreter.step(stepMode="forward")
        print("Cycle {}".format(interpreter.getCycleCount()))
        print("Next line to execute : " + lines[interpreter.getCurrentLine()][:-1])
        interpreter.step(stepMode="into")
        print("Cycle {}".format(interpreter.getCycleCount()))
        print("Next line to execute : " + lines[interpreter.getCurrentLine()][:-1])
        interpreter.execute(mode="run")
        print("Cycle {}".format(interpreter.getCycleCount()))
        print("Final registers values:")
        print(interpreter.getRegisters())
    
    deltaTime = time.time() - a
    cycles = interpreter.getCycleCount()