rsemu 0.0.4

A multiplatform emulator in pure Rust, built bottom-up on a generic framework.
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
//! Hand-written tests for the MC68000 core.
//!
//! The conformance corpus next door covers instruction semantics far more
//! thoroughly than anything written by hand could; what lives here is what the
//! corpus does *not* reach — reset, interrupts, the privilege split, the trace
//! bit, the prefetch queue's invariant, and the snapshot round trip.

use alloc::sync::Arc;
use alloc::vec::Vec;

use crate::core::device::Device;
use crate::core::error::Result;
use crate::core::space::{AddressSpace, RamStore, Region};
use crate::core::state::{MachineShape, Migrations, StateReader, StateWriter};
use crate::core::value::Endian;

use super::{CLASS, Config, M68k, Reg, Regs, flags, isa, vector};

/// A 68000 with 64 KiB of big-endian RAM and nothing else.
struct Board {
    cpu: Arc<M68k>,
    ram: Arc<RamStore>,
}

impl Board {
    fn new() -> Board {
        let ram = Arc::new(RamStore::new(0x1_0000));
        let space = AddressSpace::new("cpu", 24).with_endian(Endian::Big);
        space
            .topology()
            .map(Region::ram("ram", ram.clone()).with_endian(Endian::Big), 0)
            .expect("64 KiB fits in 24 bits");
        let cpu = Arc::new(M68k::new(Config::default()));
        cpu.attach_space(Arc::new(space));
        Board { cpu, ram }
    }

    fn poke_word(&self, addr: u64, value: u16) {
        self.ram.write_u8(addr, (value >> 8) as u8).unwrap();
        self.ram.write_u8(addr + 1, value as u8).unwrap();
    }

    fn poke_long(&self, addr: u64, value: u32) {
        self.poke_word(addr, (value >> 16) as u16);
        self.poke_word(addr + 2, value as u16);
    }

    fn peek_word(&self, addr: u64) -> u16 {
        (u16::from(self.ram.read_u8(addr).unwrap()) << 8)
            | u16::from(self.ram.read_u8(addr + 1).unwrap())
    }

    fn peek_long(&self, addr: u64) -> u32 {
        (u32::from(self.peek_word(addr)) << 16) | u32::from(self.peek_word(addr + 2))
    }

    /// Assemble `words` at `$400`, point the reset vector at it, and run the
    /// reset sequence.
    fn boot(&self, words: &[u16]) {
        self.poke_long(0, 0x2000);
        self.poke_long(4, 0x0400);
        for (i, word) in words.iter().enumerate() {
            self.poke_word(0x400 + 2 * i as u64, *word);
        }
        self.cpu.step();
    }
}

#[test]
fn reset_loads_the_stack_pointer_and_program_counter() {
    let board = Board::new();
    board.boot(&[0x4e71]);
    let regs = board.cpu.regs();
    assert_eq!(regs.ssp, 0x2000);
    assert_eq!(regs.a[7], 0x2000);
    assert_eq!(regs.pc, 0x400);
    assert!(regs.supervisor());
    assert_eq!(regs.ipl_mask(), 7);
    // Both prefetch words are loaded, which is the invariant the whole
    // interpreter rests on.
    assert_eq!(regs.prefetch[0], 0x4e71);
    assert_eq!(regs.prefetch[1], board.peek_word(0x402));
}

#[test]
fn the_prefetch_queue_holds_the_words_at_pc_and_pc_plus_two() {
    let board = Board::new();
    // NOP, NOP, MOVEQ #1,D0, NOP
    board.boot(&[0x4e71, 0x4e71, 0x7001, 0x4e71]);
    for _ in 0..3 {
        let regs = board.cpu.regs();
        assert_eq!(regs.prefetch[0], board.peek_word(u64::from(regs.pc)));
        assert_eq!(regs.prefetch[1], board.peek_word(u64::from(regs.pc) + 2));
        board.cpu.step();
    }
    assert_eq!(board.cpu.regs().d[0], 1);
}

#[test]
fn nop_costs_one_bus_cycle() {
    let board = Board::new();
    board.boot(&[0x4e71]);
    let before = board.cpu.cycles();
    let used = board.cpu.step();
    assert_eq!(used, 4, "a NOP is one prefetch and nothing else");
    assert_eq!(board.cpu.cycles() - before, 4);
}

#[test]
fn an_odd_word_access_takes_an_address_error() {
    let board = Board::new();
    // MOVE.W D0,(A0) with A0 odd.
    board.boot(&[0x3080]);
    board.poke_long(u64::from(vector::ADDRESS_ERROR) * 4, 0x0800);
    board.poke_word(0x800, 0x4e71);
    let mut regs = board.cpu.regs();
    regs.a[0] = 0x1001;
    board.cpu.set_regs(regs);
    board.cpu.step();

    let regs = board.cpu.regs();
    assert_eq!(regs.pc, 0x800, "the address-error handler was entered");
    // The fourteen-byte group-0 frame, in the layout of MC68000UM figure 6-6.
    let sp = regs.a[7];
    assert_eq!(sp, 0x2000 - 14);
    assert_eq!(board.peek_long(u64::from(sp) + 2), 0x1001, "access address");
    assert_eq!(board.peek_word(u64::from(sp) + 6), 0x3080, "instruction");
    // The special status word's low five bits describe the failed access:
    // supervisor data space, a write.
    let ssw = board.peek_word(u64::from(sp));
    assert_eq!(ssw & 0x1f, 0x05, "supervisor data, write");
}

#[test]
fn a_trap_pushes_the_six_byte_frame_and_vectors() {
    let board = Board::new();
    board.boot(&[0x4e4f]); // TRAP #15
    board.poke_long(u64::from(vector::TRAP_BASE + 15) * 4, 0x0900);
    board.poke_word(0x900, 0x4e73); // RTE
    let sr_before = board.cpu.regs().sr;
    board.cpu.step();

    let regs = board.cpu.regs();
    assert_eq!(regs.pc, 0x900);
    let sp = regs.a[7];
    assert_eq!(sp, 0x2000 - 6);
    assert_eq!(board.peek_word(u64::from(sp)), sr_before);
    assert_eq!(board.peek_long(u64::from(sp) + 2), 0x402);

    // And RTE puts everything back.
    board.cpu.step();
    let regs = board.cpu.regs();
    assert_eq!(regs.pc, 0x402);
    assert_eq!(regs.sr, sr_before);
    assert_eq!(regs.a[7], 0x2000);
}

#[test]
fn user_mode_cannot_touch_the_status_register() {
    let board = Board::new();
    board.boot(&[0x46fc, 0x2700]); // MOVE #$2700,SR
    board.poke_long(u64::from(vector::PRIVILEGE) * 4, 0x0a00);
    board.poke_word(0xa00, 0x4e71);
    let mut regs = board.cpu.regs();
    regs.sr &= !flags::S; // drop to user state
    regs.usp = 0x1800;
    board.cpu.set_regs(regs);
    assert_eq!(board.cpu.regs().a[7], 0x1800);

    board.cpu.step();
    let regs = board.cpu.regs();
    assert_eq!(regs.pc, 0xa00);
    assert!(regs.supervisor(), "the handler runs in supervisor state");
    // The frame went on the supervisor stack, and the user stack is untouched.
    assert_eq!(regs.usp, 0x1800);
    assert_eq!(regs.ssp, 0x2000 - 6);
    assert_eq!(board.peek_long(u64::from(regs.ssp) + 2), 0x400);
}

