def __init__(self, program, arguments, environment={}, symbolic=[]): # guess architecture from file from elftools.elf.elffile import ELFFile arch = {'x86':'i386','x64':'amd64'}[ELFFile(file(args.program)).get_machine_arch()] bits = {'i386':32, 'amd64':64}[arch] self.trace = [] logger.info("Loading %s ELF program %s", arch, program) logger.info("Arguments: %s", arguments) logger.info("Environment: %s", environment) solver = Solver() mem = SMemory(solver, bits, 12) cpu0 = Cpu(mem, arch) os = SLinux(solver, [cpu0], mem) self.os=os environment = [ '%s=%s' % (key, val) for (key,val) in environment.items() ] arguments = [program] + [ self.makeSymbolic(arguments[i], 'ARGV%02d'%i) for i in xrange(0, len(arguments)) ] environment = [ self.makeSymbolic(environment[i], 'ENV%02d'%i) for i in xrange(0, len(environment)) ] #pass arguments to exe os.exe(program, arguments, environment) #FIXME: Find a way to set symbolic files from command line # open standard files stdin, stdout, stderr assert os._open(SymbolicFile(solver, 'stdin','rb')) == 0 assert os._open(File('stdout','wb')) == 1 assert os._open(File('stderr','wb')) == 2 self.trace = []
def symbbl(inst, arch="i386", preDefineMem={}, startPC=0): assert arch in ["i386", "amd64"] instmem = InstMemory() for addr in xrange(len(inst)): instmem.putchar(addr, inst[addr]) datamem = DataMemory({'i386': 32, 'amd64': 64}[arch]) PC0 = startPC cpu = Cpu(instmem, datamem, arch) cpu.PC = startPC for k in preDefineMem.keys(): _doPreDefineMem(k[0], k[1], preDefineMem[k], datamem, cpu) #RUN while PC0 <= cpu.PC < len(inst) + PC0: if issymbolic(cpu.PC): pcs = getallvalues(cpu.PC) if len(pcs) == 1: cpu.PC = pcs[0] else: print "Stop Execution because symbolic PC" print pcs print cpu.PC raw_input() break print cpu.getInstruction(cpu.PC) cpu.execute() return cpu
def __init__(self): self.screen = Screen(640, 320) self.input_handler = InputHandler(self.screen) self.cpu = Cpu(self.screen, self.input_handler) self.loop()
def main(): # Initialize CPU cpu = Cpu() # Initialize graphics key_lookup = initialize_io() key = None # Specify Rom (TODO: Build CLI) rom_path = "~Barend/Github/Chip-8/Roms/EMULOGO.ch8" # Load ROM load_rom(cpu.memory, cpu.pc, rom_path) # Main cycle while cpu.pc <= 4096: # Get pressed keys for event in pygame.event.get(): if event.type == pygame.KEYDOWN: key = key_lookup[event.unicode] # fetch opcode from memory opcode = cpu.fetch_opcode(cpu.pc) hex_opcode = hex(opcode) program_counter = cpu.pc # Execute opcode cpu.execute_operation(opcode, key)
def main(): rom = file_explorer() if rom is None: sys.exit() renderer = Renderer() keyboard = Keyboard() cpu = Cpu(renderer, keyboard) game_starter(rom, cpu, renderer, keyboard)
def __init__(self, rom): self.rom = rom self.cpu = Cpu() self.gpu = Gpu() self.cpu.gpu = self.gpu # fill ram/rom for index, byte in enumerate(self.rom.rom): self.cpu.write_8bit(index, byte)
def __init__(self, debug, graphicsScale): self.rom = Rom() self.gpu = Gpu(graphicsScale) self.cpu = Cpu(self.gpu) self.gpu.setCpu(self.cpu) self.debugger = None self.debugger = Debugger(self.cpu) if True == debug: self.debugger.activate()
def initCpuList(statFile): """ This function only runs once to initialize the cpuList. It creates placeholder Cpu objects for the cpuList so they can be used to store all cpu information later in the code. """ global cpuList statsAllCpu = re.findall(r'cpu\d+.* ', statFile) for statsForOneCpu in statsAllCpu: cpuCols = statsForOneCpu.split() cpuName = cpuCols[0] tempCpu = Cpu(cpuName) cpuList.append(tempCpu)
def part1(): target = 19690720 part1_code = _code.copy() cpu = Cpu(_code) for noun in range(100): for verb in range(100): part1_code[1] = noun part1_code[2] = verb cpu.flash(part1_code) memory = cpu.run() if memory[0] == target: return 100 * noun + verb
def run(fp): program_contents = "" while True: read = os.read(fp, 4096) if len(read) == 0: break program_contents += read os.close(fp) cpu = Cpu(1024 * 1024, program_contents) start = time.time() cpu.run() end = time.time() print print "Executed %sops in %ss ( %sops/sec )" % (printpretty( cpu.counter), printpretty(end - start), printpretty(cpu.counter / (end - start)))
def on_init(self): pygame.init() self._display_surf = pygame.display.set_mode( self.size, pygame.HWSURFACE | pygame.DOUBLEBUF, 8) # Set NES color palette. self._display_surf.set_palette([(0x75, 0x75, 0x75), (0x27, 0x1b, 0x8f), (0x00, 0x00, 0xab), (0x47, 0x00, 0x9f), (0x8f, 0x00, 0x77), (0xab, 0x00, 0x13), (0xa7, 0x00, 0x00), (0x7f, 0x0b, 0x00), (0x43, 0x2f, 0x00), (0x00, 0x47, 0x00), (0x00, 0x51, 0x00), (0x00, 0x3f, 0x17), (0x1b, 0x3f, 0x5f), (0x00, 0x00, 0x00), (0x00, 0x00, 0x00), (0x00, 0x00, 0x00), (0xbc, 0xbc, 0xbc), (0x00, 0x73, 0xef), (0x23, 0x3b, 0xef), (0x83, 0x00, 0xf3), (0xbf, 0x00, 0xbf), (0xe7, 0x00, 0x5b), (0xdb, 0x2b, 0x00), (0xcb, 0x4f, 0x0f), (0x8b, 0x73, 0x00), (0x00, 0x97, 0x00), (0x00, 0xab, 0x00), (0x00, 0x93, 0x3b), (0x00, 0x83, 0x8b), (0x00, 0x00, 0x00), (0x00, 0x00, 0x00), (0x00, 0x00, 0x00), (0xff, 0xff, 0xff), (0x3f, 0xbf, 0xff), (0x5f, 0x97, 0xff), (0xa7, 0x8b, 0xfd), (0xf7, 0x7b, 0xff), (0xff, 0x77, 0xb7), (0xff, 0x77, 0x63), (0xff, 0x9b, 0x3b), (0xf3, 0xbf, 0x3f), (0x83, 0xd3, 0x13), (0x4f, 0xdf, 0x4b), (0x58, 0xf8, 0x98), (0x00, 0xeb, 0xdb), (0x00, 0x00, 0x00), (0x00, 0x00, 0x00), (0x00, 0x00, 0x00), (0xff, 0xff, 0xff), (0xab, 0xe7, 0xff), (0xc7, 0xd7, 0xff), (0xd7, 0xcb, 0xff), (0xff, 0xc7, 0xff), (0xff, 0xc7, 0xdb), (0xff, 0xbf, 0xb3), (0xff, 0xdb, 0xab), (0xff, 0xe7, 0xa3), (0xe3, 0xff, 0xa3), (0xab, 0xf3, 0xbf), (0xb3, 0xff, 0xcf), (0x9f, 0xff, 0xf3), (0x00, 0x00, 0x00), (0x00, 0x00, 0x00), (0x00, 0x00, 0x00)]) self._running = True self.cartridge = Cartridge("../../test/ff.nes") self.ppu = Ppu(self._display_surf) self.papu = Papu() self.cpu = Cpu(self.ppu, self.papu, self.cartridge, KeyboardController(self._display_surf)) self.cpu.power_on()
def parseInfo(statFile, readTime): """ This function takes the information from /proc/stat and parses it for relevant information. Parameters: statFile (str): The contents of /proc/stat. readTime (float): The time at which /proc/stat was read. Returns: list: Returns a list of Cpu objects for each cpu on the system. """ global cpuList try: statsAllCpu = re.findall(r'cpu\d+.* ', statFile) for statsForOneCpu in statsAllCpu: cpuName, utime, _, stime, idle, *_ = statsForOneCpu.split() cpuIndex = cpuList.index(Cpu(cpuName)) cpuList[cpuIndex].updateAll(utime, stime, idle, readTime) return cpuList except: print("Error occurred while parsing cpustat file") return []
import sys from helpers.utilities import Utilities import lexer import token_parser import run from cpu import Cpu from display import Display if __name__ == "__main__": sys.setrecursionlimit(10**6) code = Utilities.read_asm_file("src/display_test.asm") print("\n----- Stage 1 (Lexer) ----\n") tokens = lexer.lexer(code) for token in tokens: print(token) print("\n----- Stage 2 (Parser) ----\n") # Parse the token list parsed = token_parser.parser(tokens) for parsed_item in parsed: print(parsed_item) print("\n----- Stage 3 (Execution) ----\n") z80 = Cpu() display = Display() run.runner(z80, parsed, display) print(z80)
def __init__(self): self.board = Board() self.playerO = Human("O", self.board) self.playerX = Cpu("X", self.board)
argv.append('matrizlinha.txt') argv.append('matrizcoluna.txt') argv.append('matrizlinha.txt') argv.append('matrizcoluna.txt') argv.append('matrizlinha.txt') argv.append('matrizcoluna.txt') argv.append('matrizlinha.txt') argv.append('matrizcoluna.txt') argv.append('matrizlinha.txt') argv.append('matrizcoluna.txt') argv.append('matrizlinha.txt') argv.append('matrizcoluna.txt') argv.append('matrizlinha.txt') argv.append('matrizcoluna.txt') argv.append('matrizlinha.txt') argv.append('matrizcoluna.txt') argv.append('matrizlinha.txt') argv.append('matrizcoluna.txt') argv.append('matrizlinha.txt') if len(argv) <= 1: print("Usage: pyton main.py programa1.txt programa2.txt...") exit() c = Cpu() mmu = Mmu(int(MEMORIA() / PAGINA()), PAGINA()) dados = Dados(MEMORIA(), PAGINA()) controlador = Controlador() timer = Timer() so = So(timer, argv, dados) controlador.inicia(c, argv, dados, mmu, so, timer)
import sys from cpu import Cpu cpu = Cpu() if len(sys.argv) != 2: print("usage: ls8.py <filename>", file=sys.stderr) sys.exit(1) else: cpu.load(sys.argv[1]) cpu.run()
from cpu import Cpu from linux import Linux import traceback elf = Elf("../progs_to_test/bin/hello_cpp") mem = Memory() # Load program segments into the memory for ph in elf.program_header.entries: data = ph.data_to_load_to_memory print("writing a segment: %d bytes at pos 0x%x" % (len(data), ph.p_vaddr)) mem.write(ph.p_vaddr, data) cpu = Cpu(mem, elf.elf_header.e_entry, 0x123456789ABCDEF) linux = Linux(cpu, mem) cpu.linux = linux # set gs and fs to non-zero values # TODO: initialize to meaningful values cpu.gs = 0xeeeeeeeeeeee cpu.fs = 0xf0f0f0f0f0f0 try: while not cpu.stopped: print("=====") print("pos = 0x%x" % cpu.mem_stream.pos) cpu.exectute_next_instruction()
from cpu import Cpu if __name__ == "__main__": proc = Cpu() proc.memory = [ 6502, # Store the integer of 6502 in location 0x00 42, # Store the integer of 42 in location 0x01 0xA5, 0x00, # LDA 00 ; Store the value at 0x00 in the A register 0xA6, 0x01, # LDX 01 ; Store the value at 0x01 in the X register 0x85, 0x01, # STA 01 ; Store the value in the A register in location 0x01 0x86, 0x00, # STX 00 ; Store the value in the X register in location 0x00 00 # BRK ; End our glorious program ] # our first instruction is LDA, which is at location 0x02, let's start there proc.pc = 0x02 # Examine the memory before we start print("Before -- 0x00: %d 0x01: %d" % (proc.memory[0x0], proc.memory[0x1])) proc.run() # The results. The values at 0x0 and 0x1 should be swapped print("After -- 0x00: %d 0x01: %d" % (proc.memory[0x0], proc.memory[0x1]))
from memory import Memory from cpu import Cpu import random import matplotlib.pyplot as plt hdd = Memory('HDD', 5000, 3.) hdd.data_init() # 캐시 메모리가 l1만 있을 때 -> l1의 lower_memory = ram ram = Memory('RAM', 1000, 1., hdd) # l3 = Memory('L3', 200, 0.1, ram) # l2 = Memory('L2', 20, 0.1, l3) # l1= Memory('L1', 5, 0.1, l2) l1 = Memory('L1', 5, 0.1, ram) cpu = Cpu(l1) for i in range(1000): v1 = random.randint(1, 1000) v2 = random.randint(1, 1000) print("(register 1)", v1, "(register 2)", v2, " = ", cpu.plus(v1, v2)) print("cache L1 : ", l1.memory) print("Hit =", Memory.hit) print('Memory access time of L1, ram, hdd =', round(Memory.total_time, 2)) hitRatio1 = Memory.hit / Memory.total_hit totalTime1 = Memory.total_time # 캐시 메모리가 l1, l2, l3 3개일 때 -> 각각의 lower_memory는 순차적으로 내려감 # 메모리의 상황이 달라졌기 때문에 다시 초기화한다. ram = Memory('RAM', 1000, 1., hdd) l3 = Memory('L3', 200, 0.1, ram) l2 = Memory('L2', 20, 0.1, l3)
#* You should have received a copy of the GNU General Public License * #* along with this program. If not, see <http://www.gnu.org/licenses/>. * #* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ import sys import os from optparse import OptionParser from cpu import Cpu # Options, usage and stuff... ver = "%prog - version 0.1" usage = "usage: '%prog [options] GAME'\n\n" usage += "chipy8 is a Chip8 emulator written in Python using pygame.\n" parser = OptionParser(usage, version=ver) parser.add_option('-v', '--verbose', action='store_true', dest='verbose', default=False, help='Print debug information') parser.add_option('-i', '--ips', action='store', dest='ips', type='float', default=60, help='How many instructions to execute each second') parser.add_option('-s', '--scale', action='store', dest='scale', type='int', default=1, help='Increase the window size with the scale factor') (options, args) = parser.parse_args() if len(args) != 1: parser.error("Wrong number of arguments specified") else: if not os.path.exists(args[0]): parser.error("File doesn't exist") else: if os.path.getsize(args[0]) > 0x0fff: parser.error("File to large") cpu = Cpu(options.verbose, options.scale) cpu.read_rom(args[0]) cpu.run(options.ips)
def game_loop(): pygame.init() beep = pygame.mixer.Sound("bell.ogg") size = width, height = 640, 320 clock = pygame.time.Clock() black = 0, 0, 0 white = 255, 255, 255 fps = 60 gfx_width = 64 gfx_height = 32 scale_factor = 10 screen = pygame.display.set_mode(size) game = load_game("PONG2") cpu = Cpu() cpu.reset() i = 0 for x in range(len(game)): cpu.memory[i + 0x200] = game[i] i += 1 run = True while (run): for event in pygame.event.get(): if event.type == pygame.QUIT: run = False keys = pygame.key.get_pressed() if keys[pygame.K_ESCAPE]: run = False #Row 1 of keys cpu.key[1] = keys[pygame.K_1] cpu.key[2] = keys[pygame.K_2] cpu.key[3] = keys[pygame.K_3] cpu.key[0xc] = keys[pygame.K_4] #Row 2 of keys cpu.key[4] = keys[pygame.K_q] cpu.key[5] = keys[pygame.K_w] cpu.key[6] = keys[pygame.K_e] cpu.key[0xd] = keys[pygame.K_r] #Row 3 of keys cpu.key[7] = keys[pygame.K_a] cpu.key[8] = keys[pygame.K_s] cpu.key[9] = keys[pygame.K_d] cpu.key[0xe] = keys[pygame.K_f] #Row 4 of keys cpu.key[0xa] = keys[pygame.K_z] cpu.key[0x0] = keys[pygame.K_x] cpu.key[0xb] = keys[pygame.K_c] cpu.key[0xf] = keys[pygame.K_v] cpu.cycle() if cpu.play_sound: pygame.mixer.Sound.play(beep) cpu.play_sound = False if cpu.draw_flag: clock.tick(fps) for i in range(gfx_height): for j in range(gfx_width): if cpu.gfx[i * gfx_width + j]: screen.fill(white, (j * scale_factor, i * scale_factor, scale_factor, scale_factor)) else: screen.fill(black, (j * scale_factor, i * scale_factor, scale_factor, scale_factor)) pygame.display.flip() cpu.draw_flag = False pygame.quit()
def __init__(self): self.__cpu = Cpu() self.__ram = Ram()
from cpu import Cpu from interpreter import Interpreter import struct if __name__ == "__main__": src = './code/factorial.asm' i = Interpreter() i.asm_decoder(src) vm = Cpu("./code/factorial.o") # print(vm.__get_data_from_memory(0)) # memory = 4 + 2 * 4 # pos = 0 vm.start() # vm.mm[0:4] = bytearray(struct.pack('I', 42)) # print(struct.unpack('I', vm.mm[pos:pos + 4])) vm.close()
from cpu import Cpu #Nombre del paquete de la aplicacion ASI Ecuador package = "ec.gob.asi.android" #Creando objeto, tiempo de ejecucion y dibujo de la serie de tiempo asi_cpu = Cpu() tiempo_estimado = int(input("Ingrese el tiempo de prueba: ")) asi_cpu.plot_cpu_real_time(tiempo_estimado, package) #Generando el .csv asi_cpu.put_csv() print("Valor maximo: " + str(asi_cpu.get_max_value()) + " %") print("Valor minimo: " + str(asi_cpu.get_min_value()) + " %") print("Mediana: " + str(asi_cpu.get_mediana_value()) + " %") print("Promedio: " + str(round(asi_cpu.get_promedio_value(), 2)) + " %")
def main(fileName): cpu = Cpu() cpu.load_rom(fileName) pygame.init() size = (640, 320) screen = pygame.display.set_mode(size) pygame.display.set_caption("Chip8") BLACK = (0, 0, 0) WHITE = (255, 255, 255) carryOn = True clock = pygame.time.Clock() while carryOn: for event in pygame.event.get(): # User did something if event.type == pygame.QUIT: # If user clicked close carryOn = False # Flag that we are done so we exit this loop #cpu.clear_keyboard() if event.type == pygame.KEYDOWN: if event.key == pygame.K_1: cpu.keyboard[0] = True if event.key == pygame.K_2: cpu.keyboard[1] = True if event.key == pygame.K_3: cpu.keyboard[2] = True if event.key == pygame.K_4: cpu.keyboard[3] = True if event.key == pygame.K_q: cpu.keyboard[4] = True if event.key == pygame.K_w: cpu.keyboard[5] = True if event.key == pygame.K_e: cpu.keyboard[6] = True if event.key == pygame.K_r: cpu.keyboard[7] = True if event.key == pygame.K_a: cpu.keyboard[8] = True if event.key == pygame.K_s: cpu.keyboard[9] = True if event.key == pygame.K_d: cpu.keyboard[10] = True if event.key == pygame.K_f: cpu.keyboard[11] = True if event.key == pygame.K_z: cpu.keyboard[12] = True if event.key == pygame.K_x: cpu.keyboard[13] = True if event.key == pygame.K_c: cpu.keyboard[14] = True if event.key == pygame.K_v: cpu.keyboard[15] = True if event.type == pygame.KEYUP: if event.key == pygame.K_1: cpu.keyboard[0] = False if event.key == pygame.K_2: cpu.keyboard[1] = False if event.key == pygame.K_3: cpu.keyboard[2] = False if event.key == pygame.K_4: cpu.keyboard[3] = False if event.key == pygame.K_q: cpu.keyboard[4] = False if event.key == pygame.K_w: cpu.keyboard[5] = False if event.key == pygame.K_e: cpu.keyboard[6] = False if event.key == pygame.K_r: cpu.keyboard[7] = False if event.key == pygame.K_a: cpu.keyboard[8] = False if event.key == pygame.K_s: cpu.keyboard[9] = False if event.key == pygame.K_d: cpu.keyboard[10] = False if event.key == pygame.K_f: cpu.keyboard[11] = False if event.key == pygame.K_z: cpu.keyboard[12] = False if event.key == pygame.K_x: cpu.keyboard[13] = False if event.key == pygame.K_c: cpu.keyboard[14] = False if event.key == pygame.K_v: cpu.keyboard[15] = False pass # Do clock cycle cpu.clock_cycle() if (cpu.quit): pygame.quit() return screen.fill(WHITE) #Clear screen #Draw on screen if cpu.display.draw: cpu.display.draw = False pixels = cpu.display.pixels for x in range(64): for y in range(32): if (pixels[y][x]): pygame.draw.rect(screen, WHITE, (x * 10, y * 10, 10, 10)) else: pygame.draw.rect(screen, BLACK, (x * 10, y * 10, 10, 10)) pygame.display.flip() #Show screen clock.tick(60) pygame.quit() pass
def get_ui(self, cfg, id=None): m = Cpu(self.app).prepare(cfg) return UI.HContainer( UI.ProgressBar(value=m.get_value(), max=m.get_max(), width=220), UI.Label(text=str(m.get_value())+'%'), )