Beispiel #1
0
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)
Beispiel #2
0
    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 BIT(cpu: Cpu, token1: Token, token2: Token) -> None:
    bit = int(token1.value.strip(','))
    # If the bit is not set
    if not cpu.register[token2.token_type] & (1 << bit):
        cpu.flags["Z"] = True
    cpu.flags["N"] = False
    cpu.flags["H"] = True
    return
Beispiel #4
0
 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)
Beispiel #5
0
 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 DEC(cpu: Cpu, token1: Token) -> None:
    # Check if the register isn't already at 0
    if not cpu.register[token1.token_type] == 0:
        cpu.register[token1.token_type] -= 1
        # Set the subtract flag since a subtraction was performed
        cpu.flags["N"] = True
    # Set the zero flag to true since the register value is now zero
    if cpu.register[token1.token_type] == 0:
        cpu.flags["Z"] = True
    return
Beispiel #7
0
class TestMiscOpcodes(unittest.TestCase):
    def setUp(self):
        self.cpu = Cpu(MMU())
        self.cpu.mmu.rom = [0] * 128
        self.cpu.mmu.load('C:/Users/cjpowell/workspace/Python/gbpy/resources/test_file.gb')

    def test_daa(self):
        self.cpu.registers.a = 0xc9
        self.cpu._op_27()
        self.assertEqual(self.cpu.registers.a, 0x29)
        self.assertEqual(self.cpu.registers.carry_flag, 1)
Beispiel #8
0
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 AND(cpu: Cpu, token1: Token) -> None:
    # Check if the token is of type value
    if token1.token_type == tt.VALUE:
        cpu.register[tt.REGISTER_A] &= get_value(token1)
    # Otherwise it must be a register
    else:
        cpu.register[tt.REGISTER_A] &= cpu.register[token1.token_type]
    # Setup flags
    if cpu.register[tt.REGISTER_A] == 0:
        cpu.flags["Z"] = True
    cpu.flags["N"] = False
    cpu.flags["H"] = True
    cpu.flags["C"] = False
    return
Beispiel #10
0
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
Beispiel #11
0
 def setUp(self):
     self.cpu = Cpu(MMU())
     self.cpu.mmu.rom = [0] * 128
     self.cpu.mmu.load('C:/Users/cjpowell/workspace/Python/gbpy/resources/test_file.gb')
     self.cpu.mmu.rom[0] = 0x1
     self.cpu.mmu.rom[1] = 0xed
     self.cpu.registers.sp = 0xfffe
Beispiel #12
0
Datei: nes.py Projekt: c--y/pyes
class Machine(object):

    def __init__(self):
        self.cpu = Cpu(self)
        self.memory = Memory(self)
        self.ppu = Ppu(self)
        self.apu = Apu(self)
        self.pads = [JoyStick(self), JoyStick(self)]
        self.rom = None

        self.total_cycles = 0

    def load_rom(self, file_path):
        nes_rom = read_ines(file_path)
        self.rom = nes_rom.to_mapper()

    def run(self):
        while True:
            cycles = self.cpu.step()
            self.total_cycles += cycles

            for i in xrange(3 * cycles):
                # self.ppu.step()
                pass

            for i in xrange(cycles):
                # self.apu.step()
                pass
Beispiel #13
0
    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 = []
Beispiel #14
0
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)
Beispiel #15
0
    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()
Beispiel #16
0
    def __init__(self):
        self.cpu = Cpu()
        self.ppu = Ppu()

        self.rom = None
        self.memory = None

        self.is_running = False
Beispiel #17
0
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)))
Beispiel #18
0
 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)
Beispiel #19
0
class Nes(object):
    __metaclass__ = Singleton

    def __init__(self):
        self.cpu = Cpu()
        self.ppu = Ppu()

        self.rom = None
        self.memory = None

        self.is_running = False

    def reset(self):
        if self.memory:
            self.memory.reset()

        self.cpu.reset()
        self.ppu.reset()

    def start(self):
        pass
    
    def stop(self):
        pass
    
    def load(self, filename):
        if self.is_running:
            self.stop()

        self.rom = Rom()
        self.rom.load(filename)

        if self.rom.is_valid:
            self.memory = Mapper(self.rom.mapper_type)
            if self.memory == None:
                raise Exception('Unknown mapper: %d' % self.rom.mapper_type)

            self.memory.load()
            self.ppu.set_mirroring(self.rom.get_mirrowing())

        return self.rom.is_valid

    def reload(self):
        if self.rom and self.rom.filename:
            self.load(self.rom.filename)
Beispiel #20
0
Datei: nes.py Projekt: c--y/pyes
    def __init__(self):
        self.cpu = Cpu(self)
        self.memory = Memory(self)
        self.ppu = Ppu(self)
        self.apu = Apu(self)
        self.pads = [JoyStick(self), JoyStick(self)]
        self.rom = None

        self.total_cycles = 0
def XOR(cpu: Cpu, token1: Token) -> None:
    # Check if the token is of type value
    if token1.token_type == tt.VALUE:
        cpu.register[tt.REGISTER_A] ^= get_value(token1)
    # Check if the token is of type direct
    elif token1.token_type == tt.DIRECT:
        cpu.register[tt.REGISTER_A] ^= cpu.memory[get_direct_value(
            cpu, token1)]
    # Otherwise it must be a register
    else:
        cpu.register[tt.REGISTER_A] ^= cpu.register[token1.token_type]
    # Setup flags
    if cpu.register[tt.REGISTER_A] == 0:
        cpu.flags["Z"] = True
    cpu.flags["N"] = False
    cpu.flags["H"] = False
    cpu.flags["C"] = False
    return