#[test]
fn the_two_stack_pointers_are_separate_registers() {
    let board = Board::new();
    board.boot(&[0x4e71]);
    let mut regs = board.cpu.regs();
    regs.sr &= !flags::S;
    regs.usp = 0x1000;
    regs.ssp = 0x2000;
    board.cpu.set_regs(regs);
    assert_eq!(board.cpu.reg(Reg::A(7)), 0x1000);

    // Returning to supervisor state swaps the bank back.
    let mut regs = board.cpu.regs();
    regs.sr |= flags::S;
    board.cpu.set_regs(regs);
    assert_eq!(board.cpu.reg(Reg::A(7)), 0x2000);
    assert_eq!(board.cpu.reg(Reg::Usp), 0x1000);
}

#[test]
fn an_illegal_encoding_traps_through_vector_four() {
    let board = Board::new();
    board.boot(&[0x4afc]); // ILLEGAL
    board.poke_long(u64::from(vector::ILLEGAL) * 4, 0x0b00);
    board.poke_word(0xb00, 0x4e71);
    board.cpu.step();
    let regs = board.cpu.regs();
    assert_eq!(regs.pc, 0xb00);
    // An illegal instruction pushes its own address, not the next one.
    assert_eq!(board.peek_long(u64::from(regs.ssp) + 2), 0x400);
}

#[test]
fn the_a_and_f_lines_have_their_own_vectors() {
    for (opcode, vec, target) in [
        (0xa000u16, vector::LINE_A, 0xc00u32),
        (0xf000, vector::LINE_F, 0xd00),
    ] {
        let board = Board::new();
        board.boot(&[opcode]);
        board.poke_long(u64::from(vec) * 4, target);
        board.poke_word(u64::from(target), 0x4e71);
        board.cpu.step();
        assert_eq!(board.cpu.regs().pc, target, "opcode {opcode:04x}");
    }
}

#[test]
fn an_interrupt_above_the_mask_is_taken_between_instructions() {
    let board = Board::new();
    board.boot(&[0x4e71, 0x4e71]);
    board.poke_long(u64::from(vector::AUTOVECTOR_BASE + 4) * 4, 0x0e00);
    board.poke_word(0xe00, 0x4e73);
    // Drop the mask so level 4 gets through.
    let mut regs = board.cpu.regs();
    regs.sr = (regs.sr & !flags::IPL) | (2 << 8);
    board.cpu.set_regs(regs);

    board.cpu.set_ipl(4);
    board.cpu.step();
    let regs = board.cpu.regs();
    assert_eq!(regs.pc, 0xe00, "the level 4 autovector");
    assert_eq!(regs.ipl_mask(), 4, "the mask rises to the level serviced");
}

#[test]
fn an_interrupt_at_or_below_the_mask_is_ignored() {
    let board = Board::new();
    board.boot(&[0x4e71]);
    let mut regs = board.cpu.regs();
    regs.sr = (regs.sr & !flags::IPL) | (5 << 8);
    board.cpu.set_regs(regs);
    board.cpu.set_ipl(5);
    board.cpu.step();
    assert_eq!(
        board.cpu.regs().pc,
        0x402,
        "the NOP ran, no vector was taken"
    );
}

#[test]
fn level_seven_is_not_maskable() {
    let board = Board::new();
    board.boot(&[0x4e71]);
    board.poke_long(u64::from(vector::AUTOVECTOR_BASE + 7) * 4, 0x0f00);
    board.poke_word(0xf00, 0x4e73);
    assert_eq!(board.cpu.regs().ipl_mask(), 7);
    board.cpu.set_ipl(7);
    board.cpu.step();
    assert_eq!(board.cpu.regs().pc, 0xf00);
}

#[test]
fn stop_waits_for_an_interrupt() {
    let board = Board::new();
    board.boot(&[0x4e72, 0x2000]); // STOP #$2000 — supervisor, mask 0
    board.poke_long(u64::from(vector::AUTOVECTOR_BASE + 1) * 4, 0x0e80);
    board.poke_word(0xe80, 0x4e73);
    board.cpu.step();
    assert!(board.cpu.is_stopped());
    // Stepping a stopped core makes time pass and nothing else.
    let pc = board.cpu.regs().pc;
    assert!(board.cpu.step() > 0);
    assert_eq!(board.cpu.regs().pc, pc);

    board.cpu.set_ipl(1);
    board.cpu.step();
    assert!(!board.cpu.is_stopped());
    assert_eq!(board.cpu.regs().pc, 0xe80);
}

#[test]
fn the_trace_bit_takes_an_exception_after_each_instruction() {
    let board = Board::new();
    board.boot(&[0x7001]); // MOVEQ #1,D0
    board.poke_long(u64::from(vector::TRACE) * 4, 0x0f80);
    board.poke_word(0xf80, 0x4e73);
    let mut regs = board.cpu.regs();
    regs.sr |= flags::T;
    board.cpu.set_regs(regs);

    board.cpu.step();
    let regs = board.cpu.regs();
    assert_eq!(regs.d[0], 1, "the instruction completed first");
    assert_eq!(regs.pc, 0xf80);
    assert!(!regs.flag(flags::T), "tracing is off inside the handler");
    assert_eq!(board.peek_long(u64::from(regs.ssp) + 2), 0x402);
}

#[test]
fn addresses_reach_the_bus_modulo_sixteen_megabytes() {
    let board = Board::new();
    // MOVE.W #$1234,($FF001000).L — the high byte has no pin to drive.
    board.boot(&[0x33fc, 0x1234, 0xff00, 0x1000]);
    board.cpu.step();
    assert_eq!(board.peek_word(0x1000), 0x1234);
}

#[test]
fn a_double_fault_halts_the_processor() {
    let board = Board::new();
    // MOVE.W D0,(A0) with A0 odd, and an address-error vector that is also
    // odd: the exception's own fetch faults, which is the double bus fault.
    board.boot(&[0x3080]);
    board.poke_long(u64::from(vector::ADDRESS_ERROR) * 4, 0x0801);
    let mut regs = board.cpu.regs();
    regs.a[0] = 0x1001;
    board.cpu.set_regs(regs);
    board.cpu.step();
    assert!(board.cpu.is_halted());
    assert_eq!(board.cpu.step(), 0, "a halted core consumes no time");
}

#[test]
fn arithmetic_sets_the_flags_the_manual_gives_it() {
    let board = Board::new();
    // ADD.W D1,D0 with $8000 + $8000: zero, overflow, carry and extend.
    board.boot(&[0xd041]);
    let mut regs = board.cpu.regs();
    regs.d[0] = 0x8000;
    regs.d[1] = 0x8000;
    board.cpu.set_regs(regs);
    board.cpu.step();
    let regs = board.cpu.regs();
    assert_eq!(regs.d[0] & 0xffff, 0);
    assert!(regs.flag(flags::Z));
    assert!(regs.flag(flags::V));
    assert!(regs.flag(flags::C));
    assert!(regs.flag(flags::X));
    assert!(!regs.flag(flags::N));
}

