def run(fp): program_contents = "" while True: read = os.read(fp, 4096) if len(read) == 0: break program_contents += read os.close(fp) program = parse(program_contents) i = 0 functions = [None] * 1024 while i < len(program): ops = program[i] opcode = int(ops[0]) if opcode == OpCode.MAKE_FUNCTION: name = int(ops[1]) params = int(ops[2]) func, bytecodes_length = make_function(name, params, program, i + 1) functions[name] = func i += bytecodes_length i += 1 functions = [func for func in functions if func is not None] main_func = functions[0] init_frame = Frame(None, main_func, main_func.num_locals, main_func.literals, main_func.stack_size) vm = VM(functions) vm.run(init_frame)
def test_input(self): ops =[9, 32768, 32769, 4, 19, 32768] # - Store into register 0 the sum of 4 and the value contained in register 1. # - Output to the terminal the character with the ascii code contained in register 0. vm = VM(ops) vm.r[1] = 65 vm.run() self.assertEqual(vm.r[0], vm.r[1] + 4)
class Eval: def __init__(self): self.vm = VM() def eval(self, expr): compiled_expr = compile(expr) print("compiled_expr:", compiled_expr) self.vm.reg.x = compiled_expr self.vm.run() return self.vm.reg.a
def main(): vm = VM() try: opts, args = getopt.getopt( sys.argv[1:], "c:i:o:gh", ["codefile=", "inputfile=", "outputfile=", "debug", "help"] ) except getopt.GetoptError as error: print(error) exit() # Go through the options, initializing and configuring the vm. for opt, arg in opts: if opt in ("-h", "--help"): exit() elif opt in ("-c", "--codefile"): try: codeFile = open(arg, mode="rt", encoding="utf-8") header = codeFile.readline() if not vm.setLoader(header, codeFile): print("The header of the file {} is not recognized:".format(arg)) print(header) sys.exit(2) transferHeader = codeFile.readline() vm.setTransferStage(transferHeader) except IOError as ioe: print(ioe) sys.exit(2) elif opt in ("-i", "--inputfile"): try: vm.input = open(arg, mode="rt", encoding="utf-8") except IOError as ioe: print(ioe) sys.exit(2) elif opt in ("-o", "--outputfile"): try: vm.output = open(arg, mode="wb") except IOError as ioe: print(ioe) sys.exit(2) elif opt in ("-g", "--debug"): vm.setDebugMode() # If a code file isn't supplied, there won't be any loader so we end. if vm.loader is None: exit() vm.run() sys.exit(0)
class Interpreter: def __init__(self): #The VM is the only thing that persists throughout running chunks of code #The lexer and parser are better off refershing line numbers and such when #made to run on a new chunk of code self.vm = VM() def run(self, code): #First we scan for tokens scanner = lexer.Scanner(code.upper()) tokens = scanner.scanTokens() #We use None as a way to return Errors if (tokens == None): print("Lexical error encountered. Not executing") return #Next we parse the tokens we've generated into trees parser = parsing.Parser(tokens) trees = parser.parse() if (trees == None): print("Parsing error encountered. Not executing") return #The next section forms a middle end, that changes the not so assembly code so far #into proper assembly code that the actual transputer would be able to handle #We should check for any prefix errors that may come up and be undetecable #at run time after we expand out illegal operands in the expansion step prefixChanger = prefixChecking.PrefixPreparer(trees) trees = prefixChanger.prepare() if (trees == None): print("Illegal prefix sequence encountered. Not executing") return #Then we use an expander to expand out double length instructions #And operands longer than 4 bits #We also check if there is any overflow when expanding out jumps expander = expanding.Expander(trees) trees = expander.expand() if (trees == None): print("Ran into a problem while correcting Jumps. Not executing") return #After this we're ready to interpret! self.vm.run(trees)
def execute(filename): try: f = open(filename) except: print_msg("open file error\n", abort=True) text = f.read() f.close() token = tokenizer(text) parser = Parser(token) instruction = parser.parse() #print repr(text) #print instruction vm = VM(instruction) vm.run() return text
class TestVM(unittest.TestCase): def setUp(self): self.vm = VM() def test_halt(self): self.vm.reg.a = TString("halt") self.vm.reg.x = Halt() self.vm.run() a = self.vm.reg.a self.assertIsInstance(a, TString) self.assertEqual("halt", a.value) def test_constant(self): self.vm.reg.x = Constant(TString("constant"), Halt()) self.vm.run() a = self.vm.reg.a self.assertIsInstance(a, TString) self.assertEqual("constant", a.value) def test_refer(self): self.vm.reg.e = Env([TSymbol("foo")], [TString("foo_val")], None) self.vm.reg.x = Refer(TSymbol("foo"), Halt()) self.vm.run() a = self.vm.reg.a self.assertIsInstance(a, TString) self.assertEqual("foo_val", a.value) def test_assign(self): self.vm.reg.e = Env(["foo"], [TString("foo_val")], None) self.vm.reg.a = TString("foo_val_2") self.vm.reg.x = Assign("foo", Halt()) self.vm.run() val = self.vm.reg.e.look_up("foo") self.assertIsInstance(val, TString) self.assertEqual("foo_val_2", val.value) def test_closure(self): self.vm.reg.e = Env(["foo"], [TNumber(10)], None) self.vm.reg.x = Closure([TSymbol("a"), TSymbol("b")], None, Halt()) self.vm.run() a = self.vm.reg.a self.assertIsInstance(a, TClosure)
def run(fp, filename): file_contents = "" read = os.read(fp, 4096) while len(read) > 0: file_contents += read read = os.read(fp, 4096) os.close(fp) program = parse(file_contents) if len(program) > 0 and program[0][0] == BYTECODE_HEADER: del program[0] else: raise InvalidBytecodeFileException( "Cannot execute Aver Bytecode file. Please ensure that the file you're trying to run was generated by the compiler", filename) i = 0 functions = [None] * 1024 while i < len(program): ops = program[i] opcode = int(ops[0]) if opcode == OpCode.MAKE_FUNCTION: name = int(ops[1]) params = int(ops[2]) func, bytecodes_length = make_function(name, params, program, i + 1) functions[name] = func i += bytecodes_length i += 1 functions = [func for func in functions if func is not None] main_func = functions[0] init_frame = Frame(None, main_func, main_func.num_locals, main_func.literals, main_func.stack_size) vm = VM(functions) vm.run(init_frame)
def main(): print "---" print "Simple test" print vm = VM(code_test) vm.run() print "---" print "GCD" print vm = VM(code_gcd) vm.greg[0] = 9 vm.greg[1] = 12 vm.run() print "---" print "Concurrent fibonacci" print vm = VM(code_fib_concurrent, 4) vm.greg[0] = 17 vm.run()
file = open('./code.bin', 'rb') data = file.read(0x200) code = file.read() file.close() vm = VM(code, data) # vm.transpile() # vm.run(verbose=True) # vm.run(input=b'n3w_ag3_v1rtu4liz4t1on_', verbose=True) def crc32(input, round_xor, final_xor): state = z3.BitVecVal(0xffffffff, 32) for i in range(0, 32): state = z3.If( state & 1 == z3.LShR(input, i) & 1, z3.LShR(state, 1), z3.LShR(state, 1) ^ round_xor) return state ^ final_xor s = z3.Solver() input = z3.BitVec('input', 32) round_xor = u32(data[0x80:0x84]) final_xor = u32(data[0x88:0x8c]) s.add(crc32(input, round_xor, final_xor) == 0) if s.check() == z3.sat: suffix = int(str(s.model()[input])) vm.run(input=b'n3w_ag3_v1rtu4liz4t1on_' + p32(suffix), silent=False)
#!/usr/bin/python3 from vm import VM from parsing import readProgram, parseInput, parseOutput import sys if __name__ == '__main__': if len(sys.argv) < 2: raise ValueError("You need to specify a program") progName = sys.argv[1] with open(progName, 'r') as f: prog = readProgram(f) progIn = input() vm = VM(istream=parseInput(progIn), dynamicMem=prog.dynamicMem, initMem=prog.initMem) vm.cmd = prog.cmds vm.run() print(parseOutput(vm.ostream))
def run(): bytecode = Bytecode() lexer = MyLexer() parser = MyParser(bytecode) code = ''' var x = 1 - 2 - 3; var y = 1 + 2 + 3 + x; ''' #result = parser.parse(lexer.tokenize(code)) # Initialize the counter bytecode.emit(Instruction.PUSH) bytecode.emit(0) bytecode.emit(Instruction.STORE) bytecode.emit(0) # Initalize the value bytecode.emit(Instruction.PUSH) bytecode.emit(10) bytecode.emit(Instruction.DUP) # Branch if the value is 0 bytecode.emit(Instruction.BRZ) bytecode.emit(12) # Loads the counter bytecode.emit(Instruction.LOAD) bytecode.emit(0) # Adds one to the counter bytecode.emit(Instruction.PUSH) bytecode.emit(1) bytecode.emit(Instruction.ADD) # Stores the counter again bytecode.emit(Instruction.STORE) bytecode.emit(0) # Pushes 2 on the stack bytecode.emit(Instruction.PUSH) bytecode.emit(2) # Subtracts 2 from the value bytecode.emit(Instruction.SUB) # Jumps back to the top bytecode.emit(Instruction.JMP) bytecode.emit(-15) bytecode.emit(Instruction.HALT) bytecode.dumpinstructions() vm = VM(bytecode) vm.run() print("stack:", vm.stack) print("storage:", vm.storage)