Beispiel #22
0
def main():
    cpu = Cpu()
    cpu.load_rom('games/UFO')

    while cpu.running:
        # each instruction is 2bytes long
        # so they need to be put together
        high_byte = cpu.memory[cpu.program_counter]
        low_byte = cpu.memory[cpu.program_counter+1]
        opcode = high_byte << 8 | low_byte
        cpu.opcode = OpCode(opcode)

        instruction = cpu.instruction_mapping.get(cpu.opcode.identifier, None)
        if not instruction:
            raise Exception('Instruction not found {:x}'.format(cpu.opcode))
        else:
            instruction()

        cpu.program_counter += 2
def SUB(cpu: Cpu, token1: Token) -> None:
    # check if the token is of type value
    if token1.token_type == tt.VALUE:
        cpu.register[tt.REGISTER_A] -= get_value(token1)
    # check if the token is of type direct
    elif token1.token_type == tt.DIRECT:
        cpu.register[tt.REGISTER_A] -= cpu.memory[get_direct_value(
            cpu, token1)]
    # Otherwise it must be an register
    else:
        cpu.register[tt.REGISTER_A] -= cpu.register[token1.token_type]
    # Set flags
    if cpu.register[tt.REGISTER_A] <= 0:
        cpu.register[
            tt.
            REGISTER_A] = 0  # Make sure that the register isn't a negative value
        cpu.flags["Z"] = True
    cpu.flags["N"] = True
    return
Beispiel #24
0
 def setUp(self):
     self.mManager = Mock()
     self.mHandler = Mock()
     self.cpu = Cpu(self.mManager,self.mHandler)
     self.aPcb = Mock()
     when(self.aPcb).getPid().thenReturn(0)
     when(self.aPcb).basePointer().thenReturn(0)
     when(self.aPcb).programCounter().thenReturn(0)
     when(self.aPcb).size().thenReturn(0)
     when(self.aPcb).displazament().thenReturn(0)
     self.instruction = Mock()
def SWAP(cpu: Cpu, token1: Token) -> None:
    # Check if we are dealing with a value in memory (direct)
    if token1.token_type == tt.DIRECT:
        value = cpu.memory[get_direct_value(cpu, token1)]
    # Otherwise it must be a register
    else:
        value = cpu.register[token1.token_type]
    result = ((value & 0x0F) << 4 | (value & 0xF0) >> 4)
    # Set flags
    if result <= 0:
        result = 0
        cpu.flags["Z"] = True
    cpu.flags["N"] = False
    cpu.flags["H"] = False
    cpu.flags["C"] = False
    if token1.token_type == tt.DIRECT:
        cpu.memory[get_direct_value(cpu, token1)] = result
    else:
        cpu.register[token1.token_type] = result
    return
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 INC(cpu: Cpu, token1: Token) -> None:
    # TODO: Set H flag
    # Check if the token is of type direct
    if token1.token_type == tt.DIRECT:
        cpu.memory[get_direct_value(cpu, token1)] += 1
    # Otherwise an register is incremented
    else:
        cpu.register[token1.token_type] += 1
    # Reset the the subtract flag since a increment was performed
    cpu.flags["N"] = False
    return
Beispiel #28
0
class Chip8:

    cpu = None
    screen = None
    input_handler = None

    MAX_MEMORY = 4096

    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 loop(self):
        self.cpu.load_rom(sys.argv[1])

        while True:
            self.cpu.cycle()
Beispiel #29
0
class Emu(object):
    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 run(self, binPath):
        self.rom.load(binPath)
        self.cpu.execProg(self.rom.romData, self.debugger)
        self.pyGameMainLoop()

    def pyGameMainLoop(self):
        while 1:
            event = pygame.event.wait()
            if event.type == pygame.KEYDOWN:
                keysPressed = pygame.key.get_pressed()
                self.cpu.keyboard.keyPressedIndication(keysPressed)
                if keysPressed[pygame.K_q]:
                    self.cpu.stop()
            if event.type == pygame.QUIT:
                self.cpu.stop()

            if False == self.cpu.running:
                raise SystemExit
def LD(cpu: Cpu, token1: Token, token2: Token) -> None:
    # Check if the second token is of type value
    if token2.token_type == tt.VALUE:
        # Check if the first token is of type direct
        if token1.token_type == tt.DIRECT:
            cpu.memory[get_direct_value(cpu, token1)] = get_value(token2)
            return
        # Otherwise it must be a register
        cpu.register[token1.token_type] = get_value(token2)
    # Check if the second token is of type direct
    elif token2.token_type == tt.DIRECT:
        cpu.register[token1.token_type] = cpu.memory[get_direct_value(
            cpu, token2)]
        return
    # Otherwise it must be register
    else:
        # Check if the first token is of type direct
        if token1.token_type == tt.DIRECT:
            cpu.memory[get_direct_value(
                cpu, token1)] = cpu.register[token2.token_type]
            return
        # Otherwise it must be register to register operations
        cpu.register[token1.token_type] = cpu.register[token2.token_type]
    return
Beispiel #31
0
def test_cpu_init():
    c = Cpu(Machine())
    print c.__dict__

    c.set_carry(True)
    out1 = bin(c.p.value)
    print out1

    c.set_interrupt(True)
    out2 = bin(c.p.value)
    print out2

    c.test_and_set_negative(0x80)
    out4 = bin(c.p.value)
    print out4