#[test]
fn addx_only_ever_clears_the_zero_flag() {
    let board = Board::new();
    // ADDX.W D1,D0, adding zero to zero with X clear: Z must stay as it was.
    board.boot(&[0xd141, 0xd141]);
    let mut regs = board.cpu.regs();
    regs.sr |= flags::Z;
    regs.d[0] = 0;
    regs.d[1] = 0;
    board.cpu.set_regs(regs);
    board.cpu.step();
    assert!(
        board.cpu.regs().flag(flags::Z),
        "a zero step leaves Z alone"
    );

    let mut regs = board.cpu.regs();
    regs.sr &= !flags::Z;
    board.cpu.set_regs(regs);
    board.cpu.step();
    assert!(
        !board.cpu.regs().flag(flags::Z),
        "and a clear Z stays clear, which is the point of the rule"
    );
}

#[test]
fn abcd_adds_in_decimal() {
    let board = Board::new();
    board.boot(&[0xc300]); // ABCD D0,D1
    let mut regs = board.cpu.regs();
    regs.d[0] = 0x28;
    regs.d[1] = 0x34;
    regs.sr &= !flags::X;
    regs.sr |= flags::Z;
    board.cpu.set_regs(regs);
    board.cpu.step();
    assert_eq!(board.cpu.regs().d[1] & 0xff, 0x62);
    assert!(!board.cpu.regs().flag(flags::C));
}

#[test]
fn abcd_carries_out_of_the_high_nibble() {
    let board = Board::new();
    board.boot(&[0xc300]);
    let mut regs = board.cpu.regs();
    regs.d[0] = 0x99;
    regs.d[1] = 0x01;
    regs.sr &= !flags::X;
    board.cpu.set_regs(regs);
    board.cpu.step();
    let regs = board.cpu.regs();
    assert_eq!(regs.d[1] & 0xff, 0x00);
    assert!(regs.flag(flags::C));
    assert!(regs.flag(flags::X));
}

#[test]
fn a_byte_access_through_a7_keeps_the_stack_even() {
    let board = Board::new();
    board.boot(&[0x1f00]); // MOVE.B D0,-(A7)
    board.cpu.step();
    assert_eq!(
        board.cpu.regs().a[7],
        0x2000 - 2,
        "the stack pointer steps by two even for a byte"
    );
}

#[test]
fn movem_round_trips_a_register_list() {
    let board = Board::new();
    // MOVEM.L D0-D2,-(A7) then MOVEM.L (A7)+,D5-D7
    board.boot(&[0x48e7, 0xe000, 0x4cdf, 0x00e0]);
    let mut regs = board.cpu.regs();
    regs.d[0] = 0x1111_1111;
    regs.d[1] = 0x2222_2222;
    regs.d[2] = 0x3333_3333;
    board.cpu.set_regs(regs);
    board.cpu.step();
    assert_eq!(board.cpu.regs().a[7], 0x2000 - 12);
    board.cpu.step();
    let regs = board.cpu.regs();
    assert_eq!(regs.a[7], 0x2000);
    assert_eq!(regs.d[5], 0x1111_1111);
    assert_eq!(regs.d[6], 0x2222_2222);
    assert_eq!(regs.d[7], 0x3333_3333);
}

#[test]
fn jsr_and_rts_agree_on_the_return_address() {
    let board = Board::new();
    // JSR ($0500).W ; NOP ... at $500: RTS
    board.boot(&[0x4eb8, 0x0500]);
    board.poke_word(0x500, 0x4e75);
    board.cpu.step();
    let regs = board.cpu.regs();
    assert_eq!(regs.pc, 0x500);
    assert_eq!(board.peek_long(u64::from(regs.a[7])), 0x404);
    board.cpu.step();
    assert_eq!(board.cpu.regs().pc, 0x404);
}

/// Save one core into a snapshot's `cpu` chunk.
fn snapshot(cpu: &M68k) -> Result<Vec<u8>> {
    let mut shape = MachineShape::new();
    shape.add_device("cpu", CLASS.name)?;
    let mut w = StateWriter::new(shape);
    {
        let mut chunk = w.chunk("cpu", CLASS.name, CLASS.version)?;
        cpu.save(&mut chunk)?;
    }
    w.to_vec()
}

/// Load one core out of such a snapshot.
fn restore(cpu: &M68k, bytes: &[u8]) -> Result<()> {
    let reader = StateReader::new(bytes)?;
    let chunk = reader.load("cpu", CLASS.name, CLASS.version, &Migrations::new())?;
    let mut r = chunk.reader();
    cpu.load(&mut r)?;
    r.end()
}

#[test]
fn a_snapshot_round_trips_to_an_identical_state() -> Result<()> {
    let board = Board::new();
    board.boot(&[0x7001, 0x7202, 0x4e71]);
    board.cpu.step();
    board.cpu.step();
    board.cpu.set_ipl(3);

    let bytes = snapshot(&board.cpu)?;
    let other = M68k::new(Config::default());
    restore(&other, &bytes)?;

    assert_eq!(other.regs(), board.cpu.regs());
    assert_eq!(other.cycles(), board.cpu.cycles());
    assert_eq!(other.ipl(), 3);
    // The invariant the roadmap actually asks for: a round trip is a fixed
    // point, byte for byte.
    assert_eq!(snapshot(&other)?, bytes);
    Ok(())
}

#[test]
fn a_status_register_with_impossible_bits_cannot_be_set() {
    let board = Board::new();
    board.boot(&[0x4e71]);
    let mut regs = board.cpu.regs();
    regs.sr = 0xffff;
    board.cpu.set_regs(regs);
    assert_eq!(
        board.cpu.regs().sr & !flags::IMPLEMENTED,
        0,
        "bits 11, 12 and 14 have no storage on a 68000"
    );
}

#[test]
fn registers_can_be_named() {
    assert_eq!(Reg::from_name("d3"), Some(Reg::D(3)));
    assert_eq!(Reg::from_name("a7"), Some(Reg::A(7)));
    assert_eq!(Reg::from_name("usp"), Some(Reg::Usp));
    assert_eq!(Reg::from_name("pc"), Some(Reg::Pc));
    assert_eq!(Reg::from_name("d9"), None);
    assert_eq!(Reg::from_name("nope"), None);
    for reg in Reg::ALL {
        assert_eq!(Reg::from_name(&alloc::format!("{reg}")), Some(*reg));
    }
}

#[test]
fn the_register_display_is_readable() {
    let regs = Regs {
        sr: flags::S | flags::IPL | flags::Z,
        ..Regs::default()
    };
    let text = alloc::format!("{regs}");
    assert!(text.contains("D0:00000000"));
    assert!(text.contains("-S--Z--"));
    assert!(text.ends_with("I7"));
}

#[test]
fn the_isa_description_covers_every_row() {
    let text = super::describe_isa();
    assert_eq!(text.lines().count(), isa::TABLE.len());
    assert!(text.contains("MOVE"));
}

#[test]
fn construction_from_properties_validates_what_it_is_given() {
    use crate::core::props::Props;
    use crate::core::registry::Registry;
    use crate::core::space::RequesterId;

    let cpu = M68k::from_props(&Props::new().with("requester", 7u64)).unwrap();
    assert_eq!(cpu.config().requester, RequesterId(7));
    // A property nothing here accepts is an error, not a shrug: a typo that is
    // silently ignored is an afternoon lost.
    assert!(M68k::from_props(&Props::new().with("decimal", true)).is_err());

    let mut registry = Registry::new();
    super::register(&mut registry).unwrap();
    assert!(super::register(&mut registry).is_err(), "no double claims");
    let device = registry.create("cpu.m68k", &Props::new()).unwrap();
    assert_eq!(device.class().name, "cpu.m68k");
}

