Ejemplo n.º 1
0
def run():
    programs = [
        # These are sorted from roughly easiest first to most difficult.
        ["add", ["data", 1], ["data", 2]],
        ["add", ["data", [1, 2]], ["data", [3, 4]]],
        ["double", ["data", 13]],
        ["square", ["add", ["data", 3], ["data", 4]]],
        ["double", ["double", ["data", 5]]],
        ["tag", ["data", "td"], ["data", "hello world"]],
        ["range", ["data", 5], ["add", ["data", 5], ["data", 10]]],
        ["list", ["data", 5], ["data", 7], ["add", ["data", 8], ["data", 1]]],
        ["len", ["data", [0, 1, 2, 3, 4]]],
        ["deref", ["data", 2], ["data", ["apple", "banana", "carrot", "dog"]]],
        ["deref", ["data", "x"], ["data", {
            "x": 5,
            "y": 7
        }]],
        ["is_zero", ["data", 5]],
        ["is_zero", ["add", ["data", 3], ["data", -3]]],
        ["incr", ["data", 10]],
        ["decr", ["data", 10]],
        ["if", ["data", 1], ["data", "if-case"], ["data", "else-case"]],
        [
            "if", ["eq", ["data", "x"], ["data", "y"]], ["data", "if-case"],
            ["data", "else-case"]
        ],
        ["factorial", ["data", 5]],
        ["math_row", ["data", 7]],
        ["td", ["data", "hello"]],
        ["concat", ["data", ["a", "b", "c"]]],
        ["tr", ["list", ["td", ["data", "a"]], ["data", "<td>b</td>"]]],
        ["map", ["data", [1, 2, 3]], ["data", "double"]],
        ["math_tr", ["data", 7]],
        ["math_table_guts", ["range", ["data", 5], ["data", 12]]],
        ["table", ["data", "header_row"], ["data", ["foo", "bar"]]],
    ]

    for program in programs:
        vm = VirtualMachine(BOTS)

        def callback(answer):
            print '%s ->\n    %s\n' % (program, str(answer))

        vm.process_program(callback, program)

    def write_html(answer):
        open('foo.html', 'w').write(answer)

    vm = VirtualMachine(BOTS)
    vm.process_program(write_html,
                       ["math_table", ["range", ["data", 5], ["data", 15]]])
Ejemplo n.º 2
0
def part_two(data):
    to_check = []
    master = data
    for i, instruction in enumerate(data):
        if instruction[0] == VirtualMachine.OP_JUMP or instruction[
                0] == VirtualMachine.NOP:
            to_check.append(i)
    for i in to_check:
        data = master.copy()
        instruction = data[i][0]
        data[i] = (VirtualMachine.OP_JUMP if instruction == VirtualMachine.NOP
                   else VirtualMachine.NOP, data[i][1])
        vm = VirtualMachine(data)
        result = vm.run()
        if result != VirtualMachine.INFINITE_LOOP:
            return result
Ejemplo n.º 3
0
def gen_bytecode():
    '''
    Positions of different strings:

    heap_start:        8191
    first_bytes:       10239
    middle_bytes_hash: 10339
    last_bytes_hash:   10439
    enflag:            10539
    error_msg:         10639
    hardcoded:         10739
    enter_string:      10839
    memory_end:        24575
    '''

    code = ''
    with open('asm_code', 'r') as asmfile:
        code = asmfile.read()

    vm = VirtualMachine(bytearray(b''))
    inter = Interpreter({v.__name__: k for k, v in vm.opcode.items()})
    bytecode = inter.translate(code.split('\n'))

    return bytecode
Ejemplo n.º 4
0
from flask import Flask
from flask import render_template
from flask import redirect
from flask import request
from vm import VirtualMachine

app = Flask(__name__)
vmachine = VirtualMachine(1)


@app.route("/")
def index():
    return render_template("index.html", vmachine=vmachine)


@app.route("/change_status/<new_status>")
def change_status(new_status):
    if new_status == "0":
        vmachine.stop()
    elif new_status == "1":
        vmachine.start()
    elif new_status == "2":
        vmachine.suspend()
    return redirect("/")


@app.route("/run_process", methods=["GET", "POST"])
def run_process():
    if request.method == "POST":
        pid = int(request.form["pid"])
        ram = float(request.form["ram"])
Ejemplo n.º 5
0
from flask import Flask
from flask import render_template
from flask import redirect
from flask import request
from vm import VirtualMachine

app = Flask(__name__)
vmachine = VirtualMachine("Azkaban", 16, 3.7, 1000, "Debian")


@app.route("/")
def index():
    return render_template("index.html", vmachine=vmachine)


@app.route("/change_status/<new_status>")
def change_status(new_status):
    if new_status == "0":
        vmachine.stop()
    elif new_status == "1":
        vmachine.start()
    elif new_status == "2":
        vmachine.suspend()
    else:
        print("""
            Elija una opción correcta por favor:
            0 = Parar la máquina.
            1 = Iniciarla.
            2 = Suspenderla.
            """)
    return redirect("/")
Ejemplo n.º 6
0
#!/usr/bin/env python3

from vm import VirtualMachine

c = VirtualMachine()
c.load_program("add_255_3.vef")
print(c.memory_offset)
print(c.memory)
c.load_program("sub_256_3.vef")
print(c.memory_offset)
print(c.memory)
c.run()

# assert c.output()[0] == 0x22

Ejemplo n.º 7
0
from screen import SCREEN_SIZE, SCREEN_TOTAL_SIZE
from vm import VirtualMachine

import pygame
import sys
import os

if __name__ == "__main__":
    PATH = os.path.dirname(__file__)
    # get the code
    filename = os.path.join(PATH, sys.argv[1])
    with open(filename, "rb") as document:
        raw_code = document.read()
    # initialise the window
    display = pygame.display.set_mode(SCREEN_TOTAL_SIZE)
    # setup the vm
    vm = VirtualMachine(
        screen_size=SCREEN_SIZE,
        screen_surface=display,  # screen
        instruction_set=InstructionSet,
        register_set=RegisterSet(),  # cpu
        key_map=KEY_MAP  # keyboard
    )
    vm.load(raw_code)
    # pygame event loop
    running = True
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
        next(vm)
Ejemplo n.º 8
0
                arg = parse(machine.read_address(addr + 1 + i))
                args.append(arg)

            if op == 'jmp':
                forks.append(int(args[1]))
            if op in ['jt', 'jf']:
                forks.append(int(args[2]))
            elif op == 'out' and args[1][0] != 'R':
                args.append(chr(int(args[1])))
            memo[addr] = ' '.join(args)

            if op == 'ret':
                break
            addr += 1 + n_args
        else:
            addr += 1
    for fork in forks:
        trace(machine, fork, memo)
    return memo


if __name__ == '__main__':
    addr = int(sys.argv[1])
    machine = VirtualMachine('input/challenge.bin')
    machine.load_state('teleporter')

    output = trace(machine, addr)

    for key in sorted(output.keys()):
        print "{}: {}".format(key, output[key])
Ejemplo n.º 9
0
def part_one(data):
    vm = VirtualMachine(data)
    return vm.run()