Beispiel #32
0
class Chip16:
    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 step(self):
        self.cpu.step()

    def print_debug(self):
        self.cpu.print_state()
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 []
Beispiel #34
0
class Chip16:

    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 step(self):
        self.cpu.step()

    def print_debug(self):
        self.cpu.print_state()
Beispiel #35
0
def runner(cpu: Cpu,
           parsed_tokens: List[List[Token]],
           display: Display = None) -> None:
    # Is the program finished?
    if cpu.register[TokenType.REGISTER_PC] >= len(parsed_tokens):
        print(f"[info] The program has jumped {JP.counter} times\n")
        return

    # Are the labels found yet?
    if cpu.labels is None:
        cpu.labels = search_labels(parsed_tokens)

    # Unpack current line
    opcode, *params = parsed_tokens[cpu.register[TokenType.REGISTER_PC]]

    # Check if the to be executed line isn't an invalid line
    if opcode.token_type == TokenType.INVALID:
        raise ASMSyntaxError(opcode.line, f"Invalid syntax: {opcode.value}")

    # Execute current line
    pc_value = cpu_opcodes[opcode.token_type](cpu, *params)

    # If the pc_value is not none, set the PC register to that value (happens with jump-like instructions)
    if pc_value:
        cpu.register[TokenType.REGISTER_PC] = pc_value
    # Otherwise up the program counter by one
    else:
        cpu.register[TokenType.REGISTER_PC] += 1

    # Check if a display is supplied
    if display:
        if display.draw(cpu):
            raise DisplayClosed(None, "Display has been closed")

    # call the runner recursively
    return runner(cpu, parsed_tokens, display)
Beispiel #36
0
  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()
Beispiel #37
0
class TestCallOpcodes(unittest.TestCase):
    def setUp(self):
        self.cpu = Cpu(MMU())
        self.cpu.mmu.rom = [0] * 128
        self.cpu.mmu.load('C:/Users/cjpowell/workspace/Python/gbpy/resources/test_file.gb')
        self.cpu.mmu.rom[0] = 0x1
        self.cpu.mmu.rom[1] = 0xed
        self.cpu.registers.sp = 0xfffe

    def test_standard_call(self):
        self.cpu._op_cd()
        self.assertEqual(self.cpu.registers.sp, 0xfffc)
        self.assertEqual(self.cpu.registers.pc, 1)
        self.cpu._op_cd()
        self.assertEqual(self.cpu.registers.sp, 0xfffa)
        self.assertEqual(self.cpu.registers.pc, 0xed)

    def test_call_if(self):
        self.cpu._op_c4()
        self.cpu._op_cc()
        self.cpu._op_d4()
        self.cpu._op_dc()
        self.assertTrue(False)
Beispiel #38
0
class TestJumpOpcodes(unittest.TestCase):
    def setUp(self):
        self.cpu = Cpu(MMU())
        self.cpu.mmu.rom = [0] * 128
        self.cpu.mmu.load('C:/Users/cjpowell/workspace/Python/gbpy/resources/test_file.gb')

    def test_jump_to_addr_nn(self):
        self.cpu._op_c3()
        self.assertEqual(self.cpu.registers.pc, 0xff00)

    def test_jump_to_addr_if(self):
        self.cpu._op_c2()
        self.assertEqual(self.cpu.registers.pc, 0xff00)
        self.assertEqual(self.cpu.registers.zero_flag, 0)

        self.cpu.registers.pc = 0
        self.cpu.registers.zero_flag = 1
        self.cpu._op_ca()
        self.assertEqual(self.cpu.registers.pc, 0xff00)

        self.cpu.registers.pc = 0
        self.cpu._op_d2()
        self.assertEqual(self.cpu.registers.pc, 0xff00)
        self.assertEqual(self.cpu.registers.carry_flag, 0)

        self.cpu.registers.pc = 0
        self.cpu.registers.carry_flag = 1
        self.cpu._op_da()
        self.assertEqual(self.cpu.registers.pc, 0xff00)

    def test_jump_to_address_in_HL(self):
        self.cpu.registers.h = 0
        self.cpu.registers.l = 0x41
        self.cpu._op_e9()
        self.assertEqual(self.cpu.registers.pc, 0x24)

    def test_jump_to_addr_add_n(self):
        self.cpu._op_18()
        self.assertEqual(self.cpu.registers.pc, 0xff)

    def test_jump_to_add_add_n_if(self):
        self.cpu._op_20()
        self.assertEqual(self.cpu.registers.pc, 0xff)
        self.assertEqual(self.cpu.registers.zero_flag, 0)

        self.cpu.registers.pc = 0
        self.cpu.registers.zero_flag = 1
        self.cpu._op_28()
        self.assertEqual(self.cpu.registers.pc, 0xff)

        self.cpu.registers.pc = 0
        self.cpu._op_30()
        self.assertEqual(self.cpu.registers.pc, 0xff)
        self.assertEqual(self.cpu.registers.carry_flag, 0)

        self.cpu.registers.pc = 0
        self.cpu.registers.carry_flag = 1
        self.cpu._op_38()
        self.assertEqual(self.cpu.registers.pc, 0xff)
Beispiel #39
0
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
Beispiel #40
0
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()