#[test]
fn realize_does_nothing_outward_because_the_space_has_not_arrived_yet() {
    use crate::core::device::{Deferred, RealizeCtx};
    use crate::core::space::RequesterId;

    // The check that a core has an address space used to live in `realize`. It
    // cannot: the realizer runs `realize` for every device *before* it binds
    // any of them, so a core that refused here would refuse every machine. The
    // check is in `Instance::bind`, and the test for it is below.
    let cpu = M68k::new(Config::default());
    let mut deferred = Deferred::new();
    let ctx_hosts = crate::core::HostObjects::new();
    let mut ctx = RealizeCtx::new("cpu", RequesterId::ANONYMOUS, &mut deferred, &ctx_hosts);
    assert!(cpu.realize(&mut ctx).is_ok());
}

/// A `BuildOptions` and registry that know about this core and `ram`/`rom`.
fn machine_layer() -> (crate::core::Registry, crate::machine::BuildOptions) {
    let mut options = crate::machine::BuildOptions::new();
    options.classes.insert(super::schema());
    for schema in crate::machine::builtin::schemas() {
        options.classes.insert(schema);
    }
    super::bind(&mut options.bindings).expect("nothing else claims cpu.m68k");
    crate::machine::builtin::bind(&mut options.bindings).expect("ram and rom");

    let mut registry = crate::core::Registry::new();
    crate::machine::builtin::register(&mut registry).expect("ram and rom");
    super::register(&mut registry).expect("nothing else claims cpu.m68k");
    (registry, options)
}

#[test]
fn binding_a_core_with_no_address_space_is_a_machine_error() {
    let (registry, options) = machine_layer();
    let text = "machine \"m\" {\n  osc x = 8000000 Hz\n  \
                space mem { width = 24, endian = big }\n  \
                object dram \"ram\" { size = 64K }\n  object cpu \"cpu.m68k\" { clock = x }\n  \
                map mem 0 size 64K = dram\n}\n";
    let err = crate::machine::build("t.machine", text, &registry, &options)
        .expect_err("a core with no `space =` cannot fetch");
    let text = alloc::format!("{err}");
    assert!(text.contains("address space"), "{text}");
}

#[test]
fn the_three_ipl_pins_are_one_sink_seen_through_three_ports() {
    use crate::core::device::Device;
    use crate::core::wire::{Level, Wire, WireId};

    // The shape a 68000 forces: the pins encode a *level*, so nothing can
    // resolve one of them alone, and all three ports therefore have to reach
    // the same object. Three separate sinks would each see a third of the
    // answer and drive a third of the level.
    let board = Board::new();
    let mut wires = Vec::new();
    let mut pins = Vec::new();
    for (line, port) in ["ipl0", "ipl1", "ipl2"].iter().enumerate() {
        let src = WireId::new(line as u64 + 1);
        let pin = board.cpu.sink(port, &[src]).expect("an IPL pin");
        assert_eq!(pin.line, line as u32, "the port names which line it is");
        let wire = Wire::builder()
            .source(src)
            .sink_weak(Arc::downgrade(&pin.sink), pin.line)
            .build();
        pins.push(pin);
        wires.push((wire, src));
    }

    assert_eq!(board.cpu.ipl(), 0);
    wires[1].0.set(wires[1].1, Level::High);
    assert_eq!(board.cpu.ipl(), 2, "IPL1 alone encodes level 2");
    wires[0].0.set(wires[0].1, Level::High);
    assert_eq!(board.cpu.ipl(), 3, "and with IPL0, level 3");
    wires[2].0.set(wires[2].1, Level::High);
    assert_eq!(board.cpu.ipl(), 7, "all three is the non-maskable level");
    wires[1].0.set(wires[1].1, Level::Low);
    assert_eq!(board.cpu.ipl(), 5);
}

#[test]
fn the_pins_a_machine_file_may_name_are_exactly_these_four() {
    use crate::core::device::Device;
    let cpu = M68k::new(Config::default());
    for port in ["ipl0", "ipl1", "ipl2", "reset"] {
        assert!(cpu.sink(port, &[]).is_some(), "`{port}` should be a pin");
    }
    for port in ["irq", "ipl", "ipl3", ""] {
        assert!(
            cpu.sink(port, &[]).is_none(),
            "`{port}` is not a pin this core has"
        );
    }
}

#[test]
fn the_reset_pin_latches_and_the_next_step_runs_the_sequence() {
    use crate::core::device::Device;
    use crate::core::wire::{Level, Wire, WireId};

    let board = Board::new();
    board.boot(&[0x4e71]); // NOP
    board.cpu.step();
    assert_eq!(board.cpu.regs().pc, 0x402);

    let src = WireId::new(1);
    let pin = board.cpu.sink("reset", &[src]).expect("a reset pin");
    let wire = Wire::builder()
        .source(src)
        .sink_weak(Arc::downgrade(&pin.sink), pin.line)
        .build();
    // The latch lives outside the execution lock, so it becomes execution
    // state on the step that consumes it — which is what keeps a device
    // asserting reset from inside an access this core issued out of the core's
    // own critical section.
    wire.set(src, Level::High);
    board.cpu.step();
    let regs = board.cpu.regs();
    assert_eq!(regs.pc, 0x400, "the sequence re-read vector 1");
    assert_eq!(regs.a[7], 0x2000, "and vector 0");
    assert_eq!(regs.ipl_mask(), 7);
}

/// A controller on one `IPL` encoding, the way a real 68000 peripheral sits in
/// CPU space: it compares the level the acknowledge cycle presents on A3-A1
/// with its own and answers only its own, declining every other.
///
/// `answer` is what it drives once it is the one being asked — a vector and
/// `DTACK`, or `VPA` for a controller that has nothing to supply.
#[derive(Debug)]
struct Controller {
    level: u8,
    answer: crate::core::wire::IntAckResponse,
    asked: crate::core::sync::AtomicU32,
}

impl Controller {
    /// A controller on `level` that drives `vector`.
    fn vectoring(level: u8, vector: u8) -> Arc<Controller> {
        Arc::new(Controller {
            level,
            answer: crate::core::wire::IntAckResponse::Vector(u32::from(vector)),
            asked: crate::core::sync::AtomicU32::new(0),
        })
    }

    /// A controller on `level` that asserts `VPA` instead.
    fn autovectoring(level: u8) -> Arc<Controller> {
        Arc::new(Controller {
            level,
            answer: crate::core::wire::IntAckResponse::Autovector,
            asked: crate::core::sync::AtomicU32::new(0),
        })
    }

    /// How many acknowledge cycles have reached this controller, declined ones
    /// included — a cycle another controller took never gets here at all.
    fn asked(&self) -> u32 {
        self.asked.load(crate::core::sync::Ordering::Relaxed)
    }

