9 //typedef int (clock_func_t) (void);
10 static int fetch_and_decode_inst(void);
11 static int decode_inst(void);
12 static int execute_inst(void);
13 static int reset_handler1(void);
14 static int reset_handler2(void);
16 #define NMI_ADDR 0xFFFA
17 #define RESET_ADDR 0xFFFC
18 #define IRQ_BRK_ADDR 0xFFFE
20 int decode6502(unsigned char inst);
21 int execute6502(void);
22 int test_and_set_exec(void);
24 int init_6502core(void);
26 void pc_set(unsigned short addr);
27 unsigned short pc_get(void);
28 void pc_move(int offset);
31 void set_rw_pin(int rw);
33 static unsigned char cpu_data_buffer;
34 static unsigned short cpu_addr_buffer;
37 * clock execution function array.
38 * max execution cycle is 7.
39 * the last element must be NULL.
41 clock_func_t *execute_func;
43 static unsigned long clock_cnt;
46 int get_clock_cnt(void) {
57 //dprint("%d\n", clock_cnt);
65 unsigned char load_memory(unsigned short addr) {
70 cpu_data_buffer = get_bus_data();
73 return cpu_data_buffer;
76 void store_memory(unsigned short addr, unsigned char data) {
84 cpu_addr_buffer = addr;
85 cpu_data_buffer = data;
89 * load address in the memory.
90 * loading 2 bytes takes 2 cycles.
91 * the parameter "cycle" means first or second read.
93 unsigned short load_addr(unsigned short addr, int cycle) {
94 unsigned char byte = load_memory(addr);
96 ///NES=little endian. lower byte first, higher byte second.
98 cpu_addr_buffer = byte;
100 cpu_addr_buffer |= byte << 8;
101 return cpu_addr_buffer;
104 void reset_cpu(void) {
106 execute_func = reset_handler1;
109 static int reset_handler1(void) {
110 load_addr(RESET_ADDR, 1);
111 execute_func = reset_handler2;
115 static int reset_handler2(void) {
116 load_addr(RESET_ADDR + 1, 2);
117 pc_set(cpu_addr_buffer);
119 execute_func = fetch_and_decode_inst;
123 static int decode_inst(void) {
126 ret = decode6502(cpu_data_buffer);
131 static int fetch_and_decode_inst(void) {
136 void break_hit(void);
138 void dump_6502(int full);
139 extern int debug_mode;
140 extern unsigned short break_point;
141 extern int dbg_log_msg;
142 extern int critical_error;
147 if (break_point == pc) {
168 fprintf(stderr, "cpu decode instruction failure.\n");
171 critical_error = TRUE;
177 execute_func = execute_inst;
183 static int execute_inst(void) {
187 void dump_6502(int full);
188 extern int critical_error;
190 //dprint("execute\n");
192 //execute the instruction
197 fprintf(stderr, "cpu execute instruction failure.\n");
202 critical_error = TRUE;
207 //last cycle goes to next execute cycle
208 if (test_and_set_exec()) {
209 execute_func = fetch_and_decode_inst;
214 void set_cpu_addr_buf(unsigned short addr) {
215 cpu_addr_buffer = addr;
218 unsigned short get_cpu_addr_buf(void) {
219 return cpu_addr_buffer;
222 void set_cpu_data_buf(unsigned char data) {
223 cpu_data_buffer = data;
226 unsigned char get_cpu_data_buf(void) {
227 return cpu_data_buffer;
233 ret = init_6502core();
238 ret = register_clock_hander(clock_cpu);