Beispiel #41
0
class Pynes:
  def __init__(self):
    self._running = True
    self._display_surf = None
    self.size = self.width, self.height = 512, 448

  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 on_event(self, event):
    if event.type == pygame.QUIT:
      self._running = False
  
  def on_loop(self):
    if self.cpu.registers['pc'] in BREAKPOINTS:
      raise Exception("Breakpoint at {0:#4x}".format(self.cpu.registers['pc']))
    self.cpu.tick() 
    nmi = self.ppu.tick()
    if nmi:
      self.cpu.interrupt('NMI')

  def on_render(self):
    pass

  def on_cleanup(self):
    pygame.quit()
  
  def on_execute(self):
    if self.on_init() == False:
      self._running = False

    while( self._running ):
      for event in pygame.event.get():
        self.on_event(event)
      self.on_loop()
      self.on_render()
    self.on_cleanup()
Beispiel #42
0
def test_same_page():
    a1 = 0x3244
    a2 = 0x3256
    assert Cpu.same_page(a1, a2)
Beispiel #43
0
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]))

Beispiel #44
0
#*   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)

Beispiel #45
0
 def _init_cpu(self):
     bus = Bus(self._memory)
     self.cpu = Cpu(bus)
     self.cpu.pc = 0x200
     self.gen = self.cpu.start()
Beispiel #46
0
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()
Beispiel #47
0
class TestRetOpcodes(unittest.TestCase):
    def setUp(self):
        self.cpu = Cpu(MMU())
        self.cpu.mmu.rom = [0] * 128
        self.cpu.mmu.load('C:/Users/cjpowell/workspace/Python/gbpy/resources/test_file.gb')

    def test_standard_return(self):
        self.cpu._op_c9()
        self.assertTrue(False)

    def test_return_if(self):
        self.cpu._op_c0()
        self.cpu._op_c8()
        self.cpu._op_d0()
        self.cpu._op_d8()
        self.assertTrue(False)

    def test_return_enable_interrupts(self):
        self.cpu._op_d9()
        self.assertTrue(False)