    /// Hang this controller off `port`, keeping the `Arc` alive in the caller:
    /// the net holds it weakly.
    fn attach(self: &Arc<Self>, cpu: &M68k, port: &str) {
        use crate::core::device::Device;
        let weak: alloc::sync::Weak<dyn crate::core::wire::IntAck> = Arc::downgrade(self) as _;
        cpu.attach_int_ack(port, weak);
    }
}

impl crate::core::wire::IntAck for Controller {
    fn acknowledge(
        &self,
        cycle: crate::core::wire::IntAckCycle,
    ) -> crate::core::wire::IntAckResponse {
        self.asked
            .fetch_add(1, crate::core::sync::Ordering::Relaxed);
        if cycle.level() == Some(self.level) {
            self.answer
        } else {
            crate::core::wire::IntAckResponse::Declined
        }
    }
}

#[test]
fn a_controller_that_answers_the_acknowledge_vectors_and_one_that_does_not_autovectors() {
    // Autovector first: nothing attached, so the level picks the vector.
    let board = Board::new();
    board.boot(&[0x4e71, 0x4e71]);
    board.poke_long(u64::from(vector::AUTOVECTOR_BASE + 5) * 4, 0x0800);
    // Drop the mask, which a reset leaves at 7, so level 5 gets through.
    let mut regs = board.cpu.regs();
    regs.sr = (regs.sr & !flags::IPL) | (1 << 8);
    board.cpu.set_regs(regs);
    board.cpu.set_ipl(5);
    board.cpu.step();
    assert_eq!(
        board.cpu.regs().pc,
        0x0800,
        "with nothing answering, `VPA` and the autovector for level 5"
    );

    // And now with a controller on the net.
    let board = Board::new();
    board.boot(&[0x4e71, 0x4e71]);
    board.poke_long(64 * 4, 0x0900);
    let mut regs = board.cpu.regs();
    regs.sr = (regs.sr & !flags::IPL) | (1 << 8);
    board.cpu.set_regs(regs);
    let device = Controller::vectoring(5, 64);
    device.attach(&board.cpu, "ipl2");
    board.cpu.set_ipl(5);
    board.cpu.step();
    assert_eq!(device.asked(), 1, "the CPU must run the acknowledge cycle");
    assert_eq!(
        board.cpu.regs().pc,
        0x0900,
        "and take the vector the controller drove, not the autovector"
    );
}

/// The gap this seam was reshaped to close: a 68000 puts the level being
/// acknowledged on A3-A1, so a board may carry **two** vectoring controllers on
/// different `IPL` pins and each answers only its own level. With an
/// acknowledge that carried no argument, whichever controller was attached
/// second silently answered for both.
#[test]
fn two_vectoring_controllers_on_different_ipl_pins_each_answer_their_own_level() {
    let board = Board::new();
    // Two RTEs at $400: each handler returns to the next one.
    board.boot(&[0x4e73, 0x4e73]);
    board.poke_long(80 * 4, 0x0a00); // the level-2 controller's vector
    board.poke_long(96 * 4, 0x0b00); // the level-5 controller's vector
    board.poke_word(0xa00, 0x4e71);
    board.poke_word(0xb00, 0x4e71);

    // `ipl1` alone encodes level 2, `ipl2` alone encodes level 4 — but the
    // level a controller claims is its own business, and this one claims 5.
    let low = Controller::vectoring(2, 80);
    let high = Controller::vectoring(5, 96);
    low.attach(&board.cpu, "ipl1");
    high.attach(&board.cpu, "ipl2");

    let mut regs = board.cpu.regs();
    regs.sr = (regs.sr & !flags::IPL) | (1 << 8);
    board.cpu.set_regs(regs);
    board.cpu.set_ipl(5);
    board.cpu.step();
    assert_eq!(
        board.cpu.regs().pc,
        0x0b00,
        "level 5 is the second controller's, and it supplies vector 96"
    );
    assert_eq!(low.asked(), 1, "the first controller saw the cycle");
    assert_eq!(high.asked(), 1, "and declining passed it to the second");

    // And the other way round, which is the half that could not be expressed:
    // the same processor, a different level, the *other* controller's vector.
    let mut regs = board.cpu.regs();
    regs.sr = (regs.sr & !flags::IPL) | (1 << 8);
    board.cpu.set_regs(regs);
    board.cpu.set_ipl(2);
    board.cpu.step();
    assert_eq!(
        board.cpu.regs().pc,
        0x0a00,
        "level 2 is the first controller's, and it supplies vector 80"
    );
    assert_eq!(low.asked(), 2);
    assert_eq!(
        high.asked(),
        1,
        "a cycle the first controller took never reaches the second"
    );
}

/// Being asked and having nothing to supply is not the same as not being asked:
/// the first is `VPA` and terminates the cycle, the second passes it on.
#[test]
fn a_controller_that_asserts_vpa_takes_the_cycle_and_the_one_behind_it_never_sees_it() {
    let board = Board::new();
    board.boot(&[0x4e71, 0x4e71]);
    board.poke_long(u64::from(vector::AUTOVECTOR_BASE + 4) * 4, 0x0c00);
    board.poke_long(112 * 4, 0x0d00);
    board.poke_word(0xc00, 0x4e71);
    board.poke_word(0xd00, 0x4e71);

    // Both are on level 4. The first asserts `VPA`; the second would drive a
    // vector, and must never be given the chance.
    let vpa = Controller::autovectoring(4);
    let vectoring = Controller::vectoring(4, 112);
    vpa.attach(&board.cpu, "ipl2");
    vectoring.attach(&board.cpu, "ipl2");

    let mut regs = board.cpu.regs();
    regs.sr = (regs.sr & !flags::IPL) | (1 << 8);
    board.cpu.set_regs(regs);
    board.cpu.set_ipl(4);
    board.cpu.step();
    assert_eq!(
        board.cpu.regs().pc,
        0x0c00,
        "`VPA` answers the cycle, and the autovector for level 4 is taken"
    );
    assert_eq!(vpa.asked(), 1);
    assert_eq!(
        vectoring.asked(),
        0,
        "the cycle was over: an answered acknowledge is not passed on"
    );
}

/// The same controller offered on two `IPL` pins — which is how level 5 is
/// encoded — is one controller, asked once.
#[test]
fn a_controller_wired_to_two_ipl_pins_answers_one_acknowledge() {
    let board = Board::new();
    board.boot(&[0x4e71, 0x4e71]);
    board.poke_long(96 * 4, 0x0b00);
    board.poke_word(0xb00, 0x4e71);
    let device = Controller::vectoring(5, 96);
    device.attach(&board.cpu, "ipl0");
    device.attach(&board.cpu, "ipl2");

    let mut regs = board.cpu.regs();
    regs.sr = (regs.sr & !flags::IPL) | (1 << 8);
    board.cpu.set_regs(regs);
    board.cpu.set_ipl(5);
    board.cpu.step();
    assert_eq!(board.cpu.regs().pc, 0x0b00);
    assert_eq!(device.asked(), 1, "offered twice, kept once");
}

