def main(argv): input = FileStream(argv[1]) lexer = QuarkLexer(input) stream = CommonTokenStream(lexer) parser = QuarkParser(stream) tree = parser.main() virtual_machine = VirtualMachine(parser) virtual_machine.run()
def get_choices_vm_hardware(self, vm): chosen_option, index = pick(self.options_vm_hardware, self.title) # if last element, exit if index == len(self.options_vm_hardware) - 1: exit(0) elif index == 0: VirtualMachine.change_mac(vm, self.inventory.service_instance) elif index == 2: exit(0)
class TestVirtualMachine(unittest.TestCase): def setUp(self): ctx = FakeContext() secret_key = ctx.generate_keys() tape = Tape() tape_indices = tape.generate_tape(2, ctx, secret_key) utils.flag = Number.from_plaintext(1, ctx, secret_key, size=1) utils.one = Number.from_plaintext(1, ctx, secret_key, size=1) utils.zero = Number.from_plaintext(0, ctx, secret_key, size=1) # Initial state of machine data_ptr = Number.from_plaintext(0, ctx, secret_key) instruction_ptr = Number.from_plaintext(0, ctx, secret_key) # Defines instructions inc_data_ptr = Number.from_plaintext(1, ctx, secret_key) inc_data_cell = Number.from_plaintext(2, ctx, secret_key) dec_data_ptr = Number.from_plaintext(3, ctx, secret_key) dec_data_cell = Number.from_plaintext(4, ctx, secret_key) mark_loop = Number.from_plaintext(5, ctx, secret_key) loop_back = Number.from_plaintext(6, ctx, secret_key) instruction_set = { "+":inc_data_cell, "-":dec_data_cell, ">":inc_data_ptr, "<":dec_data_ptr, "[":mark_loop, "]":loop_back } instructions, instruction_indices = VirtualMachine.compile("++[>+++<-]", instruction_set, ctx, secret_key) self.blind_machine = VirtualMachine( tape, tape_indices, instruction_indices, instruction_set, instructions, instruction_ptr, data_ptr ) self.context = ctx self.secret_key = secret_key self.tape = tape def test_machine_step(self): self.blind_machine.run() self.assertEqual(self.tape.decrypt_tape(self.secret_key), [0, 6])
def main(argv): while True: input_ = input("|> ") with NamedTemporaryFile(mode="wb") as input_file: print(input_.encode('utf-8'), file=input_file) filename = input_file.name lexer = QuarkLexer(FileStream(filename)) stream = CommonTokenStream(lexer) parser = QuarkParser(stream) tree = parser.main() virtual_machine = VirtualMachine(parser) virtual_machine.run()
def p_programa(p): 'programa : dec_programa progvar main_goto progfunc main_block' log.write("/////////////Programa terminado con exito///////////////") log.write(" ######### Register table ###########") register.print_table() log.write(" ####### Debug Quadruples ############") quadruple_reg.print_debug_quadruples() log.write('########## Constants ###########') quadruple_reg.print_constants() log.write('########## Quadruple names ###########') quadruple_reg.print_name_quadruples() log.write('########## Quadruple dirs ###########') quadruple_reg.print_quadruples() log.write('##') register.function_list[0]['size_dict'] = register.address_handler.return_global_size_dict() # Cosigue el directorio de funciones de la clase register dir_funciones = register.function_list # Guarda la tabla de constantes que se tenía en el quadruple_register constant_table = quadruple_reg.constant_list # Guarda la lista de cuádruplos generados quadruple_list = quadruple_reg.quadruple_list quadruples = [] # Guarda sólo las direcciones en los cuádruplos for quadruple in quadruple_list: oper = quadruple['operator'] op_1 = quadruple['operand_1'] op_2 = quadruple['operand_2'] res = quadruple['result'] if isinstance(op_1, dict): op_1 = op_1['address'] if op_2 is not None: if isinstance(op_2, dict): op_2 = str(op_2['address']) else: op_2 = str(op_2) if isinstance(res, dict): res = res['address'] quadruple_new = dict(operator=oper, operand_1=op_1, operand_2=op_2, result=res) quadruples.append(quadruple_new) # Genera un último cuádruplo al final que termina el programa quadruple_new = dict(operator="end", operand_1=None, operand_2=None, result=None) quadruples.append(quadruple_new) # Inicializa la máquina virtual y ejecuta los cuádruplos vm = VirtualMachine(quadruples, constant_table, dir_funciones) vm.execute_code()
def run(code, tape_size=2): ctx = NUFHEContext() #ctx = FakeContext() secret_key = ctx.generate_keys() # Create tape with size of 2 tape = Tape() tape_indices = tape.generate_tape(tape_size, ctx, secret_key) utils.flag = Number.from_plaintext(1, ctx, secret_key, size=1) utils.one = Number.from_plaintext(1, ctx, secret_key, size=1) utils.zero = Number.from_plaintext(0, ctx, secret_key, size=1) # Initial state of machine data_ptr = Number.from_plaintext(0, ctx, secret_key) instruction_ptr = Number.from_plaintext(0, ctx, secret_key) # Defines instructions inc_data_ptr = Number.from_plaintext(1, ctx, secret_key) inc_data_cell = Number.from_plaintext(2, ctx, secret_key) dec_data_ptr = Number.from_plaintext(3, ctx, secret_key) dec_data_cell = Number.from_plaintext(4, ctx, secret_key) mark_loop = Number.from_plaintext(5, ctx, secret_key) loop_back = Number.from_plaintext(6, ctx, secret_key) instruction_set = { "+": inc_data_cell, "-": dec_data_cell, ">": inc_data_ptr, "<": dec_data_ptr, "[": mark_loop, "]": loop_back } instructions, instruction_indices = VirtualMachine.compile( code, instruction_set, ctx, secret_key) blind_machine = VirtualMachine(tape, tape_indices, instruction_indices, instruction_set, instructions, instruction_ptr, data_ptr) blind_machine.run() pprint.pprint(tape.decrypt_tape(secret_key))
def test_invalid_jump_destination(): with pytest.raises(IndexError) as excinfo: VirtualMachine().runCode([ PUSH, 66, PUSH, 1, JUMPI, PUSH, 0, JUMP, PUSH, 'jumpi successful', STOP ]) assert "Invalid destination" in str(excinfo.value)
def __init__(self, folder_name, name, si): self._name = name self._folder_name = folder_name self._si = si self._virtual_machines = [] for vm in VmUtils.get_vms_by_compute_resource(self._folder_name, self._name, self._si): self._virtual_machines.append(VirtualMachine(self._folder_name, self._name, vm))
def __init__(self, number_of_individuals, selection, crossing, p_mutation, elitarism, number_of_generations): """ :param number_of_individuals: int :param selection: function :param crossing: :param p_mutation: array? # FIXME :param elitarism: :param number_of_generations: """ self.number_of_individuals = number_of_individuals self.selection = selection self.crossing = crossing self.p_mutation = p_mutation self.elitarism = elitarism self.number_of_generations = number_of_generations self.individuals = [] self.virtual_machine = VirtualMachine()
class TestSimple: def setup(self): self.vm = VirtualMachine() self.program = "" def teardown(self): exec_globals, exec_locals = {}, {} vm_globals, vm_locals = {}, {} assert (exec(self.program, exec_locals, exec_locals) == self.vm.run_code(self.program, vm_globals, vm_locals)) assert (exec_globals == vm_globals) exec_keys = list(exec_locals.keys()) for key in exec_keys: if key.startswith("__"): exec_locals.pop(key) assert (exec_locals == vm_locals) def test_operations(self): self.program = """ a = 10 b = 20 c = a - b d = a + b e = a / b f = a * b g = f / c - (a + b * d) / e + b / e""" def test_append(self): self.program = """ l = [] for i in range(100): l.append(i)""" def test_loop(self): self.program = """ a = 0 for i in range(100): a += 1""" def test_add(self): self.program = """ a = 10 b = 20 c = a + b""" def test_mul(self): self.program = """
def run(): ctx = nufhe.Context() secret_key, cloud_key = ctx.make_key_pair() vm = ctx.make_virtual_machine(cloud_key) # Create tape # Create VM # Execute instruction # Get output tape encrypted # Decrypt tape to get execution results tape = Tape() # Create tape of size n n = 2 indices = [] # Encrypt indices before feeding into VM for x in range(n): tape.add_cell(Number.from_plaintext(0, ctx, secret_key)) indices.append(Number.from_plaintext(x, ctx, secret_key)) utils.logic = vm utils.flag = Number.from_plaintext(1, ctx, secret_key, size=1) # Flag for conditions utils.one = Number.from_plaintext(1, ctx, secret_key, size=1) # A one utils.zero = Number.from_plaintext(0, ctx, secret_key, size=1) # A zero utils.data_ptr = Number.from_plaintext(0, ctx, secret_key) # Cell to perform op on blind_machine = VirtualMachine(tape, indices) # Add 1 instruction """for x in range(3): inc_data_ptr = Number.from_plaintext(0, ctx, secret_key) inc_data_cell = Number.from_plaintext(1, ctx, secret_key) blind_machine.step(inc_data_ptr, inc_data_cell) """ #print(utils.one + utils.one) A = 129 B = 5 sum = Number.from_plaintext(A, ctx, secret_key) + Number.from_plaintext( B, ctx, secret_key) print(sum.decrypt(ctx, secret_key)) print(A, "+", B, "=", sum.decrypt(ctx, secret_key, decimal=True))
def main(): machine = VirtualMachine(config.get('machine_limit')) m = read_map(config.get('map_name')) pop = generate_population(config.get('population_size'), config.get('ind_min_size'), machine, deepcopy(m)) mutation_probability = config.get('mutation_probability') el = config.get('elitarism_size') top, gen, avgs = genetic_algorithm(pop, fiitness_function, machine, mutation, crossover, requirement, mutation_probability, m, el) print_way(top['Object'], deepcopy(m)) plt.plot([x for x in range(0, gen + 1)], avgs) plt.show()
def print_way(individual, m): """ Prints found way :param individual: int """ machine = VirtualMachine(500) curr = m['Start'] t_c = 0 for step in machine.run_program(copy.deepcopy(individual)): if t_c == m['Treasure_count']: return curr = (curr[0] + steps[step][0], curr[1] + steps[step][1]) print(curr) try: if curr[0] < 0 or curr[1] < 0 or curr[0] > m['Height'] or curr[ 1] > m['Width']: return if m['Map'][curr[0]][curr[1]] == 'P': t_c += 1 print(t_c) m['Map'][curr[0]][curr[1]] = 'X' except: return return
def update_from_xml(self, xml_path): xml_object = ParseXML(xml_path) logger.debug('Parsed XML file') self.suite = xml_object.get_tests_suite() logger.debug('Saving Tests Suite name - %s', self.suite) for test_case_name, props in xml_object.get_tests().iteritems(): logger.debug('Initializing TestCase object for %s', test_case_name) self.test_cases[test_case_name] = TestCase(name=test_case_name, properties=props) for vm_name, vm_details in xml_object.get_vms().iteritems(): logger.debug('Initializing VirtualMachine object for %s', vm_name) self.vms[vm_name] = VirtualMachine( vm_name=vm_name, hv_server=vm_details['hvServer'], os=vm_details['os'], check=self.validate_vm)
def p_np_end_program_(p): ''' np_end_program_ : ''' # Adds ENDProg quadruple and performs finishing functions inter_code.add_endprog_quad() # creates the output to be added to the obj file output = { 'Constants': inter_code.mem.constant_.output(), 'Quadruples': inter_code.quadruples, 'DirFunc': dir_func.output() } inter_code.mem.constant_.reset_memory() # creates the object code file with open("fa.bigsheep","w+") as json_file: json.dump(output, json_file) # starts the instance of the virtual machine vm = VirtualMachine("fa.bigsheep")
class GeneticAlgorithm: #počet jedincov programu, typ selekcie, (prípadne typ kríženia) pravdepodobnosť mutácie # (každého použitého typu), elitarizmus (áno/nie, prípadne počet), počet generácií # na koniec/prerušenie, ak nenájdem všetky poklady skôr def __init__(self, number_of_individuals, selection, crossing, p_mutation, elitarism, number_of_generations): """ :param number_of_individuals: int :param selection: function :param crossing: :param p_mutation: array? # FIXME :param elitarism: :param number_of_generations: """ self.number_of_individuals = number_of_individuals self.selection = selection self.crossing = crossing self.p_mutation = p_mutation self.elitarism = elitarism self.number_of_generations = number_of_generations self.individuals = [] self.virtual_machine = VirtualMachine() def create_first_generation(self): # RANDOM for _ in range(self.number_of_individuals): self.individuals.append( Individual([{ 'program': random.randint(0, 255), 'fitness': 0 } for _ in range(cs.INDIVIDUAL_MEMORY)])) def test_generation(self): for ind in self.individuals: ind['fitness'] = self.virtual_machine.evaluate(ind['program']) return
def test_add(): assert VirtualMachine().runCode([PUSH, 3, PUSH, 4, ADD, STOP]) == 7
def add_vms_for_benchmark_if_possible(self, bm): """[summary] [description] Args: bm: [description] Returns: [description] bool """ vm_ids = [] vms = [] for vm_spec in bm.vm_specs: print(vm_spec.id) vm_region = cloud_util.get_region_from_zone( vm_spec.cloud, vm_spec.zone) vm_id = self.vm_total_count vm = VirtualMachine(node_id=vm_id, cpu_count=vm_spec.cpu_count, zone=vm_spec.zone, os_type=vm_spec.os_type, network_tier=vm_spec.network_tier, machine_type=vm_spec.machine_type, cloud=vm_spec.cloud, min_cpu_platform=vm_spec.min_cpu_platform, ssh_private_key=self.ssh_private_key_file, ssl_cert=self.ssl_cert_file, vm_spec=vm_spec, vm_spec_id=vm_spec.id) # if VM with same specs already exists, return false 0 tmp_vm_list = self.get_list_if_vm_exists(vm) suitable_vm_found = False # if a vm already exists if len(tmp_vm_list) > 0: can_add_another, status = self.check_if_can_add_vm(vm) add_from_list = True # if there is room to add a duplicate vm and if flags allow it # then add the VM if (can_add_another and status == "VM Exists. Quota not Exceeded" and FLAGS.allow_duplicate_vms == True and len(tmp_vm_list) < FLAGS.max_duplicate_vms + 1): print("here1") # checks if there is enough space in a region to add another vm success = self.regions[ vm_region].add_virtual_machine_if_possible(vm) if success: add_from_list = False self.virtual_machines.append(vm) self.graph.add_node(vm_id, vm=vm) vms.append(vm) vm_ids.append(vm.node_id) self.vm_total_count += 1 suitable_vm_found = True continue else: logger.debug("QUOTA EXCEEDED. add from existing") # TODO add to tmp_list add_from_list = True # if not room in quota, return duplicate vm with lowest degree elif add_from_list: tmp_vm_index = 0 min_degree_index = 0 # find initial min_degree_index that has not been used # by a vm in this benchmark while tmp_vm_index < len(tmp_vm_list): if tmp_vm_list[tmp_vm_index].node_id in vm_ids: tmp_vm_index += 1 else: min_degree = self.graph.degree[ tmp_vm_list[tmp_vm_index].node_id] min_degree_index = tmp_vm_index tmp_vm_index += 1 suitable_vm_found = True break while tmp_vm_index < len(tmp_vm_list): degree = self.graph.degree[ tmp_vm_list[tmp_vm_index].node_id] # if degree is smaller and vm_id not already in this benchmark if (degree < min_degree and not (tmp_vm_list[tmp_vm_index].node_id in vm_ids)): min_degree_index = tmp_vm_index tmp_vm_index += 1 if suitable_vm_found: vms.append(tmp_vm_list[min_degree_index]) vm_ids.append(tmp_vm_list[min_degree_index].node_id) continue # if vm does not exist yet elif (not suitable_vm_found): # try to add vm to region print("here2") status = self.regions[ vm_region].add_virtual_machine_if_possible(vm) print("Status ", status) # if successful, also add that vm to virtual_machines list # and increment total number of vms, return True, and the vm if status is True: print("adding vm in zone " + vm.zone) self.virtual_machines.append(vm) self.graph.add_node(vm_id, vm=vm) vms.append(vm) vm_ids.append(vm.node_id) self.vm_total_count += 1 # return false, None if not enough space in region else: logger.debug("QUOTA EXCEEDED. VM waitlisted") vms.append(None) print(vms) return vms
def test_jumpi(): assert VirtualMachine().runCode([ PUSH, 8, PUSH, 1, JUMPI, PUSH, 0, JUMP, PUSH, 'jumpi successful', STOP ]) == 'jumpi successful'
def test_jump(): assert VirtualMachine().runCode( [PUSH, 6, JUMP, PUSH, 0, JUMP, PUSH, 'jump successful', STOP]) == 'jump successful'
def test_or(): assert VirtualMachine().runCode([PUSH, 0, PUSH, 1, OR, STOP]) == 1
def test_and(): assert VirtualMachine().runCode([PUSH, 0, PUSH, 1, AND, STOP]) == 0
def test_EQ(): assert VirtualMachine().runCode([PUSH, 3, PUSH, 4, EQ, STOP]) == 0
def test_infinite_loop(): with pytest.raises(RecursionError) as excinfo: VirtualMachine().runCode([PUSH, 0, JUMP, STOP]) assert "infinite loop" in str(excinfo.value)
import dis import builtins from virtual_machine import VirtualMachine vm_locals = {} vm = VirtualMachine(local_names=vm_locals) exec_locals = {} program = """ b = [] b.append(10) b """ if __name__ == "__main__": print(dis.dis(program)) print() for inst in dis.get_instructions(program): print(inst) exec(program, {}, exec_locals) print("Exec:", exec_locals) vm.run_code(program) print("Vm:", vm_locals)
def test_push_instruction_last(): with pytest.raises(RuntimeError) as excinfo: VirtualMachine().runCode([PUSH, 1, PUSH, 2, ADD, PUSH]) assert "cannot be last" in str(excinfo.value)
def test_div(): assert VirtualMachine().runCode([PUSH, 3, PUSH, 6, DIV, STOP]) == 2
def test_sub(): assert VirtualMachine().runCode([PUSH, 3, PUSH, 4, SUB, STOP]) == 1
def test_GT(): assert VirtualMachine().runCode([PUSH, 3, PUSH, 4, GT, STOP]) == 1
def setup(self): self.vm = VirtualMachine() self.program = ""
def test_mul(): assert VirtualMachine().runCode([PUSH, 3, PUSH, 4, MUL, STOP]) == 12