Beispiel #48
0
class TestArithmeticOpcodes(unittest.TestCase):
    def setUp(self):
        self.cpu = Cpu(MMU())
        self.cpu.mmu.rom = [0] * 128
        self.cpu.mmu.load('C:/Users/cjpowell/workspace/Python/gbpy/resources/test_file.gb')

    def test_registers_0_at_init(self):
        self.assertEqual(0, self.cpu.registers.a)
        self.assertEqual(0, self.cpu.registers.b)
        self.assertEqual(0, self.cpu.registers.c)
        self.assertEqual(0, self.cpu.registers.d)
        self.assertEqual(0, self.cpu.registers.e)
        self.assertEqual(0, self.cpu.registers.h)
        self.assertEqual(0, self.cpu.registers.l)

    def test_flags_0_at_init(self):
        self.assertEqual(0, self.cpu.registers.carry_flag)
        self.assertEqual(0, self.cpu.registers.hc_flag)
        self.assertEqual(0, self.cpu.registers.zero_flag)
        self.assertEqual(0, self.cpu.registers.sub_flag)

    def test_direct_add(self):
        self.cpu.registers.b = 0
        self.cpu.registers.c = 15  # should trip sub flag
        self.cpu.registers.d = 255  # should trip carry flag, sub flag reset
        self.cpu.registers.e = 7
        self.cpu.registers.h = 234 # should trip zero flag

        self.cpu._op_80()
        self.assertEqual(self.cpu.registers.a, 0)
        self.assertListEqual([1, 0, 0, 0], self.cpu.flags())

        self.cpu.registers.a = 1
        self.cpu._op_81()
        self.assertEqual(self.cpu.registers.a, 16)
        self.assertListEqual([0, 0, 1, 0], self.cpu.flags())

        self.cpu._op_82()
        self.assertEqual(self.cpu.registers.a, 15)
        self.assertListEqual([0, 0, 0, 1], self.cpu.flags())

        self.cpu._op_83()
        self.cpu._op_84()
        self.assertEqual(self.cpu.registers.a, 0)
        self.assertListEqual([1, 0, 1, 1], self.cpu.flags())

    def test_direct_adc(self):
        self.cpu.registers.b = 0
        self.cpu.registers.c = 15  # should trip sub flag
        self.cpu.registers.d = 255  # should trip carry flag, sub flag reset
        self.cpu.registers.e = 7
        self.cpu.registers.h = 233  # should trip zero flag

        self.cpu._op_88()
        self.assertEqual(self.cpu.registers.a, 0)
        self.assertListEqual([1, 0, 0, 0], self.cpu.flags())

        self.cpu.registers.a = 1
        self.cpu._op_89()
        self.assertEqual(self.cpu.registers.a, 16)
        self.assertListEqual([0, 0, 1, 0], self.cpu.flags())

        self.cpu._op_8a()
        self.assertEqual(self.cpu.registers.a, 15)
        self.assertListEqual([0, 0, 0, 1], self.cpu.flags())

        self.cpu._op_8b()
        self.cpu._op_8c()
        self.assertEqual(self.cpu.registers.a, 0)
        self.assertListEqual([1, 0, 1, 1], self.cpu.flags())

    def test_indirect_add(self):
        self.cpu._op_86()
        self.assertEqual(self.cpu.registers.a, 0xff)
        self.assertEqual(self.cpu.registers.hc_flag, 0)

        self.cpu._op_c6()
        self.assertEqual(self.cpu.registers.a, 0xfe)
        self.assertEqual(self.cpu.registers.carry_flag, 1)
        self.assertEqual(self.cpu.registers.hc_flag, 1)

    def test_indirect_adc(self):
        self.cpu.registers.a = 1
        self.cpu.registers.sub_flag = 1
        self.cpu._op_8e()
        self.assertEqual(self.cpu.registers.a, 0)
        self.assertEqual(self.cpu.registers.zero_flag, 1)
        self.assertEqual(self.cpu.registers.sub_flag, 0)
        self.assertEqual(self.cpu.registers.carry_flag, 1)
        self.assertEqual(self.cpu.registers.hc_flag, 1)

        self.cpu._op_ce()
        self.assertEqual(self.cpu.registers.a, 1)
        self.assertEqual(self.cpu.registers.zero_flag, 0)
        self.assertEqual(self.cpu.registers.carry_flag, 0)
        self.assertEqual(self.cpu.registers.hc_flag, 0)

    def test_direct_sub(self):
        self.cpu.registers.a = 1
        self.cpu.registers.b = 1
        self.cpu.registers.c = 1
        self.cpu._op_90()
        self.assertEqual(self.cpu.registers.sub_flag, 1)
        self.assertEqual(self.cpu.registers.zero_flag, 1)

        self.cpu._op_91()

    def test_direct_sbc(self):
        self.cpu.registers.b = 1
        self.cpu._op_98()
        self.assertEqual(self.cpu.registers.a, 0xff)
        self.assertEqual(self.cpu.registers.sub_flag, 1)
        self.assertEqual(self.cpu.registers.zero_flag, 0)
        self.assertEqual(self.cpu.registers.carry_flag, 1)
        self.assertEqual(self.cpu.registers.hc_flag, 1)

    def test_indirect_sub(self):
        self.cpu.registers.a = 0xff
        self.cpu._op_96()
        self.assertEqual(self.cpu.registers.a, 0)
        self.assertEqual(self.cpu.registers.zero_flag, 1)
        self.assertEqual(self.cpu.registers.sub_flag, 1)

        self.cpu._op_96()
        self.assertEqual(self.cpu.registers.a, 0x01)
        self.assertEqual(self.cpu.registers.zero_flag, 0)
        self.assertEqual(self.cpu.registers.sub_flag, 1)
        self.assertEqual(self.cpu.registers.hc_flag, 1)
        self.assertEqual(self.cpu.registers.carry_flag, 1)

        self.cpu.registers.a = 0xff
        self.cpu.registers.pc = 0  # Just to be sure
        self.cpu._op_d6()  # subtracts value in memory at location of current PC from A
        self.assertEqual(self.cpu.registers.a, 0)
        self.assertEqual(self.cpu.registers.pc, 1)
        self.assertEqual(self.cpu.registers.zero_flag, 1)
        self.assertEqual(self.cpu.registers.sub_flag, 1)
        self.assertEqual(self.cpu.registers.carry_flag, 0)
        self.assertEqual(self.cpu.registers.hc_flag, 0)

    def test_indirect_sbc(self):
        self.cpu._op_9e()
        self.assertEqual(self.cpu.registers.a, 0x01)
        self.assertEqual(self.cpu.registers.carry_flag, 1)
        self.assertEqual(self.cpu.registers.hc_flag, 1)
        self.assertEqual(self.cpu.registers.zero_flag, 0)
        self.assertEqual(self.cpu.registers.sub_flag, 1)

        self.cpu.registers.pc = 1
        self.cpu._op_de()
        self.assertEqual(self.cpu.registers.a, 0)  # Carry flag is set, so 1-1 = 0
        self.assertEqual(self.cpu.registers.carry_flag, 0)
        self.assertEqual(self.cpu.registers.zero_flag, 1)
        self.assertEqual(self.cpu.registers.hc_flag, 0)
        self.assertEqual(self.cpu.registers.sub_flag, 1)


    def test_increment(self):
        self.cpu._op_04()
        self.assertEqual(self.cpu.registers.b, 1)

        self.cpu.registers.c = 0xf
        self.cpu._op_0c()
        self.assertEqual(self.cpu.registers.c, 0x10)
        self.assertEqual(self.cpu.registers.hc_flag, 1)
        self.cpu._op_34()
        self.assertEqual(self.cpu.registers.zero_flag, 1)
        self.assertEqual(self.cpu.registers.hc_flag, 1)

    def test_decrement(self):
        self.cpu.registers.b = 1
        self.cpu._op_05()
        self.assertEqual(self.cpu.registers.b, 0)
        self.assertEqual(self.cpu.registers.zero_flag, 1)
        self.assertEqual(self.cpu.registers.sub_flag, 1)

        self.assertEqual(self.cpu.mmu.rom[0], 0xff)
        self.cpu._op_35()
        self.assertEqual(self.cpu.mmu.rom[0], 0xfe)
Beispiel #49
0
    
    print "\nCAPTURING"
    print "  b [address] \n\tSet one or more brakepoints."
    print "  \tIf no address given a list of all breakpoints is displayed.\n"
    print "  d[elete] <nr> \n\tDeletes breakpoint number <nr>.\n"
    print "  w[watch] <register> \n\tTriggers changes in a register specified."
    print "  \tIf no register is specified lists all watchpoints set.\n"
    print "  dw <nr> \n\tDeletes watchpoint number <nr>.\n"
    

def print_no_cpu():
    print "No cpu loaded."

print "AUA interactive debugging shell 0.1"

c = Cpu()
c.load("../../as/boot")
input = readline.get_line_buffer()
while len(input) == 0 or input[0] != "q":
    
    if len(input) > 0:
        
        if input[0] == "b":
            if len(input) > 1:
                c.add_breakpoint(input[1:])
            else:
                breakpoints = c.list_breakpoints()
                if len(breakpoints) > 0:
                    for i in range(len(breakpoints)):
                        print i+1, "\t", hex(breakpoints[i])
                        