#[test]
fn the_scheduler_budget_is_never_overshot_and_the_debt_is_paid_back() {
    // `MOVEM.L` of every register is far longer than a one-cycle budget, so
    // this is the case where a plain `run` reports more than it was handed —
    // which the scheduler rejects outright.
    let board = Board::new();
    board.boot(&[0x48e7, 0xffff, 0x60fa]); // MOVEM.L d0-a7,-(a7) ; BRA .-4
    let before = board.cpu.cycles();
    let mut total = 0u64;
    for _ in 0..64 {
        let used = board.cpu.run_budget(1);
        assert!(used <= 1, "a budget of one cycle reported {used}");
        total += used;
    }
    assert_eq!(total, 64, "every tick of every budget was granted and used");
    assert_eq!(
        board.cpu.cycles() - before,
        total + board.cpu.cycle_debt(),
        "cycles executed but not yet reported are exactly the debt"
    );
}

#[test]
fn a_core_without_a_space_does_nothing_rather_than_panicking() {
    let cpu = M68k::new(Config::default());
    assert_eq!(cpu.step(), 0);
    assert!(cpu.disassemble(0, 4).is_empty());
}

// ---------------------------------------------------------------------------
// The quirks. Each of these is a place where the obvious implementation is
// wrong, so each gets a test that says what the hardware actually does.
// ---------------------------------------------------------------------------

#[test]
fn link_a7_pushes_the_stack_pointer_it_has_just_moved() {
    let board = Board::new();
    board.boot(&[0x4e57, 0xfff0]); // LINK A7,#-16
    board.cpu.step();
    let regs = board.cpu.regs();
    // A7 was decremented to $1ffc before it was read, so that is what landed
    // on the stack — not the $2000 it held on entry.
    assert_eq!(board.peek_long(0x1ffc), 0x1ffc);
    assert_eq!(regs.a[7], 0x1ffc - 16);
}

#[test]
fn unlk_a7_ends_up_holding_what_it_popped() {
    let board = Board::new();
    board.boot(&[0x4e5f]); // UNLK A7
    board.poke_long(0x2000, 0x0000_1234);
    board.cpu.step();
    assert_eq!(
        board.cpu.regs().a[7],
        0x1234,
        "the register is restored after the stack pointer, so it wins"
    );
}

#[test]
fn a_shift_past_the_operand_width_runs_out_of_carry() {
    let board = Board::new();
    // ASR.B D1,D0 with a count of 12 on a negative byte.
    board.boot(&[0xe220, 0xe220]);
    let mut regs = board.cpu.regs();
    regs.d[0] = 0x0000_00f3;
    regs.d[1] = 12;
    regs.sr &= !(flags::X | flags::C);
    board.cpu.set_regs(regs);
    board.cpu.step();
    let regs = board.cpu.regs();
    assert_eq!(regs.d[0] & 0xff, 0xff, "the result is all sign bits");
    assert!(regs.flag(flags::N));
    assert!(
        !regs.flag(flags::C) && !regs.flag(flags::X),
        "the operand ran out before the count did, so nothing was shifted out"
    );

    // Exactly eight, and the sign bit *is* the last bit out.
    let mut regs = board.cpu.regs();
    regs.d[0] = 0x0000_00f3;
    regs.d[1] = 8;
    board.cpu.set_regs(regs);
    board.cpu.step();
    let regs = board.cpu.regs();
    assert!(regs.flag(flags::C) && regs.flag(flags::X));
}

#[test]
fn a_plain_rotate_leaves_the_extend_flag_alone() {
    let board = Board::new();
    board.boot(&[0xe358]); // ROL.W #1,D0
    let mut regs = board.cpu.regs();
    regs.d[0] = 0x0000_8001;
    regs.sr &= !flags::X;
    board.cpu.set_regs(regs);
    board.cpu.step();
    let regs = board.cpu.regs();
    assert_eq!(regs.d[0] & 0xffff, 0x0003);
    assert!(regs.flag(flags::C), "the bit rotated out reaches carry");
    assert!(!regs.flag(flags::X), "but never reaches extend");
}

#[test]
fn abcd_decides_its_carry_before_correcting_the_units() {
    let board = Board::new();
    board.boot(&[0xc300]); // ABCD D0,D1
    let mut regs = board.cpu.regs();
    regs.d[0] = 0x2d;
    regs.d[1] = 0x69;
    regs.sr &= !flags::X;
    board.cpu.set_regs(regs);
    board.cpu.step();
    let regs = board.cpu.regs();
    // $2d + $69 is $96 in binary, below $99, so no carry — and only then does
    // the units correction take it to $9c. Testing after the correction would
    // wrongly carry and give $fc.
    assert_eq!(regs.d[1] & 0xff, 0x9c);
    assert!(!regs.flag(flags::C));
}

#[test]
fn sbcd_carries_out_of_the_units_correction() {
    let board = Board::new();
    board.boot(&[0x8300]); // SBCD D0,D1
    let mut regs = board.cpu.regs();
    regs.d[0] = 0xef;
    regs.d[1] = 0xf0;
    regs.sr &= !flags::X;
    board.cpu.set_regs(regs);
    board.cpu.step();
    let regs = board.cpu.regs();
    // $f0 - $ef borrows nothing in binary and needs no tens correction, but
    // subtracting the units correction takes it below zero: the result is $fb
    // *and* the carry is set.
    assert_eq!(regs.d[1] & 0xff, 0xfb);
    assert!(regs.flag(flags::C) && regs.flag(flags::X));
}

#[test]
fn movem_stores_the_register_it_is_walking_as_it_found_it() {
    let board = Board::new();
    // MOVEM.L D0/A7,-(A7): the mask is read backwards for a predecrement, so
    // A7 is bit 0 and D0 is bit 15.
    board.boot(&[0x48e7, 0x8001]);
    board.cpu.step();
    let regs = board.cpu.regs();
    assert_eq!(regs.a[7], 0x2000 - 8);
    assert_eq!(
        board.peek_long(0x2000 - 4),
        0x2000,
        "A7 is stored with the value it had before the instruction, not the \
         value it has reached by its turn"
    );
    assert_eq!(board.peek_long(0x2000 - 8), regs.d[0]);
}

#[test]
fn movem_reads_one_word_past_the_end_of_its_list() {
    let board = Board::new();
    // MOVEM.W (A0)+,D0 — one register, but two words are read.
    board.boot(&[0x4c98, 0x0001]);
    board.poke_word(0x1000, 0x1234);
    board.poke_word(0x1002, 0x5678);
    let mut regs = board.cpu.regs();
    regs.a[0] = 0x1000;
    board.cpu.set_regs(regs);
    let used = board.cpu.step();
    let regs = board.cpu.regs();
    assert_eq!(regs.d[0], 0x1234, "sign-extended from the word read");
    assert_eq!(regs.a[0], 0x1002, "the discarded word does not advance A0");
    // The register-list fetch, the transfer, the discarded word, and the
    // final prefetch: four bus cycles and no internal time at all.
    assert_eq!(used, 16);
}

#[test]
fn a_jump_takes_its_last_extension_word_out_of_the_queue() {
    let board = Board::new();
    // JMP $10(A0). The displacement is already prefetched, so the only bus
    // cycles are the two that reload the queue at the target.
    board.boot(&[0x4ee8, 0x0010]);
    board.poke_word(0x1010, 0x4e71);
    let mut regs = board.cpu.regs();
    regs.a[0] = 0x1000;
    board.cpu.set_regs(regs);
    let used = board.cpu.step();
    assert_eq!(board.cpu.regs().pc, 0x1010);
    assert_eq!(
        used, 10,
        "two bus cycles and two internal, not three cycles"
    );
}

