-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcpu.rkt
2251 lines (2013 loc) · 90.3 KB
/
cpu.rkt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#lang racket
(require (for-syntax syntax/parse racket/syntax racket/format racket/base)
racket/draw)
(provide
;; Emulation
run ; run until STOP
continue ; continue from STOP
step ; single step
;; Memory
load load2 store mem-dump
;; Registers
A X Y PC S C Z V
;; Assembler
assembler traditional->assembler assembler->traditional
install-opcodes-from-assembler
;; Other
split-string-into-lines hex hex$ bin bin%)
;;;
;;; References
;;;
;;; Opcode reference:
;;; http://www.6502.org/tutorials/6502opcodes.html#SBC
;;; Opcode reference and pseudo code from Vice:
;;; http://nesdev.com/6502.txt
;;;
;;; SETTINGS
;;;
(define video-type 'pal)
;;;
;;; TODO
;;;
; - implement sbc
; Extend tradional->assembler to handle comments
; The +1 extra cycle for page boundary crossings needs to be handled.
; Finish the assembler. I.e. support labels and symbols.
; Tests ...
; Load files from other assemblers
; Load and save rom files.
; Memory banks
; Support the unsupported opcodes:
; ALR: A:=(A and #{imm})/2;
; ANC: A:=A and #{imm}; Generates opcode $0B.
; ARR: A:=(A and #{imm})/2;
; AXS: X:=A and X-#{imm};
; DCP: {adr}:={adr}-1; A-{adr};
; ISC: {adr}:={adr}+1; A:=A-{adr};
; LAS: A,X,S:={adr} and S;
; LAX: A,X:={adr};
; RLA: {adr}:={adr}rol; A:=A and {adr};
; RRA: {adr}:={adr}ror; A:=A adc {adr};
; SAX: {adr}:=A and X;
; SLO: {adr}:={adr}*2; A:=A or {adr};
; SRE: {adr}:={adr}/2; A:=A xor {adr};
;;;
;;; SYNTAX UTILITIES
;;;
(module utils racket
(provide symbol-downcase symbol-upcase syntax-downcase syntax-upcase)
(define (convert s f)
(if (syntax? s)
(convert (syntax-e s) f)
(string->symbol (f (symbol->string s)))))
(define (symbol-downcase s) (convert s string-downcase))
(define (symbol-upcase s) (convert s string-upcase))
(define (syntax-downcase ctx stx-sym)
(datum->syntax ctx (symbol-downcase (syntax-e stx-sym))))
(define (syntax-upcase ctx stx-sym)
(datum->syntax ctx (symbol-upcase (syntax-e stx-sym)))))
(require (submod "." utils))
(begin-for-syntax
(require (submod "." utils))
(define (format-ids locs fmt vss)
(for/list ([vs (syntax->list vss)] [loc (syntax->list locs)])
(apply format-id loc fmt (syntax->list vs)))))
;;;
;;; BITS AND BYTES
;;;
(define bitand bitwise-and)
(define bitor bitwise-ior)
(define bitxor bitwise-xor)
(define (bitasl n) (arithmetic-shift n 1))
(define (bitlsr n) (arithmetic-shift n -1)) ; introduces 0 as msb
(define byte-masks #(1 2 4 8 16 32 64 128))
(define negated-byte-masks (for/vector ([b byte-masks]) (- 255 b)))
(define (bit-clear? b pos) (zero? (bitand b (vector-ref byte-masks pos))))
(define (bit-set? b pos) (not (zero? (bitand b (vector-ref byte-masks pos)))))
(define (bit-clear b pos) (bitand b (vector-ref negated-byte-masks pos)))
(define (bit-set b pos) (bitor b (vector-ref byte-masks pos)))
(define (low bits) (bitwise-and bits #xff)) ; returns the low 8 bits
(define (high bits) (arithmetic-shift bits -8)) ; returns the high 8 bits
(define (bit-ref bits pos) (byte>> (bitwise-and bits (vector-ref byte-masks pos)) pos))
(define (byte-msb? b) (not (zero? (bitand b #b10000000))))
(define (byte-set-msb b) (bitor b #b10000000))
(define (byte-clear-msb b) (bitand b #b01111111))
(define (byte-set-lsb b) (bitor b #b00000001))
(define (byte-clear-lsb b) (bitand b #b11111110))
(define (byte-inc b) (if (= b 255) 0 (+ b 1)))
(define (byte-dec b) (if (= b 0) 255 (- b 1)))
(define (byte-pos? b) (not (byte-msb? b)))
(define (byte-neg? b) (byte-msb? b))
(define (byte-neg b) (byte (bitxor b #xff))) ; negation
(define (byte-zero? b) (= b 0))
(define (byte-one? b) (= b 1))
(define (byte n) (bitand n #xFF))
(define (byte+ b c) (bitand (+ b c) #xFF))
(define (byte- b c) (bitand (- b c) #xFF)) ; todo check this!
(define (byte-or b c) (bitand (bitor b c) #xFF))
(define (byte-xor b c) (bitand (bitxor b c) #xFF))
(define (byte-and b c) (bitand (bitand b c) #xFF))
(define (byte-asl b) (bitand (bitasl b) #xFF))
(define (byte-lsr b) (bitand (bitlsr b) #xFF))
(define (byte-rol b c?) (if c? (byte-set-lsb (byte-asl b)) (byte-asl b)))
(define (byte-ror b c?) (if c? (byte-set-msb (byte-lsr b)) (byte-lsr b)))
(define (byte<< b n) (arithmetic-shift b n))
(define (byte>> b n) (arithmetic-shift b (- n)))
(define (byte-lower-nibble b) (bitand b #b00001111))
(define (byte-upper-nibble b) (arithmetic-shift b -4))
(define (nibbles->byte u l) (byte-or (arithmetic-shift u 4) l))
(define (word hi lo) (+ (* hi 256) lo))
(define (word+ w1 w2) (bitand (+ w1 w2) #xFFFF))
(define (word- w1 w2) (bitand (- w1 w2) #xFFFF))
(define (word>> w n) (arithmetic-shift w (- n)))
(define (word-and b c) (bitand (bitand b c) #xFFFF))
(define (word-msb w) (word>> w 8))
(define (word-lsb w) (word-and w #xFF))
(define (hex2 n) (~r n #:base 16 #:min-width 2 #:pad-string "0"))
(define (hex4 n) (~r n #:base 16 #:min-width 4 #:pad-string "0"))
(define hex hex2)
(define (hex$ n) (string->symbol (string-append "$" (if (<= n #xff) (hex2 n) (hex4 n)))))
(define (bin8 n) (~r n #:base 2 #:min-width 8 #:pad-string "0"))
(define (bin16 n) (~r n #:base 2 #:min-width 16 #:pad-string "0"))
(define bin bin8)
(define (bin% n) (string->symbol (string-append "%" (if (<= n #xff) (bin8 n) (bin16 n)))))
;;;
;;; REGISTERS
;;;
(define-syntax (define-register stx)
(syntax-parse stx
[(_define-register name)
(with-syntax ([name! (format-id #'name "~a!" #'name)])
#'(begin (define name 0)
(define-syntax (name! so)
(syntax-parse so [(_name! expr) (syntax/loc so (set! name expr))]))))]))
(define-register A) ; accumulator ( 8 bit)
(define-register X) ; index register ( 8 bit)
(define-register Y) ; index register ( 8 bit)
(define-register SP) ; stack pointer ( 8 bit)
(define-register PC) ; program counter (16 bit)
(define (~registers)
(~a "A:" (hex2 A) " "
"X:" (hex2 X) " "
"Y:" (hex2 Y) " "
"SP:" (hex2 SP)))
;;;
;;; STATUS REGISTER: FLAGS
;;;
; The status register contains 8 flags.
; The status register is represented as 8 individual flags.
(define-syntax (define-flags stx)
(syntax-parse stx
[(_define-flags (name bit-number description) ...)
(with-syntax ([(name! ...) (format-ids #'(name ...) "~a!" #'((name) ...))])
#'(begin (define name 0) ...
(define (name! v) (set! name v)) ...))]))
(define-flags
(C 0 carry) ; contains the result affecting the flag (set if result<#0x100 )
(Z 1 zero) ; contains the last byte affecting the flag
(I 2 interrupt) ; boolean
(D 3 decimal-mode) ; boolean
(B 4 break) ; boolean
(U 5 unused) ; #t
(V 6 overflow) ; 0 or 1
(S 7 sign)) ; contains the last byte affecting the flag
(define (reset-status-register)
(C! #x100) (Z! 0) (I! #f) (D! #t) (B! #f) (U! #t) (V! 0) (S! 0))
; Note: The sign flag is also known as the N flag (for Negative)
(define (S?) (byte-neg? S)) ; true, if the (negative) sign is set
(define (set-S) (S! #b10000000))
(define (clear-S) (S! 0))
(define (Z?) (zero? Z)) ; true, if the zero flag is set
(define (set-Z) (Z! 0))
(define (clear-Z) (Z! 1))
(define (V?) (= V 1)) ; true, if overflow is set
(define (set-V) (V! 1))
(define (clear-V) (V! 0))
(define (C?) (< C #x100)) ; true, if the carry flag is set
(define (set-C) (C! 0))
(define (clear-C) (C! #x100))
(define (I?) I)
(define (set-I) (I! #t))
(define (clear-I) (I! #f))
(define (B?) B)
(define (set-B) (B! #t))
(define (clear-B) (B! #f))
(define (D?) D)
(define (set-D) (D! #t))
(define (clear-D) #;(D! #f) (void)) ; The 6502 in the NES doesn't support the decimal flag
; ; so .. make this void
(define (~flags)
(~a (if (C?) "C" ".")
(if (Z?) "Z" ".")
(if I "I" ".")
(if D "D" ".")
(if B "B" ".")
(if U "_" "_")
(if (V?) "V" ".")
(if (S?) "S" ".")))
(define (flags->integer)
(string->number
(string-append*
(reverse
(list (if (C?) "1" "0")
(if (Z?) "1" "0")
(if I "1" "0")
(if D "1" "0")
(if B "1" "0")
(if U "1" "0")
(if (V?) "1" "0")
(if (S?) "1" "0"))))
2))
;;;
;;; CLOCK
;;;
(define cycle-count 0)
;;;
;;; MEMORY
;;;
;; SIMPLEST MODEL: Simple 64KB address space. No memory mapped IO-registers.
;; The memory is represented as a mutable array of bytes.
; (define mem (make-bytes #x10000 0))
; (define (load a) (bytes-ref mem a))
; (define (store a v) (bytes-set! mem a v))
;;; MEMORY MAPPER
; Due to the memory mapping of the NES all loads and stores to the memory
; will go through the load and store below.
; The smallest ram chips used in the NES (and/or cartridges) are 2KB,
; so let's call a 2KB sized piece of memory a page.
(define (page) (make-vector #x800 0))
; Besides standard ram a few addresses are memory mapped.
; The PPU (graphics chip) have 8 registers that are accessed throgh
; addresses $2000-$2007.
; For now, let's represent the PPU registers as a vector.
(define ppu-registers (make-vector 8 0))
; We can change the representation later, if all access to the PPU goes through ppu-ref and ppu-set!
(define (ppu-reg-ref i) (vector-ref ppu-registers i))
(define (ppu-reg-set! i b)
(case i
[(7) (ppu-data-write b)] ; $2007 ; fast path
[(0) ;(displayln (list 'ppu-ctrl (bin b)) (current-error-port))
(vector-set! ppu-registers i b)] ; $2000
[(3) ;(displayln (list 'ppu-oam-addr (bin b)) (current-error-port))
(vector-set! ppu-registers i b)]
[(4) ;(displayln (list 'ppu-oam-data (bin b)) (current-error-port))
(vector-set! ppu-registers i b)]
; [(1) (ppu-mask-set! b)] ; $2001
; [(2) (ppu-status-set! b)] ; $2002
; [(3) (ppu-oam-addr! b)] ; $2003
; [(4) (ppu-oam-data! b)] ; $2004
; [(5) (ppu-scroll-set! b)] ; $2005
[(6) (ppu-addr-write b)] ; $2006
[else (vector-set! ppu-registers i b)]))
; The actual memory layout depends on which chips are present in the cartridge.
; However there are 2KB internal ram (i.e. not on a cartridge) at the beginning
; of the address space. Further more page 2, 3, and, 4 are mirrors of that first page.
; The first page is internal ram.
; The following pages are mirrors of the first page.
(define page0 (page)) ; $0000 - $0800
(define page1 page0) ; $0800 - $0FFF 2KB mirror of $0-$7FF
(define page2 page0) ; $1000 - $17FF 2KB mirror of $0-$7FF
(define page3 page0) ; $1800 - $1FFF 2KB mirror of $0-$7FF
(define memmap
(vector page0 page1 page2 page3 ; $0000 - $1FFF
#f #f #f #f ; $2000 - $3FFF PPU
#f (page) (page) (page) ; $4000 - $5FFF APU + IO + more
(page) (page) (page) (page) ; $6000 - $7FFF
(page) (page) (page) (page) ; $8000 - $9FFF
(page) (page) (page) (page) ; $A000 - $BFFF
(page) (page) (page) (page) ; $C000 - $DFFF
(page) (page) (page) (page))) ; $E000 - $FFFF
(define (make-$C000-$FFFF-a-mirror-of-$8000-BFFF)
; If the prg rom is only 16KB then it needs to be mirrored.
(for ([i (in-range 8)])
(vector-set! memmap (+ 24 i) (vector-ref memmap (+ 16 i)))))
(define (load a) ; retrieve the byte value stored at address a
(define bank (word>> a 11)) ; upper 5 bits = the bank number
(define page (vector-ref memmap bank)) ; the memmap maps bank to page
(cond
[page (vector-ref page (word-and a #b11111111111))] ; index = lower 11 bits
[(<= 4 bank 7) (ppu-reg-ref (word-and a #b111))] ; index of PPU register = lower 3 bits
[(= bank 8) (cond
[(= a #x4017) 1] ; JOY 1 ; XXX TODO
[else 0])] ; we will ignore the APU for the time being
[else (error 'load "unexpected ")])) ; no other banks need special treatment
(define (store a b) ; store the byte value b at address a
(define bank (word>> a 11))
(define page (vector-ref memmap bank))
(cond
[page (vector-set! page (word-and #b11111111111 a) b)]
[(<= 4 bank 7) (ppu-reg-set! (word-and a #b111) b)]
[(= bank 8) (void)]
[else (error 'store "unexpected ")]))
(define (load2 a) (word (load (+ a 1)) (load a)))
(define (load2bug a) (word (load (word (high a) (byte+ a 1))) (load a)))
(define (push! v) (store (+ #x100 SP) v) (SP! (byte- SP 1)))
(define (pull!) (SP! (byte+ SP 1)) (load (+ #x100 SP)))
(define (on-zero-page? adr) (< adr 256))
;;;
;;; PPU - Picture Processing Unit
;;;
; The PPU is the graphics chip. It is a small CPU that runs in parallel with the main CPU.
; The PPU has a 16KB ram chip. This ram is refered to as video ram.
; The address space of the PPU is
; A ppu page is 256 bytes.
(define ppu-page-size 256)
(define (ppu-page) (make-vector ppu-page-size 0))
(define ppu-memmap (make-vector (/ (* 64 1024) ppu-page-size) #f)) ; the address space is 64kb
(define ppu-palettes (ppu-page))
(define (ppu-reset)
; allocate pages and put them into the memmap
(define (install-ram from-address to-address)
(for ([i (in-range (/ from-address ppu-page-size)
(/ to-address ppu-page-size))])
(vector-set! ppu-memmap i (ppu-page))))
; make memap entries point to already existing pages (thus introducing mirroring)
(define (mirror-range from-address to-address source)
(define src (/ source ppu-page-size))
(for ([i (in-range (/ from-address ppu-page-size)
(/ to-address ppu-page-size))]
[j (in-naturals)])
(vector-set! ppu-memmap i (vector-ref ppu-memmap (+ src j)))))
(install-ram #x0000 #x2000) ; Pattern Tables
(install-ram #x2000 #x3F00) ; Name Tables
; #x3F00 #x4000 ; Palettes (needs special handling)
(mirror-range #x3000 #x3F00 #x2000) ; Mirrors of name tables
(mirror-range #x4000 #x10000 #x0000) ; Mirrors bottom 16KB (four times)
; From https://wiki.nesdev.com/w/index.php/PPU_power_up_state
; Initial Register Values
; Register At Power After Reset
; PPUCTRL ($2000) 0000 0000 0000 0000
; XXX
; PPUMASK ($2001) 0000 0000 0000 0000
; PPUSTATUS ($2002) +0+x xxxx U??x xxxx
; OAMADDR ($2003) $00 unchanged1
; $2005 / $2006 latch cleared cleared
; PPUSCROLL ($2005) $0000 $0000
; PPUADDR ($2006) $0000 unchanged
; PPUDATA ($2007) read buffer $00 $00
; odd frame no no
; OAM pattern pattern
; NT RAM (external, in Control Deck) mostly $FF unchanged
; CHR RAM (external, in Game Pak) unspecified pattern unchanged
)
; The palettes are only from $3F00 to $3F1F.
; The range $3F20-$3FFF mirrors $3F00-$3F1F, but since that's within a page,
; this needs to be handled in the load and store. We store #f in the
; memory map to indicate special handling.
(define (ppuload a) ; retrieve the byte value stored at address a
(define bank (word>> a 8)) ; upper 8 bits = the bank number
(define page (vector-ref ppu-memmap bank)) ; the memmap has the page of the bank
(if page
(vector-ref page (word-and a #b11111111)) ; lower 8 bits = position in page
(vector-ref ppu-palettes (word-and a #b00011111)))) ; $0-$1f is 5 bits
(define (ppustore a b) ; store the byte b at address a
; (displayln (list 'ppustore a b) (current-error-port))
(define bank (word>> (word-and #b1111111100000000 a) 8)) ; upper 8 bits = the bank number
(define page (vector-ref ppu-memmap bank)) ; the memmap has the page of the bank
(if page
(vector-set! page (word-and a #b11111111) b) ; lower 8 bits = position in page
(vector-set! ppu-palettes (word-and a #b00011111) b))) ; $0-$1f is 5 bits
(ppu-reset)
;;;
;;; Addressing Modes
;;;
; EXAMPLES
(define immediate 0) ; LDA #$20
(define zero-page 1) ; LDA $20
(define zero-page-x 2) ; LDA $20,x
(define zero-page-y 3) ; LDX $20,y
(define absolute 4) ; LDA $1234
(define absolute-x 5) ; LDA $1234,x
(define absolute-y 6) ; LDA $1234,y
(define indirect 7) ; JMP ($1234) (JMP only)
(define indirect-x 8) ; LDA ($44,x)
(define indirect-y 9) ; LDA ($44),y
(define relative 10) ; BNE label
(define implied 11) ; BRK
(define accumulator 12) ; ROL A
(define todo 13)
;;;
;;; FETCH/DECODE/EXECUTE
;;;
(define opcode-modes (make-bytes 256 todo))
(define opcode-sizes (make-bytes 256 0))
(define opcode-cycles (make-bytes 256 0))
(define opcode-handlers (for/vector ([i 256]) (λ _ (error 'opcode-handler (opcode-handler-error i)))))
(define (opcode-handler-error i) (~a "The opcode handler for opcode " i " has not been defined"))
(define trace-fuel 0)
(define (trace [n 10]) (set! trace-fuel n))
(define (step)
;; TODO handle interrupts here? Note - use exceptions and handle it in run.
; Note: The 6502 increments the PC first, then fetches the instruction
;;; Uddate PC
(PC! (word+ PC 1)) ; increment pc
(unless (zero? trace-fuel)
(displayln (disassemble-single PC))
(set! trace-fuel (- trace-fuel 1)))
(when (zero? trace-fuel) (raise 'done))
(define pc PC) ; save old pc
;;; Fetch
(define opcode (load PC)) ; fetch opcode
;;; Decode
(define mode (bytes-ref opcode-modes opcode)) ; find adressing mode
(define size (bytes-ref opcode-sizes opcode)) ; instruction size
(define cycles (bytes-ref opcode-cycles opcode)) ; clock cycles needed
(define handle (vector-ref opcode-handlers opcode)) ; does the work
(set! cycle-count (+ cycle-count cycles)) ; increment clock
;;; Execute
(define effective-operand
; todo: order these in most-used-first order
(cond ; ; ***EXAMPLES***
[(= mode immediate) (+ pc 1)] ; LDA #$20
[(= mode zero-page) (load (+ pc 1))] ; LDA $20
[(= mode zero-page-x) (byte+ X (load (+ pc 1)))] ; LDA $20,x
[(= mode zero-page-y) (byte+ Y (load (+ pc 1)))] ; LDX $20,y (LDX, STX only)
[(= mode absolute) (load2 (+ pc 1))] ; LDA $1234
[(= mode absolute-x) (word+ X (load2 (+ pc 1)))] ; LDA $1234,x
[(= mode absolute-y) (word+ Y (load2 (+ pc 1)))] ; LDA $1234,y
[(= mode indirect) (load2bug (load2 (+ pc 1)))] ; JMP ($1234) (JMP only)
[(= mode indirect-x) (load2bug (word+ X (load (+ pc 1))))] ; LDA ($44,x)
[(= mode indirect-y) (word+ Y (load2bug (load (+ pc 1))))] ; LDA ($44),y
[(= mode relative) (let ([offset (load (+ pc 1))]) ; BNE label
; (displayln (list 'pc pc 'offset offset))
(if (byte-neg? offset)
(+ pc +1 offset (- #x100))
(+ pc +1 offset)))]
[(= mode implied) #f] ; BRK
[(= mode accumulator) #f] ; ROL A
[else (error 'step (~a "Unhandled mode: " mode " Opcode: " opcode))]))
;;; Update PC before calling handler
(when (> size 1) (PC! (word+ PC (- size 1))))
(handle effective-operand)
#;(displayln (~a " "
"P:" (number->string (flags->integer) 16) " " (~flags) " "
(~registers)))
cycles)
;;;
;;; OPCODES / INSTRUCTIONS
;;;
; Main references used for the instruction table:
; http://www.6502.org/tutorials/6502opcodes.html
; The remaining (undocumented) opcodes are still missing:
; http://visual6502.org/wiki/index.php?title=6502_all_256_Opcodes
(define-syntax affects (syntax-rules ())) ; used as keyword
(define opcode-to-instruction-name-ht (make-hash)) ; for the disassembler
(define mnemonic-to-mode-to-opcode-ht (make-hash)) ; for the assembler
(define (register-mnemonic! mne mode opcode)
(define (register mne)
(define mode-to-opcode-ht (or (hash-ref mnemonic-to-mode-to-opcode-ht mne #f)
(let ([ht (make-hash)])
(hash-set! mnemonic-to-mode-to-opcode-ht mne ht)
ht)))
(hash-set! mode-to-opcode-ht mode opcode))
(register (symbol-downcase mne))
(register (symbol-upcase mne)))
(define (mnemonic+mode->opcode mne mode)
(define ht (hash-ref mnemonic-to-mode-to-opcode-ht mne))
(hash-ref ht mode))
(define (has-mode? mne mode)
(let ([mode-to-opcode-ht (hash-ref mnemonic-to-mode-to-opcode-ht mne #f)])
(and mode-to-opcode-ht
(hash-ref mode-to-opcode-ht mode #f)
#t)))
(define (opcode->mnemonic opcode)
(hash-ref opcode-to-instruction-name-ht opcode #f))
(define (reset)
; http://www.pagetable.com/?p=410
; Reset vector: $FFFC/$FFFD
(PC! (load2 #xFFFC)))
(define (run start-address)
(reset-status-register)
(PC! (- start-address 1))
(SP! #xff) ; note: sp=$ff means address $01ff
(continue))
(define nmi-due-to-vblank? #f)
(define (continue)
(let loop ()
;(display "C")
; generate NMI due to vblank?
(when nmi-due-to-vblank?
; (displayln 'NMI (current-error-port))
(set! nmi-due-to-vblank? #f)
(handle-nmi))
; business as usual
(let cpu-loop ([fuel 113])
(unless (zero? fuel)
(step)
(cpu-loop (- fuel 1))))
;(display "P")
(ppu-step 1364)
(loop)))
(define-syntax (define-opcodes stx)
(define-syntax-class mnemonic
(pattern mnemonic:id #:with name (syntax-upcase stx #'mnemonic)))
(define-syntax-class opcode-specification
(pattern (mode opcode size cycles) #:with extra-cycles #'0)
(pattern (mode opcode size cycles extra) #:with extra-cycles #'extra))
(define-syntax-class flag
#:literals (C Z I D B V S)
(pattern (~or C Z I D B V S)))
(syntax-parse stx
#:literals (affects)
[(_define-opcodes register-opcode-handlers
(NAME:mnemonic (affects f:flag ...) (spec:opcode-specification ...)) ...)
#'(begin
(let ([name 'NAME.name])
(hash-set! opcode-to-instruction-name-ht spec.opcode name) ...
(bytes-set! opcode-sizes spec.opcode spec.size) ...
(bytes-set! opcode-cycles spec.opcode spec.cycles) ...
(bytes-set! opcode-modes spec.opcode spec.mode) ...
(register-mnemonic! name spec.mode spec.opcode) ...)
...
(define (register-opcode-handlers)
(let ([Name NAME.name]) (vector-set! opcode-handlers spec.opcode Name) ...)
...))]))
(define-opcodes
register-opcode-handlers ; use this after all instructions are defined
(STOP (affects) ((implied #xff 1 1))) ; fake instruction - emulator only
(ADC ; Add with carry
(affects S V Z C)
; (mode hex size cycles extra-cycle-on-page-crossed
((immediate #x69 2 2)
(zero-page #x65 2 3)
(zero-page-x #x75 2 4)
(absolute #x6d 3 4)
(absolute-x #x7d 3 4 1) ; 1 means extra cycle
(absolute-y #x79 3 4 1) ; on crossed page boundary
(indirect-x #x61 2 6)
(indirect-y #x71 2 5 1)))
(AND ; bitwise and with accumulator
(affects S Z)
((immediate #x29 2 2)
(zero-page #x25 2 3)
(zero-page-x #x35 2 4)
(absolute #x2d 3 4)
(absolute-x #x3d 3 4 1)
(absolute-y #x39 3 4 1)
(indirect-x #x21 2 6)
(indirect-y #x31 2 5 1)))
(ASL ; arithmetic shift left
(affects S Z C)
((accumulator #x0a 1 2)
(zero-page #x06 2 5)
(zero-page-x #x16 2 6)
(absolute #x0e 3 6)
(absolute-x #x1e 3 7)))
(BIT ; test bits
(affects S V Z)
((zero-page #x24 2 3)
(absolute #x2c 3 4)))
;;; BRANCH INSTRUCTIONS
;;; branch not taken: 2 cycles
;;; branch taken: 3 cycles
;;; +1 if page boundary crossed
(BPL (affects) ((relative #x10 2 2 1))) ; plus
(BMI (affects) ((relative #x30 2 2 1))) ; minus
(BVC (affects) ((relative #x50 2 2 1))) ; overflow clear
(BVS (affects) ((relative #x70 2 2 1))) ; overflow set
(BCC (affects) ((relative #x90 2 2 1))) ; carry clear
(BCS (affects) ((relative #xb0 2 2 1))) ; carry set
(BNE (affects) ((relative #xd0 2 2 1))) ; not equal
(BEQ (affects) ((relative #xf0 2 2 1))) ; equal
(BRK ; Break - causes non-maskable interupt
(affects B)
((implied #x00 1 7)))
(CMP ; compare accumulator
(affects S Z C)
((immediate #xc9 2 2)
(zero-page #xc5 2 3)
(zero-page-x #xd5 2 4)
(absolute #xcd 3 4)
(absolute-x #xdd 3 4 1)
(absolute-y #xd9 3 4 1)
(indirect-x #xc1 2 6)
(indirect-y #xd1 2 5 1)))
(CPX ; compare X register
(affects S Z C)
((immediate #xe0 2 2)
(zero-page #xe4 2 3)
(absolute #xec 3 4)))
(CPY ; compare Y register
(affects S Z C)
((immediate #xc0 2 2)
(zero-page #xc4 2 3)
(absolute #xcc 3 4)))
(DEC ; decrement memory
(affects S Z)
((zero-page #xc6 2 5)
(zero-page-x #xd6 2 6)
(absolute #xce 3 6)
(absolute-x #xde 3 7)))
(INC ; increment memory
(affects S Z)
((zero-page #xe6 2 5)
(zero-page-x #xf6 2 6)
(absolute #xee 3 6)
(absolute-x #xfe 3 7)))
(EOR ; bitwise exclusive or
(affects S Z)
((immediate #x49 2 2)
(zero-page #x45 2 3)
(zero-page-x #x55 2 4)
(absolute #x4d 3 4)
(absolute-x #x5d 3 4 1)
(absolute-y #x59 3 4 1)
(indirect-x #x41 2 6)
(indirect-y #x51 2 5 1)))
;;; STATUS / FLAG INSTRUCTIONS
(CLC (affects C) ((implied #x18 1 2))) ; clear carry
(SEC (affects C) ((implied #x38 1 2))) ; set carry
(CLI (affects I) ((implied #x58 1 2))) ; clear interrupt
(SEI (affects I) ((implied #x78 1 2))) ; set interrupt
(CLV (affects V) ((implied #xb8 1 2))) ; clear overflow
(CLD (affects D) ((implied #xd8 1 2))) ; clear decimal
(SED (affects D) ((implied #xf8 1 2))) ; set decimal
(JMP ; jump
(affects)
((absolute #x4c 3 6)
(indirect #x6c 3 5)))
(JSR ; jump to subroutine
(affects)
((absolute #x20 3 6)))
(LDA ; load accumulator
(affects S Z)
((immediate #xa9 2 2)
(zero-page #xa5 2 3)
(zero-page-x #xb5 2 4)
(absolute #xad 3 4)
(absolute-x #xbd 3 4 1)
(absolute-y #xb9 3 4 1)
(indirect-x #xa1 2 6)
(indirect-y #xb1 2 5 1)))
(LDX ; load X register
(affects S Z)
((immediate #xa2 2 2)
(zero-page #xa6 2 3)
(zero-page-y #xb6 2 4)
(absolute #xae 3 4)
(absolute-y #xbe 3 4 1)))
(LDY ; load Y register
(affects S Z)
((immediate #xa0 2 2)
(zero-page #xa4 2 3)
(zero-page-x #xb4 2 4)
(absolute #xac 3 4)
(absolute-x #xbc 3 4 1)))
(LSR ; logical shift right
(affects S Z C)
((accumulator #x4a 1 2)
(zero-page #x46 2 5)
(zero-page-x #x56 2 6)
(absolute #x4e 3 6)
(absolute-x #x5e 3 7)))
(NOP ; no operation
(affects)
((implied #xea 1 2)))
(ORA ; bitwise or with accumulator
(affects S Z)
((immediate #x09 2 2)
(zero-page #x05 2 3)
(zero-page-x #x15 2 4)
(absolute #x0d 3 4)
(absolute-x #x1d 3 4 1)
(absolute-y #x19 3 4 1)
(indirect-x #x01 2 6)
(indirect-y #x11 2 5 1)))
;;; REGISTER INSTRUCTIONS
(TAX (affects S Z) ((implied #xaa 1 2))) ; transfer a to x
(TXA (affects S Z) ((implied #x8a 1 2))) ; transfer x to a
(DEX (affects S Z) ((implied #xca 1 2))) ; decrement x
(INX (affects S Z) ((implied #xe8 1 2))) ; increment x
(TAY (affects S Z) ((implied #xa8 1 2))) ; transfer a to y
(TYA (affects S Z) ((implied #x98 1 2))) ; transfer y to a
(DEY (affects S Z) ((implied #x88 1 2))) ; decrement y
(INY (affects S Z) ((implied #xc8 1 2))) ; increment y
(ROL ; rotate left
(affects S Z C)
((accumulator #x2a 1 2)
(zero-page #x26 2 5)
(zero-page-x #x36 2 6)
(absolute #x2e 3 6)
(absolute-x #x3e 3 7)))
(ROR ; rotate right
(affects S Z C)
((accumulator #x6a 1 2)
(zero-page #x66 2 5)
(zero-page-x #x76 2 6)
(absolute #x6e 3 6)
(absolute-x #x7e 3 7)))
(RTI ; return from interrupt
(affects C Z I D B V S)
((implied #x40 1 6)))
(RTS ; return from subroutine
(affects)
((implied #x60 1 6)))
(SBC ; subtract with carry
(affects S V Z C)
((immediate #xe9 2 2)
(zero-page #xe5 2 3)
(zero-page-x #xf5 2 4)
(absolute #xed 3 4)
(absolute-x #xfd 3 4 1)
(absolute-y #xf9 3 4 1)
(indirect-x #xe1 2 6)
(indirect-y #xf1 2 5 1)))
(STA ; store accumulator
(affects)
((zero-page #x85 2 3)
(zero-page-x #x95 2 4)
(absolute #x8d 3 4)
(absolute-x #x9d 3 5)
(absolute-y #x99 3 5)
(indirect-x #x81 2 6)
(indirect-y #x91 2 6)))
;;; STACK INSTRUCTIONS
; TODO: look up flags affected
(TXS (affects) ((implied #x9a 1 2))) ; transfer X to SP
(TSX (affects) ((implied #xba 1 2))) ; transfer SP to X
(PHA (affects) ((implied #x48 1 3))) ; push A
(PLA (affects) ((implied #x68 1 4))) ; pull A
(PHP (affects) ((implied #x08 1 3))) ; push status
(PLP (affects) ((implied #x28 1 4))) ; pull status
(STX ; store X register
(affects)
((zero-page #x86 2 3)
(zero-page-y #x96 2 4)
(absolute #x8e 3 4)))
(STY ; store Y register
(affects)
((zero-page #x84 2 3)
(zero-page-x #x94 2 4)
(absolute #x8c 3 4))))
;;;
;;; INSTRUCTIONS
;;;
;;; Reference: http://www.6502.org/tutorials/6502opcodes.html
(define-syntax (define-instruction stx)
(define-syntax-class mnemonic
(pattern mnemonic:id #:with name (syntax-upcase stx #'mnemonic)))
(syntax-parse stx
; Most adressing modes result in a an adress adr
[(_define-instruction (mne:mnemonic adr) . body)
#'(define (mne.name adr) #;(displayln (list 'mne adr)) . body)]
; The addression mode "implied" has no adress.
[(_define-instruction (mne:mnemonic) . body)
#'(define (mne.name) #;(displayln (list 'mne)) . body)]))
; TODO: Handle cycles on branch operations
(define-syntax (extra-cycle stx) (syntax-parse stx [(_extra-cycle) #'(void)]))
;;; EMULATOR ONLY
(define-instruction (stop a) (raise 'stop)) ; stop emulation
;;; MOVE INSTRUCTIONS
(define-instruction (sta a) (store a A))
(define-instruction (stx a) (store a X))
(define-instruction (sty a) (store a Y))
(define-instruction (lda a) (let ([v (load a)]) (A! v) (S! v) (Z! v)))
(define-instruction (ldx a) (let ([v (load a)]) (X! v) (S! v) (Z! v)))
(define-instruction (ldy a) (let ([v (load a)]) (Y! v) (S! v) (Z! v)))
(define-instruction (tax _) (X! A) (S! X) (Z! X))
(define-instruction (tay _) (Y! A) (S! Y) (Z! Y))
(define-instruction (txa _) (A! X) (S! A) (Z! A))
(define-instruction (tya _) (A! Y) (S! A) (Z! A))
(define-instruction (pla _) (let ([v (pull!)]) (A! v) (S! v) (Z! v)))
(define-instruction (tsx _) (let ([v (pull!)]) (X! v) (S! v) (Z! v)))
(define-instruction (pha _) (push! A))
(define-instruction (txs _) (push! X))
(define-instruction (bit a) (let ([v (load a)])
(S! v)
(if (= (byte-and v #b01000000) #b01000000) (V! 1) (V! 0))
(Z! (byte-and v A))))
;;; LOGICAL AND ARITHMETICAL
(define-instruction (ora a) (let ([v (byte-or A (load a))]) (A! v) (S! v) (Z! v)))
(define-instruction (and a) (let ([v (byte-and A (load a))]) (A! v) (S! v) (Z! v)))
(define-instruction (eor a) (let ([v (byte-xor A (load a))]) (A! v) (S! v) (Z! v)))
(define-instruction (cmp a) (let ([v (byte- A (load a))]) (C! v) (S! v) (Z! v)))
(define-instruction (cpx a) (let ([v (byte- X (load a))]) (C! v) (S! v) (Z! v)))
(define-instruction (cpy a) (let ([v (byte- Y (load a))]) (C! v) (S! v) (Z! v)))
(define-instruction (dex _) (let ([v (byte-dec X)]) (X! v) (S! v) (Z! v)))
(define-instruction (inx _) (let ([v (byte-inc X)]) (X! v) (S! v) (Z! v)))
(define-instruction (dey _) (let ([v (byte-dec Y)]) (Y! v) (S! v) (Z! v)))
(define-instruction (iny _) (let ([v (byte-inc Y)]) (Y! v) (S! v) (Z! v)))
(define-instruction (dec a) (let ([v (byte-dec (load a))]) (store a v) (S! v) (Z! v)))
(define-instruction (inc a) (let ([v (byte-inc (load a))]) (store a v) (S! v) (Z! v)))
(define-instruction (adc a) (adc-body (load a)))
(define-instruction (sbc a) (adc-body (byte-neg (load a))))
(define (adc-body v)
; Note: The NES doesn't support decimal mode, so the D flag is ignored.
; Formulas for overflow flag:
; http://www.righto.com/2012/12/the-6502-overflow-flag-explained.html
(let* ([c (if (C?) 1 0)]
[t (+ A v c)]
[s (byte t)])
(if (> t #xff) (set-C) (clear-C))
; TODO : Use one of the efficient formulas for V instead
(V! (if (or (and (byte-neg? A) (byte-neg? v) (byte-pos? s))
(and (byte-pos? A) (byte-pos? v) (byte-neg? s)))
1 0))
(A! s)
(Z! s)
(S! t)))
(define-instruction (ror a)
(let* ([v (if a (load a) A)]
[w (byte-ror v (C?))])
(if (odd? v) (set-C) (clear-C))
(S! w)
(Z! w)
(if a (store a w) (A! w))))
(define-instruction (rol a)
(let* ([v (if a (load a) A)]
[w (byte-rol v (C?))])
(if (byte-msb? v) (set-C) (clear-C))
(S! w)
(Z! w)
(if a (store a w) (A! w))))
(define-instruction (lsr a)
(let* ([v (if a (load a) A)]
[w (byte-lsr v)])
(if (odd? v) (set-C) (clear-C))
(S! w)
(Z! w)
(if a (store a w) (A! w))))
(define-instruction (asl a)
(let* ([v (if a (load a) A)]
[w (byte-asl v)])
(if (byte-msb? v) (set-C) (clear-C))
(S! w)
(Z! w)
(if a (store a w) (A! w))))
;;; CONTROL
; Note: When the addressing mode is relative, a is the pc+displacement
(define-instruction (bpl a) (unless (S?) (PC! a)))
(define-instruction (bmi a) (when (S?) (PC! a)))
(define-instruction (bvc a) (when (= V 0) (PC! a)))
(define-instruction (bvs a) (when (= V 1) (PC! a)))
(define-instruction (bcc a) (unless (C?) (PC! a)))
(define-instruction (bcs a) (when (C?) (PC! a)))
(define-instruction (bne a) (unless (Z?) (PC! a)))
(define-instruction (beq a) (when (Z?) #;(displayln (list 'HERE 'PC PC 'a a)) (PC! a)))
(define-instruction (brk _)
(let ([pc+2 (+ PC 2)] ; todo: only +1 here?
[sr ; status register as integer
(+ (if (C?) 1 0)
(if (Z?) 2 0)
(if (I?) 4 0)
(if (D?) 8 0) ; D = 1 on the NES
16 ; B = 1 when PHP or BRK is used
32 ; U, unused, that is, always set
(if (V?) 64 0)
(if (S?) 128 0))])
(push! (high pc+2))
(push! (low pc+2))
(push! sr)
(set-B) ; set break flag
(PC! (word- (word (load #xFFFF) (load #xFFFE)) 1))))
(define (handle-nmi)
(let ([pc (+ PC 1)] ; RTI will subtract 1
[sr ; status register as integer
(+ (if (C?) 1 0)
(if (Z?) 2 0)
(if (I?) 4 0)
(if (D?) 8 0) ; D = 1 on the NES
0 ; B = 1 when PHP or BRK is used
32 ; U, unused, that is, always set
(if (V?) 64 0)
(if (S?) 128 0))])
(push! (high pc))
(push! (low pc))
(push! sr)
; (set-B) ; set break flag
(PC! (word- (word (load #xFFFB) (load #xFFFA)) 1))))
(define-instruction (rti _); (affects C Z I D B V S)
(let ([sr (pull!)] [l (pull!)] [h (pull!)])
(if (bit-clear? sr 0) (clear-C) (set-C))
(if (bit-clear? sr 1) (clear-Z) (set-Z))
(if (bit-clear? sr 2) (clear-I) (set-I))
; (if (bit-clear? sr 3) (clear-D) (set-D)) ; not on the NES
(if (bit-clear? sr 4) (clear-B) (set-B))
; (if (bit-clear? sr 5) (clear-U) (set-U)) ; unused flag always 1
(if (bit-clear? sr 6) (clear-V) (set-V))
(if (bit-clear? sr 7) (clear-S) (set-S))
(PC! (- (word h l) 1))))
; TODO: check that we are in fact pushing the correct PC
(define-instruction (jmp a) (PC! (- a 1))) ; this must match handling of pc in step
(define-instruction (jsr a) (push! (high PC)) (push! (low PC)) (PC! (- a 1)))
(define-instruction (rts _) (let ([l (pull!)] [h (pull!)]) (PC! (word h l))))
(define-instruction (nop _) (void))
;;; STATUS REGISTER
(define-instruction (clc _) (clear-C))
(define-instruction (sec _) (set-C))