Beispiel #50
0
 def setUp(self):
     self.cpu = Cpu(MMU())
     self.cpu.mmu.rom = [0] * 128
     self.cpu.mmu.load('C:/Users/cjpowell/workspace/Python/gbpy/resources/test_file.gb')
Beispiel #51
0
class TestLogicalArithmeticOpcodes(unittest.TestCase):
    def setUp(self):
        self.cpu = Cpu(MMU())
        self.cpu.mmu.rom = [0] * 128
        self.cpu.mmu.load('C:/Users/cjpowell/workspace/Python/gbpy/resources/test_file.gb')

    def test_direct_xor(self):
        self.cpu._op_a8()
        self.assertEqual(self.cpu.registers.a, 0)
        self.assertEqual(self.cpu.registers.zero_flag, 1)

        self.cpu.registers.b = 0xf
        self.cpu._op_a8()
        self.assertEqual(self.cpu.registers.a, 0xf)
        self.assertEqual(self.cpu.registers.zero_flag, 0)

        self.cpu.registers.b = 0x5f
        self.cpu._op_a8()
        self.assertEqual(self.cpu.registers.a, 0x50)

    def test_indirect_xor(self):
        self.cpu._op_ae()
        self.assertEqual(self.cpu.registers.a, 0xff)
        self.assertEqual(self.cpu.registers.zero_flag, 0)

        self.cpu._op_ae()
        self.assertEqual(self.cpu.registers.a, 0)
        self.assertEqual(self.cpu.registers.zero_flag, 1)

    def test_direct_or(self):
        self.cpu.registers.b = 0
        self.cpu._op_b0()
        self.assertEqual(self.cpu.registers.a, 0)
        self.assertEqual(self.cpu.registers.zero_flag, 1)

        self.cpu.registers.b = 0x8
        self.cpu._op_b0()
        self.assertEqual(self.cpu.registers.a, 0x8)
        self.assertEqual(self.cpu.registers.zero_flag, 0)

        self.cpu.registers.b = 0xf7
        self.cpu._op_b0()
        self.assertEqual(self.cpu.registers.a, 0xff)

    def test_indirect_or(self):
        self.cpu._op_b6()
        self.assertEqual(self.cpu.registers.a, 0xff)
        self.assertEqual(self.cpu.registers.zero_flag, 0)

        self.cpu._op_b6()
        self.assertEqual(self.cpu.registers.a, 0xff)

    def test_and(self):
        self.cpu.registers.b = 0xf
        self.cpu._op_a0()
        self.assertEqual(self.cpu.registers.a, 0)
        self.assertEqual(self.cpu.registers.zero_flag, 1)

        self.cpu.registers.a = 0xff
        self.cpu._op_a6()
        self.assertEqual(self.cpu.registers.a, 0xff)
        self.assertEqual(self.cpu.registers.zero_flag, 0)

        self.cpu.registers.pc = 1
        self.cpu._op_e6()
        self.assertEqual(self.cpu.registers.a, 0)
        self.assertEqual(self.cpu.registers.zero_flag, 1)
        self.assertEqual(self.cpu.registers.pc, 2)

    def test_compare(self):
        self.cpu._op_b8()
        self.assertEqual(self.cpu.registers.a, 0)
        self.assertEqual(self.cpu.registers.zero_flag, 1)
        self.assertEqual(self.cpu.registers.carry_flag, 0)

        self.cpu._op_be()
        self.assertEqual(self.cpu.registers.zero_flag, 0)
        self.assertEqual(self.cpu.registers.carry_flag, 1)
        self.assertEqual(self.cpu.registers.hc_flag, 1)

        self.cpu.registers.a = 0xff
        self.cpu._op_fe()
        self.assertEqual(self.cpu.registers.zero_flag, 1)
        self.assertEqual(self.cpu.registers.carry_flag, 0)
Beispiel #52
0
class TestLoadOpcodes(unittest.TestCase):
    def setUp(self):
        self.cpu = Cpu(MMU())
        self.cpu.mmu.rom = [0] * 128
        self.cpu.mmu.load('C:/Users/cjpowell/workspace/Python/gbpy/resources/test_file.gb')

    def test_direct_load(self):
        self.cpu.registers.b = 10

        self.cpu._op_48()
        self.assertEqual(self.cpu.registers.b, self.cpu.registers.c)
        self.assertEqual(self.cpu.registers.c, 10)

    def test_indirect_load_HL(self):
        self.cpu.registers.h = 0x0
        self.cpu.registers.l = 0x0
        self.cpu._op_46()
        self.assertEqual(self.cpu.registers.b, 0xff)  # All GB roms will start with this reset op

    def test_indirect_load_PC(self):
        # Reads from memory at address stored in pc (next byte read)
        self.cpu.registers.pc = 0x0
        self.cpu._op_06()
        self.assertEqual(self.cpu.registers.b, 0xff)  # roms begin with 0xff and that is what we are at.
        self.assertEqual(self.cpu.registers.pc, 0x01)  # pc should increment, as we read next value for load

    def test_indirect_load_inc(self):
        self.cpu._op_22()
        self.assertEqual(self.cpu.registers.a, 0xff)
        self.assertEqual(self.cpu.registers.l, 1)
        self.assertEqual(self.cpu.registers.h, 0)

        self.cpu.registers.l = 0xff
        self.cpu._op_22()
        self.assertEqual(self.cpu.registers.l, 0)
        self.assertEqual(self.cpu.registers.h, 1)

    def test_indirect_load_dec(self):
        self.cpu.registers.l = 1
        self.cpu._op_32()
        self.assertEqual(self.cpu.registers.a, 0)
        self.assertEqual(self.cpu.registers.l, 0)

        self.cpu._op_32()
        self.assertEqual(self.cpu.registers.a, 0xff)
        self.assertEqual(self.cpu.registers.l, 0xff)
        self.assertEqual(self.cpu.registers.h, 0xff)