#[test]
fn a_branch_to_an_odd_address_pushes_the_target_minus_four() {
    let board = Board::new();
    // BRA to an odd address: the queue reload takes the address error, and by
    // then the program counter is four behind the word it was fetching.
    board.boot(&[0x6011]);
    board.poke_long(u64::from(vector::ADDRESS_ERROR) * 4, 0x0800);
    board.poke_word(0x800, 0x4e71);
    board.cpu.step();
    let regs = board.cpu.regs();
    assert_eq!(regs.pc, 0x800);
    let sp = regs.a[7];
    assert_eq!(board.peek_long(u64::from(sp) + 2), 0x413, "the odd target");
    assert_eq!(board.peek_long(u64::from(sp) + 10), 0x413 - 4);
    // A fetch, so the special status word says program space.
    assert_eq!(board.peek_word(u64::from(sp)) & 0x1f, 0x1e);
}

#[test]
fn the_reset_instruction_pulses_the_line_without_resetting_the_core() {
    let board = Board::new();
    board.boot(&[0x4e70]); // RESET
    let pulses = board.cpu.reset_pulses();
    let used = board.cpu.step();
    assert_eq!(board.cpu.reset_pulses(), pulses + 1);
    assert_eq!(board.cpu.regs().pc, 0x402, "the processor carries on");
    assert_eq!(used, 132, "124 clocks of RESET asserted, plus the prefetch");
}

#[test]
fn move_usp_reaches_the_bank_that_is_not_in_use() {
    let board = Board::new();
    // MOVE USP,A0 then MOVE A1,USP.
    board.boot(&[0x4e68, 0x4e61]);
    let mut regs = board.cpu.regs();
    regs.usp = 0x1234;
    regs.a[1] = 0x5678;
    board.cpu.set_regs(regs);
    board.cpu.step();
    assert_eq!(board.cpu.regs().a[0], 0x1234);
    board.cpu.step();
    let regs = board.cpu.regs();
    assert_eq!(regs.usp, 0x5678);
    assert_eq!(regs.a[7], 0x2000, "the supervisor stack is untouched");
}

#[test]
fn level_seven_is_edge_triggered_and_fires_once() {
    let board = Board::new();
    board.boot(&[0x4e71, 0x4e71, 0x4e71]);
    board.poke_long(u64::from(vector::AUTOVECTOR_BASE + 7) * 4, 0x0f00);
    board.poke_word(0xf00, 0x4e71);

    board.cpu.set_ipl(7);
    board.cpu.step();
    assert_eq!(board.cpu.regs().pc, 0xf00, "the transition is recognised");

    // The pins are still at seven, and nothing more happens: the edge is gone.
    board.cpu.step();
    assert_eq!(board.cpu.regs().pc, 0xf02, "the NOP in the handler ran");

    // Dropping and re-raising is a new edge.
    board.cpu.set_ipl(0);
    board.cpu.set_ipl(7);
    board.cpu.step();
    assert_eq!(board.cpu.regs().pc, 0xf00);
}

#[test]
fn an_interrupt_during_stop_returns_after_the_stop() {
    let board = Board::new();
    // STOP #$2000, then a MOVEQ that must be what RTE comes back to.
    board.boot(&[0x4e72, 0x2000, 0x7001]);
    board.poke_long(u64::from(vector::AUTOVECTOR_BASE + 3) * 4, 0x0e80);
    board.poke_word(0xe80, 0x4e73); // RTE
    board.cpu.step();
    assert!(board.cpu.is_stopped());

    board.cpu.set_ipl(3);
    board.cpu.step();
    let regs = board.cpu.regs();
    assert!(!board.cpu.is_stopped());
    assert_eq!(regs.pc, 0xe80);
    assert_eq!(
        board.peek_long(u64::from(regs.ssp) + 2),
        0x404,
        "the address pushed is the instruction after the STOP, not inside it"
    );
    // The source has to stop asking, or a level-sensitive interrupt is simply
    // taken again the moment RTE lowers the mask.
    board.cpu.set_ipl(0);
    board.cpu.step(); // RTE
    board.cpu.step(); // MOVEQ #1,D0
    assert_eq!(board.cpu.regs().d[0], 1);
}

#[test]
fn a_reset_from_user_state_does_not_lose_a_stack_pointer() {
    let board = Board::new();
    board.boot(&[0x4e71]);
    let mut regs = board.cpu.regs();
    regs.sr &= !flags::S;
    regs.usp = 0x1500;
    regs.ssp = 0x1900;
    board.cpu.set_regs(regs);
    assert_eq!(board.cpu.reg(Reg::A(7)), 0x1500);

    board.cpu.request_reset();
    board.cpu.step();
    let regs = board.cpu.regs();
    assert!(regs.supervisor());
    // Vector 0 loaded the supervisor stack pointer, and the user one is still
    // in its own bank rather than having been overwritten by it.
    assert_eq!(regs.ssp, 0x2000);
    assert_eq!(regs.a[7], 0x2000);
    assert_eq!(regs.usp, 0x1500);
}

#[test]
fn a_bus_error_is_an_exception_rather_than_a_shrug() {
    // Nothing is mapped above 64 KiB on this board, and the space faults on an
    // unassigned access — which is what a 68000 sees as BERR.
    let board = Board::new();
    board.boot(&[0x2050]); // MOVEA.L (A0),A0
    board.poke_long(u64::from(vector::BUS_ERROR) * 4, 0x0700);
    board.poke_word(0x700, 0x4e71);
    let mut regs = board.cpu.regs();
    regs.a[0] = 0x0080_0000;
    board.cpu.set_regs(regs);
    board.cpu.step();

    let regs = board.cpu.regs();
    assert_eq!(regs.pc, 0x700);
    assert_eq!(board.cpu.bus_faults().0, 1);
    let sp = regs.a[7];
    assert_eq!(sp, 0x2000 - 14, "a bus error uses the group 0 frame too");
    assert_eq!(board.peek_long(u64::from(sp) + 2), 0x0080_0000);
    assert_eq!(
        board.peek_word(u64::from(sp)) & 0x1f,
        0x15,
        "supervisor data, read"
    );
}