Beispiel #53
0
class TestShiftAndRotateOpcodes(unittest.TestCase):
    def setUp(self):
        self.cpu = Cpu(MMU())
        self.cpu.mmu.rom = [0] * 128
        self.cpu.mmu.load('C:/Users/cjpowell/workspace/Python/gbpy/resources/test_file.gb')

    def test_rlca(self):
        self.cpu.registers.a = 0x80  # 1000 0001
        self.cpu._op_07()
        self.assertEqual(self.cpu.registers.a, 1)
        self.assertEqual(self.cpu.registers.carry_flag, 1)
        self.assertEqual(self.cpu.registers.zero_flag, 0)

    def test_rla(self):
        self.cpu.registers.a = 0x80
        self.cpu._op_17()
        self.assertEqual(self.cpu.registers.a, 0)
        self.assertEqual(self.cpu.registers.carry_flag, 1)
        self.assertEqual(self.cpu.registers.zero_flag, 1)

    def test_rrca(self):
        self.cpu.registers.a = 1
        self.cpu._op_0f()
        self.assertEqual(self.cpu.registers.a, 0x80)
        self.assertEqual(self.cpu.registers.carry_flag, 1)
        self.assertEqual(self.cpu.registers.zero_flag, 0)

    def test_rra(self):
        self.cpu.registers.a = 1
        self.cpu._op_1f()
        self.assertEqual(self.cpu.registers.a, 0x0)
        self.assertEqual(self.cpu.registers.carry_flag, 1)
        self.assertEqual(self.cpu.registers.zero_flag, 1)

    def test_rlc(self):
        # TODO: part of extended opcodes
        self.assertTrue(False)

    def test_rl(self):
        # TODO: part of extended opcodes
        self.assertTrue(False)

    def test_rrc(self):
        # TODO: part of extended opcodes
        self.assertTrue(False)

    def test_rr(self):
        # TODO: part of extended opcodes
        self.assertTrue(False)

    def test_sla(self):
        # TODO: part of extended opcodes
        self.assertTrue(False)

    def test_sra(self):
        # TODO: part of extended opcodes
        self.assertTrue(False)

    def test_srl(self):
        # TODO: part of extended opcodes
        self.assertTrue(False)
Beispiel #54
0
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)
Beispiel #55
0
class CpuTest(unittest.TestCase):

    def setUp(self):
        self.mManager = Mock()
        self.mHandler = Mock()
        self.cpu = Cpu(self.mManager,self.mHandler)
        self.aPcb = Mock()
        when(self.aPcb).getPid().thenReturn(0)
        when(self.aPcb).basePointer().thenReturn(0)
        when(self.aPcb).programCounter().thenReturn(0)
        when(self.aPcb).size().thenReturn(0)
        when(self.aPcb).displazament().thenReturn(0)
        self.instruction = Mock()

    def test_changeRoundRobin(self):
        self.cpu.changeRoundRobin(8)
        assert (self.cpu.roundRobin == 8)

    def test_pcIncrease(self):
        self.cpu.currentPcb = self.aPcb
        self.cpu.pcIncrease()
        verify(self.aPcb).pcIncrease()

    def test_assignPcb(self):
        self.cpu.assignPcb(self.aPcb)
        assert (self.cpu.currentPcb == self.aPcb)

    def test_removePcb(self):
        self.cpu.currentPcb = self.aPcb
        self.cpu.removePcb()
        assert (self.cpu.currentPcb == None)

    def test_havePcbWithPcb(self):
        self.cpu.currentPcb = self.aPcb
        assert (self.cpu.havePcb())

    def test_havePcbWithOutPcb(self):
        self.assertFalse(self.cpu.havePcb())

    def test_executeWithFullQuantum(self):

        when(self.cpu).getCurrentPcb().thenReturn(self.aPcb)

        when(self.cpu).getMemory().thenReturn(self.mManager)
        when(self.mManager).getInstruction(self.aPcb.getPid(),self.aPcb.getDisplacement()).thenReturn(self.instruction)

        when(self.instruction).execute().thenReturn(False)
        when(self.instruction).isIOInstruction().thenReturn(False)
        self.cpu.quantum = 1
        self.cpu.execute()

        verify(self.cpu.handler,times(1)).toWait(self.aPcb)
        verify(self.cpu.handler,times(0)).toKill(self.aPcb)
        verify(self.cpu.handler,times(0)).toIO(self.aPcb)
        assert self.cpu.quantum == 0


    def test_executeWithOutFullQuantum(self):

        when(self.cpu).getCurrentPcb().thenReturn(self.aPcb)

        when(self.cpu).getMemory().thenReturn(self.mManager)
        when(self.mManager).getInstruction(self.aPcb.getPid(),self.aPcb.getDisplacement()).thenReturn(self.instruction)

        when(self.instruction).execute().thenReturn(False)
        when(self.instruction).isIOInstruction().thenReturn(False)
        self.cpu.execute()

        verify(self.aPcb).pcIncrease()
        verify(self.cpu.handler,times(0)).toWait(self.aPcb)
        verify(self.cpu.handler,times(0)).toKill(self.aPcb)
        verify(self.cpu.handler,times(0)).toIO(self.aPcb)
        assert self.cpu.quantum == 1

    def test_executeWithKillIntruction(self):

        when(self.cpu).getCurrentPcb().thenReturn(self.aPcb)

        when(self.cpu).getMemory().thenReturn(self.mManager)
        when(self.mManager).getInstruction(self.aPcb.getPid(),self.aPcb.getDisplacement()).thenReturn(self.instruction)

        when(self.instruction).execute().thenReturn(True)
        when(self.instruction).isIOInstruction().thenReturn(False)
        self.cpu.execute()

        verify(self.cpu.handler,times(0)).toWait(self.aPcb)
        verify(self.cpu.handler,times(1)).toKill(self.aPcb)
        verify(self.cpu.handler,times(0)).toIO(self.aPcb)
        assert self.cpu.quantum == 0

    def test_executeWithIOIntruction(self):

        when(self.cpu).getCurrentPcb().thenReturn(self.aPcb)

        when(self.cpu).getMemory().thenReturn(self.mManager)
        when(self.mManager).getInstruction(self.aPcb.getPid(),self.aPcb.getDisplacement()).thenReturn(self.instruction)

        when(self.instruction).execute().thenReturn(False)
        when(self.instruction).isIOInstruction().thenReturn(True)
        self.cpu.execute()

        verify(self.cpu.handler,times(0)).toWait(self.aPcb)
        verify(self.cpu.handler,times(0)).toKill(self.aPcb)
        verify(self.cpu.handler,times(1)).toIOInput(self.aPcb)
        assert self.cpu.quantum == 0 
Beispiel #56
0
class Orion(QWidget):
    def __init__(self):
        super(Orion, self).__init__()
        self.ui = Ui_window()
        self.ui.setupUi(self)
        self.ui.tableWidget.setHorizontalHeaderLabels(['Endereço', 'Palavra'])
        self._memory = Memory()
        load_program(self._memory)
        self.ui.tableWidget.setRowCount(len(self._memory))
        self._init_cpu()
        self._fill_table()
        self._connect_edits()
        self.ui.pushButtonNext.clicked.connect(self.next_cpu)
        self.ui.tableWidget.itemChanged.connect(self._update_word)

    def next_cpu(self):
        try:
            info = self.gen.send(None)
            self.ui.lineEditStatus.setText(info)
            self.ui.lineEditPC.setText(hex(self.cpu.pc))
            self.ui.lineEditIR.setText(hex(self.cpu.ir))
            self.ui.lineEditAH.setText(hex(self.cpu.ula.ah))
            self.ui.lineEditBH.setText(hex(self.cpu.ula.bh))
            self.ui.lineEditAC.setText(hex(self.cpu.ula.ac))
            self.ui.lineEditAX.setText(hex(self.cpu.ax))
            self.ui.lineEditBX.setText(hex(self.cpu.bx))
            self.ui.lineEditCX.setText(hex(self.cpu.cx))
            self.ui.lineEditDX.setText(hex(self.cpu.dx))
            self.ui.lineEditSTS.setText(bin(self.cpu.sts))
            self.ui.lineEditInstruction.setText(instrucoes[self.cpu.ir])
            if self.cpu.ir == 0x8:
                self._update_table()
            self._select_row(hex(self.cpu.pc))
        except StopIteration:
            QMessageBox.information(self, "Orion", "Execução Finalizada")

    def _init_cpu(self):
        bus = Bus(self._memory)
        self.cpu = Cpu(bus)
        self.cpu.pc = 0x200
        self.gen = self.cpu.start()

    def _fill_table(self):
        for i in range(1, len(self._memory)):
            item_endereco = QTableWidgetItem(hex(i))
            item_endereco.setFlags(item_endereco.flags() ^ Qt.ItemIsEditable)
            data = self._memory.operate(i, None, 0)
            if data is not None:
                data = hex(data)
            item_palavra = QTableWidgetItem(data)
            self.ui.tableWidget.setItem(i-1, 0, item_endereco)
            self.ui.tableWidget.setItem(i-1, 1, item_palavra)

    def _update_table(self):
        for i in range(1, len(self._memory)):
            item_palavra = self.ui.tableWidget.item(i-1, 1)
            data = self._memory.operate(i, None, 0)
            if data is not None:
                data = hex(data)
            item_palavra.setText(data)

    def _select_row(self, pc):
        item = self.ui.tableWidget.findItems(pc, Qt.MatchExactly)[0]
        self.ui.tableWidget.selectRow(item.row())
        self.ui.tableWidget.scrollToItem(item)

    def _update_word(self, item):
        self.cpu.bus.transfer(int(self.ui.tableWidget.item(item.row(), 0).text(), 16), int(item.text(), 16), 1)

    def _connect_edits(self):
        self.ui.lineEditAH.editingFinished.connect(self._update_register)
        self.ui.lineEditBH.editingFinished.connect(self._update_register)
        self.ui.lineEditAC.editingFinished.connect(self._update_register)

    def _update_register(self):
        sender = self.sender().objectName()
        value = int(self.sender().text(), 16)
        if sender == 'lineEditAH':
            self.cpu.ula.ah = value
        elif sender == 'lineEditBH':
            self.cpu.ula.bh = value
        elif sender == 'lineEditAC':
            self.cpu.ula.ac = value
Beispiel #57
0
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)