#[test]
fn the_disassembler_and_the_interpreter_agree_on_every_instruction_length() {
    // The strongest thing that can be said about a table two consumers read:
    // sweep all 65 536 encodings, and for every one that both decodes and runs
    // to completion, check that the bytes the disassembler says an instruction
    // occupies are the bytes the program counter actually moved. A length
    // computed twice is a length that drifts, and this is what stops it.
    let board = Board::new();
    board.poke_long(0, 0x2000);
    board.poke_long(4, 0x0400);
    board.cpu.step();

    // A register file that keeps every addressing mode inside RAM and away
    // from an odd address, so the sweep measures decode rather than exceptions.
    let mut base = Regs {
        d: [0x0000_0004; 8],
        a: [0x0000_1000; 8],
        usp: 0x0000_1800,
        ssp: 0x0000_2000,
        pc: 0x400,
        sr: flags::S | flags::IPL,
        prefetch: [0, 0],
    };
    base.a[7] = 0x2000;

    let mut checked = 0usize;
    for opcode in 0..=u16::MAX {
        let insn = isa::decode(opcode);
        // Anything that moves the program counter somewhere of its own choosing
        // has no "length" to compare against, and anything that traps measures
        // the exception rather than the instruction.
        if !matches!(
            insn.op,
            isa::Op::Move
                | isa::Op::Movea
                | isa::Op::Moveq
                | isa::Op::Movem
                | isa::Op::Movep
                | isa::Op::Add
                | isa::Op::Addi
                | isa::Op::Addq
                | isa::Op::Adda
                | isa::Op::Addx
                | isa::Op::Sub
                | isa::Op::Subi
                | isa::Op::Subq
                | isa::Op::Suba
                | isa::Op::Subx
                | isa::Op::And
                | isa::Op::Andi
                | isa::Op::Or
                | isa::Op::Ori
                | isa::Op::Eor
                | isa::Op::Eori
                | isa::Op::Cmp
                | isa::Op::Cmpi
                | isa::Op::Cmpa
                | isa::Op::Cmpm
                | isa::Op::Abcd
                | isa::Op::Sbcd
                | isa::Op::Nbcd
                | isa::Op::Clr
                | isa::Op::Neg
                | isa::Op::Negx
                | isa::Op::Not
                | isa::Op::Tst
                | isa::Op::Tas
                | isa::Op::Ext
                | isa::Op::Swap
                | isa::Op::Exg
                | isa::Op::Lea
                | isa::Op::Muls
                | isa::Op::Mulu
                | isa::Op::Btst
                | isa::Op::Bchg
                | isa::Op::Bclr
                | isa::Op::Bset
                | isa::Op::Scc
                | isa::Op::Asl
                | isa::Op::Asr
                | isa::Op::Lsl
                | isa::Op::Lsr
                | isa::Op::Rol
                | isa::Op::Ror
                | isa::Op::Roxl
                | isa::Op::Roxr
                | isa::Op::Nop
                | isa::Op::OriToCcr
                | isa::Op::AndiToCcr
                | isa::Op::EoriToCcr
                | isa::Op::MoveFromSr
                | isa::Op::MoveToCcr
        ) {
            continue;
        }

        // Four extension words of small even values: legal for every mode, and
        // they keep an index or a displacement pointing into RAM.
        for i in 0..5u64 {
            board.poke_word(0x400 + 2 * i, 0x0010);
        }
        board.poke_word(0x400, opcode);
        board.cpu.set_regs(base);
        board.cpu.request_reset();
        board.cpu.step();
        assert_eq!(board.cpu.regs().pc, 0x400);
        board.cpu.set_regs(Regs {
            prefetch: board.cpu.regs().prefetch,
            ..base
        });

        let expected = board.cpu.disassemble(0x400, 1);
        board.cpu.step();
        let after = board.cpu.regs().pc;
        // An instruction that faulted went somewhere else entirely; it has
        // nothing to say about lengths.
        if !(0x400..=0x420).contains(&after) {
            continue;
        }
        assert_eq!(
            after - 0x400,
            u32::from(expected[0].len),
            "{opcode:04x} {}: the disassembler says {} bytes, the interpreter \
             consumed {}",
            expected[0],
            expected[0].len,
            after - 0x400
        );
        checked += 1;
    }
    assert!(checked > 20_000, "only {checked} encodings were exercised");
}

#[test]
fn a_level_seven_pulse_is_not_lost_between_steps() {
    let board = Board::new();
    board.boot(&[0x4e71]);
    board.poke_long(u64::from(vector::AUTOVECTOR_BASE + 7) * 4, 0x0f00);
    board.poke_word(0xf00, 0x4e71);

    // A step covers many clocks, so a source that raises the non-maskable
    // level and lets go again inside one is ordinary, not a race. The edge is
    // latched and must survive to the next instruction boundary.
    board.cpu.set_ipl(7);
    board.cpu.set_ipl(0);
    board.cpu.step();
    assert_eq!(board.cpu.regs().pc, 0xf00);
    assert_eq!(
        board.cpu.ipl(),
        0,
        "and the pins read what they were left at"
    );
}

#[test]
fn an_interrupt_costs_what_the_manual_says() {
    let board = Board::new();
    board.boot(&[0x4e71]);
    board.poke_long(u64::from(vector::AUTOVECTOR_BASE + 4) * 4, 0x0e00);
    board.poke_word(0xe00, 0x4e71);
    let mut regs = board.cpu.regs();
    regs.sr = (regs.sr & !flags::IPL) | (1 << 8);
    board.cpu.set_regs(regs);
    board.cpu.set_ipl(4);
    // MC68000UM Table 8-14: 44(5/3). Three of those five reads and all three
    // writes are on the bus here; the acknowledge cycle is charged rather than
    // driven, because CPU space is a function code the framework has no room
    // for yet.
    assert_eq!(board.cpu.step(), 44);
}

#[test]
fn a_supplied_interrupt_vector_is_consumed_by_the_acknowledge() {
    let board = Board::new();
    board.boot(&[0x4e73, 0x4e73]); // two RTEs, so each handler returns
    board.poke_long(64 * 4, 0x0e00); // the vector the controller supplies
    board.poke_long(u64::from(vector::AUTOVECTOR_BASE + 4) * 4, 0x0f00);
    board.poke_word(0xe00, 0x4e71);
    board.poke_word(0xf00, 0x4e71);
    let mut regs = board.cpu.regs();
    regs.sr = (regs.sr & !flags::IPL) | (1 << 8);
    board.cpu.set_regs(regs);

    board.cpu.set_interrupt_vector(Some(64));
    board.cpu.set_ipl(4);
    board.cpu.step();
    assert_eq!(board.cpu.regs().pc, 0xe00, "the controller's vector");
    assert_eq!(board.cpu.interrupt_vector(), None, "and it was consumed");

    // The next acknowledge autovectors, exactly as it would if no device
    // answered that cycle.
    let mut regs = board.cpu.regs();
    regs.sr = (regs.sr & !flags::IPL) | (1 << 8);
    board.cpu.set_regs(regs);
    board.cpu.step();
    assert_eq!(board.cpu.regs().pc, 0xf00);
}

#[test]
fn a_core_can_be_placed_mid_program_without_reaching_inside_it() {
    // A fresh core owes a reset sequence, which would throw away a register
    // file written before the first step. Anything that resumes a loaded image
    // or replays a trace turns that off through the public API.
    let board = Board::new();
    board.poke_word(0x1000, 0x7042); // MOVEQ #$42,D0
    board.cpu.set_reset_pending(false);
    board.cpu.set_regs(Regs {
        pc: 0x1000,
        sr: flags::S | flags::IPL,
        prefetch: [0x7042, board.peek_word(0x1002)],
        ..Regs::default()
    });
    board.cpu.step();
    assert_eq!(board.cpu.regs().d[0], 0x42);
    assert_eq!(board.cpu.regs().pc, 0x1002);
}

#[test]
fn resume_restarts_a_halted_core() {
    let board = Board::new();
    board.boot(&[0x3080]);
    board.poke_long(u64::from(vector::ADDRESS_ERROR) * 4, 0x0801);
    let mut regs = board.cpu.regs();
    regs.a[0] = 0x1001;
    board.cpu.set_regs(regs);
    board.cpu.step();
    assert!(board.cpu.is_halted());

    board.cpu.resume();
    assert!(!board.cpu.is_halted());
    assert!(board.cpu.step() > 0);
}