rigless 0.1.0

Virtual hardware-in-the-loop runtime: run unmodified firmware on an emulated MCU with every peripheral, chip model and unit of virtual time in Rust, and a CPU core of its own that translates the firmware's instructions to host code
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
// Copyright (c) 2026 Rigless Labs.
// SPDX-License-Identifier: MIT OR Apache-2.0
//! The protected memory system architecture, `PMSAv7`, DDI 0403E.b B3.5.
//!
//! # What is modelled
//!
//! | Behaviour | Source | Test |
//! |---|---|---|
//! | `MPU_TYPE`: the machine's regions, 0, 8 or 16, unified, read-only | B3.5.5, 100166 table 5-1 | `mpu_type_says_eight_unified_regions`, `an_mpu_of_sixteen_regions_uses_every_one` |
//! | No MPU: `MPU_TYPE` reads zero, `MPU_CTRL` is RAZ/WI and the rest read zero and drop writes | B3.5.4, B3.5.6 | `a_part_without_an_mpu_has_none_to_turn_on` |
//! | Every register resets to zero | 100166 table 5-1 | `every_register_resets_to_zero` |
//! | `MPU_CTRL`'s `ENABLE`, `HFNMIENA` and `PRIVDEFENA`, read back | B3.5.6 | `mpu_ctrl_keeps_its_three_bits` |
//! | `MPU_RNR` selects the pair `MPU_RBAR` and `MPU_RASR` reach | B3.5.7 | `rnr_selects_the_region_rbar_and_rasr_reach` |
//! | `MPU_RBAR`: `ADDR` from bit 5, `VALID` reads zero, `REGION` reads `MPU_RNR`'s low four bits, and a write with `VALID` selects its region first | B3.5.8 | `rbar_with_valid_selects_its_region_first` |
//! | `MPU_RASR`'s fields, its reserved bits reading zero | B3.5.9 | `rasr_keeps_its_fields_and_drops_reserved_bits` |
//! | A byte or halfword write to any of them is dropped, since only words are defined | B3.5.4 | `a_byte_or_halfword_write_changes_nothing` |
//! | The three aliases of the pair, so one `STM` programs four regions | B3.5.10 | `the_aliases_reach_the_same_pair` |
//! | The default map's permissions and execute-never regions, with the MPU off or bypassed | B3.5.2, B3.5.3 `DefaultPermissions()`, Table B3-1 | `a_disabled_mpu_allows_every_data_access`, `the_default_map_refuses_fetches_from_its_execute_never_regions` |
//! | The PPB always uses the default map | B3.5.1 | `the_ppb_uses_the_default_map_with_the_mpu_on` |
//! | No region and no background faults | B3.5.1, B3.5.3 `ValidateAddress()` | `an_access_no_region_matches_is_refused` |
//! | `PRIVDEFENA` makes the default map a background for privileged accesses only | B3.5.6 | `privdefena_is_a_background_for_privileged_accesses_only` |
//! | The highest matching region wins | B3.5.3 | `the_highest_matching_region_wins` |
//! | A disabled subregion falls through to lower regions and the background | B3.5.3 "Sub-region support", B3.5.9 | `a_disabled_subregion_falls_through` |
//! | A region of 4 GB matches everything, and one of 2 GB half of it | B3.5.3 `ValidateAddress()` | `a_region_of_four_gigabytes_matches_every_address`, `a_region_of_two_gigabytes_is_half_the_map` |
//! | Each `AP` encoding grants what Table B3-15 says | B2.3.8 `CheckPermission()`, Table B3-15 | `every_ap_encoding_grants_what_the_table_says` |
//! | `LDRT` and its kind are checked unprivileged from privileged code | B3.5.6 Table B3-12 | `an_unprivileged_access_from_privileged_code_is_checked_unprivileged`, `an_ldrt_the_mpu_refuses_runs_into_memmanage` |
//! | Thread mode with `CONTROL.nPRIV` is unprivileged, Handler mode never is | B1.4.4, B2.3.3 `FindPriv()` | `thread_mode_with_npriv_is_unprivileged` |
//! | `HFNMIENA` clear bypasses the MPU below execution priority 0: NMI or HardFault active, or `FAULTMASK` | B3.5.3 `ValidateAddress()`, B1.5.4 `ExecutionPriority()` | `hfnmiena_decides_for_handlers_below_priority_zero`, `execution_priority_comes_from_the_active_exceptions_not_ipsr` |
//! | Exception entry, return and lazy FP preservation check their stack accesses at the privilege and priority the pseudocode runs them at, which the exception model hands over | B1.5.6 `PushStack()`, B1.5.8 `ExceptionReturn()`, `DeActivate()` and `PopStack()`, B1.6 `PreserveFPState()` | `an_unstack_is_checked_as_the_thread_it_returns_to`, `a_push_is_checked_as_the_context_it_preempts`, `a_stack_context_holds_only_while_it_runs`, `a_frame_is_pushed_in_the_context_it_preempts`, `a_frame_is_popped_in_the_context_it_returns_to`, `lazy_preservation_runs_in_the_context_that_owns_the_state` |
//! | Vector reads use the default map whatever the regions say | B3.5.1, B3.5.3 `ValidateAddress()` | `a_vector_is_read_through_the_default_map` |
//! | A fetch needs read access and `XN` clear, and system space is always execute-never | B3.5.3, B2.3.8, B3.5.9 "Execute Never encoding" | `a_fetch_needs_read_access_and_xn_clear`, `system_space_stays_execute_never` |
//! | The translator fetches through the same check, and with the MPU on keeps what it translated apart by privilege and by execution priority below 0 | B3.5.3 | `a_fetch_is_checked_at_the_privilege_it_runs_at` |
//! | A refused access never reaches memory | B2.3.4 `MemA_with_priv()` | `a_refused_access_never_reaches_memory` |
//! | Every byte of an unaligned access is checked, and the byte refused is the fault address | B2.3.5 `MemU_with_priv()`, B3.5.3 `ValidateAddress()` | `every_byte_of_an_unaligned_access_is_checked` |
//! | A snapshot keeps the registers and what the checks answer, inline accesses included | | `a_snapshot_keeps_the_mpu`, `a_snapshot_with_the_mpu_on_checks_every_access_once_loaded` |
//! | A snapshot whose `MPU_RNR` names a region past the last is refused, since no write leaves one | B3.5.7 | `a_snapshot_naming_a_region_past_the_last_is_refused` |
//! | A page one region, or the background, decides throughout runs inline as far as it grants both privilege levels, until the MPU changes | B3.5.3 | `a_page_one_region_decides_is_inline_as_far_as_it_grants_both_privileges`, `a_page_is_decided_only_when_one_region_or_none_holds_all_of_it` |
//!
//! **Where the manual says UNPREDICTABLE, what this does.**
//!
//! | Case | Source | Choice | Test |
//! |---|---|---|---|
//! | `MPU_RNR`, or `MPU_RBAR` with `VALID`, naming a region past the last | B3.5.7, B3.5.8 | The write is ignored | `a_region_past_the_last_is_ignored` |
//! | `HFNMIENA` set with `ENABLE` clear | B3.5.6 | The MPU is off | `hfnmiena_without_enable_leaves_the_mpu_off` |
//! | `SIZE` below 4 | B3.5.3, B3.5.9 | The region is 32 bytes | `a_size_below_thirty_two_bytes_acts_as_thirty_two` |
//! | `SRD` set on a region below 256 bytes | B3.5.3, B3.5.9 | The pseudocode's subregion bits, eighths of the region | `subregions_of_a_small_region_follow_the_pseudocode` |
//! | `AP` of `100` | B2.3.8, Table B3-15 | No access | `every_ap_encoding_grants_what_the_table_says` |
//! | A base not aligned to the region's size | B3.5.8 | The pseudocode compares from the size's bit up, so the base is aligned down | `a_base_not_aligned_to_its_size_is_aligned_down` |
//! | An unaligned access to a region `TEX`, `C` and `B` make Device or Strongly-ordered | A3.5.7 | It's done a byte at a time, as Normal memory's is | `an_unaligned_access_to_device_memory_goes_byte_by_byte` |
//!
//! **What's left out, and why.** The memory type `TEX`, `C`, `B` and `S` give is kept and read
//! back but changes nothing else. Shareable memory only adds the global exclusive monitor, B2.3.7,
//! and this processor has a local one alone, since nothing shares its memory. Caching and ordering
//! don't show, since accesses happen one at a time in program order. B3.5.4 says an unprivileged
//! access to these registers is a BusFault, and that's the system control space's rule, not this
//! module's.

use serde::{Deserialize, Serialize};

use super::exception::Refused;
use super::family::Family;
use super::registers::{get, is_set, mask, mpu_ctrl, mpu_rasr, mpu_rbar, mpu_rnr, mpu_type, set};
use crate::emulator::core::Inline;

/// The most regions an MPU has room for: `MPU_RBAR.REGION` is four bits, B3.5.8.
const MOST_REGIONS: usize = 16;

/// The offsets of the MPU's registers into the system control space, Table B3-11.
const TYPE: u64 = 0xD90;
const CTRL: u64 = 0xD94;
const RNR: u64 = 0xD98;
const RBAR: u64 = 0xD9C;
const RASR: u64 = 0xDA0;

/// One of the MPU's registers.
#[derive(Clone, Copy)]
enum Register {
    Type,
    Ctrl,
    Rnr,
    Rbar,
    Rasr,
}

/// The register at `offset`, with the pair's three aliases reaching the pair, B3.5.10.
fn register(offset: u64) -> Option<Register> {
    Some(match offset {
        TYPE => Register::Type,
        CTRL => Register::Ctrl,
        RNR => Register::Rnr,
        RBAR | 0xDA4 | 0xDAC | 0xDB4 => Register::Rbar,
        RASR | 0xDA8 | 0xDB0 | 0xDB8 => Register::Rasr,
        _ => return None,
    })
}

/// The bits of `MPU_CTRL` that hold anything, B3.5.6.
const CTRL_WRITABLE: u32 =
    mask(mpu_ctrl::ENABLE) | mask(mpu_ctrl::HFNMIENA) | mask(mpu_ctrl::PRIVDEFENA);

/// The bits of `MPU_RASR` that hold anything, B3.5.9.
const RASR_WRITABLE: u32 = mask(mpu_rasr::ENABLE)
    | mask(mpu_rasr::SIZE)
    | mask(mpu_rasr::SRD)
    | mask(mpu_rasr::B)
    | mask(mpu_rasr::C)
    | mask(mpu_rasr::S)
    | mask(mpu_rasr::TEX)
    | mask(mpu_rasr::AP)
    | mask(mpu_rasr::XN);

/// `AP` of `011`, full access, which the default map gives everything, B3.5.3
/// `DefaultPermissions()`.
const FULL_ACCESS: u32 = 0b011;

/// The smallest region `MPU_RBAR` can hold a base for: `ADDR` starts at bit 5, B3.5.8.
const SMALLEST_REGION_BITS: u32 = 5;

/// What an access is for, which decides the permission it needs, B2.3.8.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Kind {
    Fetch,
    Read,
    Write,
}

/// The two things about the processor a check reads: B2.3.3's `FindPriv()`, and whether B1.5.4's
/// `ExecutionPriority()` is below 0.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct Context {
    pub(crate) privileged: bool,
    pub(crate) below_priority_zero: bool,
}

/// The MPU's registers, `MPU_CTRL` among them as the checks read it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) struct Mpu {
    /// The regions the part has, `MPU_TYPE.DREGION`. With none, there's no MPU, B3.5.4.
    regions: u8,
    ctrl: u32,
    rnr: u32,
    rbar: [u32; MOST_REGIONS],
    rasr: [u32; MOST_REGIONS],
    /// The context the exception model's own stack accesses run in, while it runs them. It never
    /// outlives one call of [`Family::with_mpu_context`], so a snapshot never holds one.
    #[serde(skip)]
    context: Option<Context>,
}

impl Mpu {
    /// An MPU of `regions`, none for a part without one, as a reset leaves it, every register zero,
    /// 100166 table 5-1.
    pub(crate) fn new(regions: u8) -> Self {
        Self {
            regions,
            ctrl: 0,
            rnr: 0,
            rbar: [0; MOST_REGIONS],
            rasr: [0; MOST_REGIONS],
            context: None,
        }
    }

    /// The regions the part has.
    pub(crate) fn regions(&self) -> u8 {
        self.regions
    }

    /// `MPU_CTRL.ENABLE`. B3.5.6 makes `HFNMIENA` set with `ENABLE` clear UNPREDICTABLE, and the
    /// MPU stays off then, since `ValidateAddress()` falls back to the default map there.
    pub(crate) fn enabled(&self) -> bool {
        is_set(mpu_ctrl::ENABLE, self.ctrl)
    }

    /// What the checks depend on, or nothing while the MPU is off and only the default map counts.
    fn in_force(&self) -> Option<(u32, [u32; MOST_REGIONS], [u32; MOST_REGIONS])> {
        self.enabled().then_some((self.ctrl, self.rbar, self.rasr))
    }

    /// Whether the processor may run an instruction fetched from `address` in `context`, B3.5.2
    /// and B3.5.3: read access and execute-never clear, with the MPU on or off.
    pub(crate) fn fetch_allows(&self, address: u32, context: Context) -> bool {
        self.permits(address, Kind::Fetch, context.privileged, || {
            context.below_priority_zero
        })
    }

    /// Whether an access of `kind` at `address` is allowed, B3.5.3's `ValidateAddress()` with
    /// B2.3.8's `CheckPermission()`. `privileged` is `ispriv`, already false for `AccType_UNPRIV`.
    /// `below_priority_zero` is only asked when `HFNMIENA` decides, since working it out walks the
    /// active exceptions. Vector table reads use the default map whatever the regions say, B3.5.1,
    /// so they mustn't come here.
    fn permits(
        &self,
        address: u32,
        kind: Kind,
        privileged: bool,
        below_priority_zero: impl FnOnce() -> bool,
    ) -> bool {
        let default = (FULL_ACCESS, default_execute_never(address));
        let ppb = address >> 20 == 0xE00;
        let permissions = if ppb
            || !self.enabled()
            || !is_set(mpu_ctrl::HFNMIENA, self.ctrl) && below_priority_zero()
        {
            Some(default)
        } else {
            self.matching(address)
                .map(|rasr| (get(mpu_rasr::AP, rasr), is_set(mpu_rasr::XN, rasr)))
                .or((is_set(mpu_ctrl::PRIVDEFENA, self.ctrl) && privileged).then_some(default))
        };
        // B3.5.1: no region can make system space executable.
        let system = address >> 29 == 0b111;
        permissions.is_some_and(|(ap, execute_never)| {
            grants(ap, kind, privileged) && !(kind == Kind::Fetch && (execute_never || system))
        })
    }

    /// Whether `MPU_RNR` holds what every write leaves it, B3.5.7: a region there is, or 0 on a
    /// processor with no MPU, where every write is dropped.
    pub(crate) fn selects_a_region(&self) -> bool {
        self.rnr < u32::from(self.regions.max(1))
    }

    /// The data accesses of the `size` bytes at `base` allowed whatever the privilege, B3.5.3.
    /// That's only when one region, or the background, holds all of them. Running below priority
    /// 0 with `HFNMIENA` clear only lets more through, since the default map grants every data
    /// access, B3.5.3 `DefaultPermissions()`. `base` is aligned to `size`, a power of two.
    pub(crate) fn inline_throughout(&self, base: u32, size: u32) -> Inline {
        // With no region deciding, the background grants nothing unprivileged, B3.5.6.
        self.deciding(base, size).map_or(Inline::Neither, |rasr| {
            // Table B3-15 never grants unprivileged software what it refuses privileged software,
            // and never a write without a read.
            let ap = get(mpu_rasr::AP, rasr);
            if grants(ap, Kind::Write, false) {
                Inline::Both
            } else if grants(ap, Kind::Read, false) {
                Inline::Reads
            } else {
                Inline::Neither
            }
        })
    }

    /// The `MPU_RASR` of the region deciding every one of the `size` bytes at `base`, B3.5.3: the
    /// highest one holding any of them in an enabled subregion, when it holds all of them so.
    /// `base` is aligned to `size`, a power of two, and so is every region, so a region holds all
    /// of them, none, or a part smaller than them.
    fn deciding(&self, base: u32, size: u32) -> Option<u32> {
        let (first, last) = (u64::from(base), u64::from(base) + u64::from(size) - 1);
        for region in (0..usize::from(self.regions)).rev() {
            let rasr = self.rasr[region];
            if !is_set(mpu_rasr::ENABLE, rasr) {
                continue;
            }
            let bits = (get(mpu_rasr::SIZE, rasr) + 1).max(SMALLEST_REGION_BITS);
            let start = u64::from(self.rbar[region]) >> bits << bits;
            let end = start + (1 << bits) - 1;
            if end < first || last < start {
                continue;
            }
            // A region smaller than the bytes is all of its eighths, as `matching` reads it.
            let subregion_bits = bits - 3;
            let (low, high) = (
                (first.max(start) - start) >> subregion_bits,
                (last.min(end) - start) >> subregion_bits,
            );
            let srd = get(mpu_rasr::SRD, rasr);
            let disabled = |subregion: u64| srd >> subregion & 1 != 0;
            if (low..=high).all(disabled) {
                continue;
            }
            let whole = start <= first && last <= end;
            return (whole && !(low..=high).any(disabled)).then_some(rasr);
        }
        None
    }

    /// The `MPU_RASR` of the highest enabled region holding `address` in an enabled subregion,
    /// B3.5.3.
    fn matching(&self, address: u32) -> Option<u32> {
        (0..usize::from(self.regions)).rev().find_map(|region| {
            let rasr = self.rasr[region];
            if !is_set(mpu_rasr::ENABLE, rasr) {
                return None;
            }
            // B3.5.3 makes a `SIZE` below 4 UNPREDICTABLE. `MPU_RBAR` can't place a region finer
            // than 32 bytes, so that's what you get.
            let bits = (get(mpu_rasr::SIZE, rasr) + 1).max(SMALLEST_REGION_BITS);
            if bits < 32 && (address ^ self.rbar[region]) >> bits != 0 {
                return None;
            }
            // `SRD` on a region below 256 bytes is UNPREDICTABLE, B3.5.9, and this is the
            // pseudocode's own reading of it: eighths of the region all the same.
            let subregion = (address >> (bits - 3)) & 0b111;
            let disabled = get(mpu_rasr::SRD, rasr) >> subregion & 1 != 0;
            (!disabled).then_some(rasr)
        })
    }
}

/// The default map's execute-never regions: peripherals, devices and system space, B3.5.3
/// `DefaultPermissions()` and Table B3-1.
fn default_execute_never(address: u32) -> bool {
    matches!(address >> 29, 0b010 | 0b101 | 0b110 | 0b111)
}

/// Whether `AP` grants an access of `kind`, B2.3.8 and Table B3-15. A fetch needs read access.
fn grants(ap: u32, kind: Kind, privileged: bool) -> bool {
    let write = kind == Kind::Write;
    match ap {
        0b001 => privileged,
        0b010 => privileged || !write,
        FULL_ACCESS => true,
        0b101 => privileged && !write,
        0b110 | 0b111 => !write,
        // `000` is no access. `100` is reserved and UNPREDICTABLE, and no access is the reading
        // that can't let anything through it shouldn't.
        _ => false,
    }
}

impl Family {
    /// The context an instruction's access runs in now: `FindPriv()` from `IPSR` and
    /// `CONTROL.nPRIV`, B2.3.3, and `ExecutionPriority()` below 0, B1.5.4.
    ///
    /// The priority comes from the exceptions the `Scs` model holds active and `FAULTMASK`, not
    /// from `IPSR`. They differ when NMI returns to a handler of priority 0 or more, and when NMI
    /// returns to Thread mode with HardFault still active.
    pub(crate) fn mpu_context(&self) -> Context {
        Context {
            privileged: self.state.privileged(),
            below_priority_zero: self.below_priority_zero(),
        }
    }

    /// B1.5.4's `ExecutionPriority()` below 0.
    pub(crate) fn below_priority_zero(&self) -> bool {
        self.scs.execution_priority(self.masks(), false, None) < 0
    }

    /// Runs `run` with every access the MPU checks checked in `context`, not the processor's own.
    /// It's for the stack accesses the pseudocode makes from a context `State` and the `Scs` model
    /// don't hold:
    /// - B1.5.6's `PushStack()` runs before `ExceptionTaken()`, so take the context before
    ///   `scs.acknowledge` makes the exception active.
    /// - B1.5.8's `PopStack()` runs after `CurrentMode`, `CONTROL.SPSEL` and `DeActivate()` change,
    ///   and before it writes `IPSR`. So after `scs.complete` and clearing `FAULTMASK`, it's
    ///   `Context { privileged: <Handler mode, or nPRIV clear>, ..self.mpu_context() }`.
    /// - B1.6's `PreserveFPState()` is privileged when `FPCCR.USER` is clear, and below priority 0
    ///   when `FPCCR.HFRDY` is clear or it's below 0 now.
    pub(crate) fn with_mpu_context<T>(
        &mut self,
        context: Context,
        run: impl FnOnce(&mut Self) -> T,
    ) -> T {
        let outer = self.mpu.context.replace(context);
        let answer = run(self);
        self.mpu.context = outer;
        answer
    }

    /// Whether an access runs privileged, B2.3.3's `FindPriv()` in the context
    /// [`Family::with_mpu_context`] set or the processor's own. `LDRT` and its kind never do.
    pub(crate) fn access_privileged(&self, unprivileged: bool) -> bool {
        !unprivileged
            && self
                .mpu
                .context
                .map_or_else(|| self.state.privileged(), |context| context.privileged)
    }

    /// Whether the MPU allows an access of `kind` at `address`, in the context
    /// [`Family::with_mpu_context`] set or the processor's own.
    fn mpu_permits(&self, address: u32, kind: Kind, unprivileged: bool) -> bool {
        let given = self.mpu.context;
        self.mpu
            .permits(address, kind, self.access_privileged(unprivileged), || {
                given.map_or_else(
                    || self.below_priority_zero(),
                    |context| context.below_priority_zero,
                )
            })
    }

    /// Whether the MPU allows a data access at `address`, B3.5, with the privilege the access runs
    /// at. Regions are at least 32 bytes and aligned to their size, and an access reaching here is
    /// aligned to its own, so its first byte decides for all of them. A refusal carries `address`,
    /// which is `MMFAR`'s, B3.5.3 `ValidateAddress()`. An unaligned access is checked a byte at a
    /// time, B2.3.5 `MemU_with_priv()`, so that's the byte refused, not where the access starts.
    pub(crate) fn mpu_check(
        &self,
        address: u32,
        kind: Kind,
        unprivileged: bool,
    ) -> Result<(), Refused> {
        if self.mpu_permits(address, kind, unprivileged) {
            Ok(())
        } else {
            Err(Refused::Mpu(address))
        }
    }

    /// Whether the processor may run an instruction fetched from `address` now, B3.5.2 and B3.5.3:
    /// read access at the processor's privilege and execute-never clear, with the MPU on or off.
    pub(crate) fn mpu_fetch_allows(&self, address: u32) -> bool {
        self.mpu_permits(address, Kind::Fetch, false)
    }

    /// Reads the MPU register at `offset` into the system control space, B3.5.4.
    pub(crate) fn mpu_read(&self, offset: u64) -> u32 {
        let mpu = &self.mpu;
        let region = mpu.rnr as usize;
        match register(offset) {
            Some(Register::Type) => set(mpu_type::DREGION, 0, u32::from(mpu.regions)),
            // B3.5.4: with no MPU, `MPU_CTRL` is RAZ/WI and the rest are reserved, read as zero.
            _ if mpu.regions == 0 => 0,
            Some(Register::Ctrl) => mpu.ctrl,
            Some(Register::Rnr) => mpu.rnr,
            Some(Register::Rbar) => mpu.rbar[region] | mpu.rnr & mask(mpu_rbar::REGION),
            Some(Register::Rasr) => mpu.rasr[region],
            None => 0,
        }
    }

    /// Writes the MPU register at `offset` into the system control space, B3.5.4, and drops what
    /// was translated when what the checks depend on changed.
    pub(crate) fn mpu_write(&mut self, offset: u64, value: u32) {
        let before = self.mpu.in_force();
        let mpu = &mut self.mpu;
        let regions = u32::from(mpu.regions);
        match register(offset) {
            // B3.5.4: with no MPU, `MPU_CTRL` is RAZ/WI and the rest are reserved, and drop writes.
            _ if regions == 0 => {}
            Some(Register::Ctrl) => mpu.ctrl = value & CTRL_WRITABLE,
            Some(Register::Rnr) => {
                // B3.5.7: a region past the last is UNPREDICTABLE, and the write is dropped.
                let region = get(mpu_rnr::REGION, value);
                if region < regions {
                    mpu.rnr = region;
                }
            }
            Some(Register::Rbar) => {
                if is_set(mpu_rbar::VALID, value) {
                    // B3.5.8: a region past the last is UNPREDICTABLE, and the write is dropped.
                    let region = get(mpu_rbar::REGION, value);
                    if region >= regions {
                        return;
                    }
                    mpu.rnr = region;
                }
                mpu.rbar[mpu.rnr as usize] = value & mask(mpu_rbar::ADDR);
            }
            Some(Register::Rasr) => mpu.rasr[mpu.rnr as usize] = value & RASR_WRITABLE,
            // B3.5.5: `MPU_TYPE` is read-only.
            Some(Register::Type) | None => {}
        }
        if self.mpu.in_force() != before {
            self.mpu_changed(self.mpu.enabled());
        }
    }
}

#[cfg(test)]
mod tests {
    use super::super::registers::{cfsr, control, fpccr, shcsr};
    use super::super::scs::SCS_BASE;
    use super::super::scs::exception::{HARD_FAULT, MEM_MANAGE, NMI, PEND_SV, SYS_TICK};
    use super::super::translate::testing::spec_of;
    use super::super::translate::testing::{Bench, CODE, DEVICE, RAM};
    use super::super::translate::{Attributes, Size};
    use super::*;
    use crate::cpu::armv7m::family::{Position, Request};
    use crate::emulator::{Exit, Processor};
    use crate::machine::armv7m::{Fpu, MpuRegions, Variant};
    use crate::soc::{FieldSpec, Width};
    use crate::time::VirtualNanos;

    /// `STR r0, [r1]`, A7.7.161.
    const STR: u16 = 0x6008;

    fn bench() -> Bench {
        Bench::new(&[0xBF00])
    }

    fn write(bench: &mut Bench, offset: u64, value: u32) {
        bench.core.debugger_access(
            Some(u64::from(value)),
            SCS_BASE + offset,
            Width::W32,
            VirtualNanos(0),
        );
    }

    fn read(bench: &mut Bench, offset: u64) -> u32 {
        bench
            .core
            .debugger_access(None, SCS_BASE + offset, Width::W32, VirtualNanos(0))
            .and_then(|value| u32::try_from(value).ok())
            .expect("the processor's own bus")
    }

    /// `MPU_CTRL` with `fields` set.
    fn mpu_ctrl(fields: &[&FieldSpec]) -> u32 {
        fields.iter().fold(0, |value, field| set(field, value, 1))
    }

    /// An enabled region of 2^(`size` + 1) bytes with access `ap`.
    fn attributes(size: u32, ap: u32) -> u32 {
        let value = set(mpu_rasr::ENABLE, 0, 1);
        let value = set(mpu_rasr::SIZE, value, size);
        set(mpu_rasr::AP, value, ap)
    }

    /// Programs `region` with `MPU_RBAR`'s `VALID`, as an `STM` to the aliases would.
    fn region(bench: &mut Bench, region: u32, base: u32, rasr: u32) {
        let value = set(mpu_rbar::VALID, base, 1);
        write(bench, RBAR, set(mpu_rbar::REGION, value, region));
        write(bench, RASR, rasr);
    }

    fn allows(bench: &mut Bench, address: u32, write: bool) -> bool {
        let kind = if write { Kind::Write } else { Kind::Read };
        bench.core.mpu_check(address, kind, false).is_ok()
    }

    fn unprivileged(bench: &mut Bench) {
        bench.core.state.control = mask(control::NPRIV);
    }

    /// Takes exception `number` as the exception model would, active in the `Scs` model and in
    /// `IPSR`.
    fn take(core: &mut Family, number: u16) {
        core.scs.pend(number);
        let masks = core.masks();
        assert_eq!(core.scs.acknowledge(masks), Some(number));
        core.state.ipsr = u32::from(number);
    }

    /// The MPU on with `HFNMIENA` clear, and one region over RAM granting `ap`.
    fn one_region(ap: u32) -> Bench {
        let mut bench = bench();
        region(&mut bench, 0, RAM, attributes(15, ap));
        write(&mut bench, CTRL, mpu_ctrl(&[mpu_ctrl::ENABLE]));
        bench
    }

    fn stack_read(core: &mut Family, address: u32) -> Result<u32, Refused> {
        core.access(
            Request::read(address, Size::Word),
            Attributes::ALIGNED,
            Position::Processor,
        )
    }

    #[test]
    fn mpu_type_says_eight_unified_regions() {
        let mut bench = bench();
        assert_eq!(read(&mut bench, TYPE), 0x0000_0800);
        write(&mut bench, TYPE, 0xFFFF_FFFF);
        assert_eq!(read(&mut bench, TYPE), 0x0000_0800, "read-only");
    }

    /// With no MPU, `MPU_TYPE.DREGION` is zero and `MPU_CTRL` is RAZ/WI, so the default map is all
    /// there is, B3.5.4 and B3.5.5.
    #[test]
    fn a_part_without_an_mpu_has_none_to_turn_on() {
        let command = spec_of(Variant::M4, Fpu::FpV4Sp, MpuRegions::None);
        let mut bench = Bench::of(&command, &[0xBF00]);
        assert_eq!(read(&mut bench, TYPE), 0);
        region(&mut bench, 0, RAM, attributes(15, 0));
        write(&mut bench, CTRL, mpu_ctrl(&[mpu_ctrl::ENABLE]));
        assert_eq!(read(&mut bench, CTRL), 0);
        assert!(!bench.core.mpu.enabled());
        assert_eq!((read(&mut bench, RBAR), read(&mut bench, RASR)), (0, 0));
    }

    /// An MPU of sixteen regions answers `DREGION` 16, and its last region is the one that
    /// decides, B3.5.3 and B3.5.5.
    #[test]
    fn an_mpu_of_sixteen_regions_uses_every_one() {
        let command = spec_of(Variant::M7, Fpu::None, MpuRegions::Sixteen);
        let mut bench = Bench::of(&command, &[0xBF00]);
        assert_eq!(read(&mut bench, TYPE), set(mpu_type::DREGION, 0, 16));
        region(&mut bench, 0, RAM, attributes(15, 0b011));
        region(&mut bench, 15, RAM, attributes(15, 0b110));
        write(&mut bench, CTRL, mpu_ctrl(&[mpu_ctrl::ENABLE]));
        assert_eq!(read(&mut bench, RNR), 15);
        assert!(allows(&mut bench, RAM, false));
        assert!(
            !allows(&mut bench, RAM, true),
            "region 15 is read-only and wins"
        );
        write(&mut bench, RNR, 16);
        assert_eq!(read(&mut bench, RNR), 15, "past the last");
    }

    #[test]
    fn every_register_resets_to_zero() {
        let mut bench = bench();
        region(&mut bench, 7, 0x2000_0000, attributes(9, 3));
        write(
            &mut bench,
            CTRL,
            mpu_ctrl(&[mpu_ctrl::ENABLE, mpu_ctrl::PRIVDEFENA]),
        );
        bench.core.reset();
        for offset in [CTRL, RNR, RBAR, RASR] {
            assert_eq!(read(&mut bench, offset), 0, "{offset:#x}");
        }
    }

    #[test]
    fn mpu_ctrl_keeps_its_three_bits() {
        let mut bench = bench();
        write(&mut bench, CTRL, 0xFFFF_FFFF);
        assert_eq!(read(&mut bench, CTRL), 0b111);
        write(&mut bench, CTRL, mpu_ctrl(&[mpu_ctrl::PRIVDEFENA]));
        assert_eq!(read(&mut bench, CTRL), 0b100);
        assert!(!bench.core.mpu.enabled());
    }

    #[test]
    fn rnr_selects_the_region_rbar_and_rasr_reach() {
        let mut bench = bench();
        for number in 0..8 {
            write(&mut bench, RNR, number);
            write(&mut bench, RBAR, 0x2000_0000 + number * 0x100 + 0xF);
            write(&mut bench, RASR, attributes(7, number % 8));
        }
        for number in 0..8 {
            write(&mut bench, RNR, number);
            assert_eq!(read(&mut bench, RNR), number);
            assert_eq!(
                read(&mut bench, RBAR),
                0x2000_0000 + number * 0x100 + number,
                "ADDR kept from bit 5, VALID reads zero, REGION reads MPU_RNR"
            );
            assert_eq!(read(&mut bench, RASR), attributes(7, number % 8));
        }
    }

    #[test]
    fn rbar_with_valid_selects_its_region_first() {
        let mut bench = bench();
        write(&mut bench, RNR, 1);
        region(&mut bench, 6, 0x0800_0000, attributes(19, 6));
        assert_eq!(read(&mut bench, RNR), 6, "VALID updates MPU_RNR");
        assert_eq!(read(&mut bench, RBAR), 0x0800_0006);
        assert_eq!(read(&mut bench, RASR), attributes(19, 6));
        write(&mut bench, RBAR, set(mpu_rbar::REGION, 0x1000_0000, 2));
        assert_eq!(read(&mut bench, RNR), 6, "without VALID, REGION is ignored");
        assert_eq!(read(&mut bench, RBAR), 0x1000_0006);
        write(&mut bench, RNR, 1);
        assert_eq!(read(&mut bench, RBAR), 1, "region 1 untouched");
    }

    #[test]
    fn a_region_past_the_last_is_ignored() {
        let mut bench = bench();
        write(&mut bench, RNR, 3);
        write(&mut bench, RNR, 8);
        assert_eq!(read(&mut bench, RNR), 3);
        write(&mut bench, RNR, 0x105);
        assert_eq!(read(&mut bench, RNR), 5, "bits 31 to 8 are reserved");
        write(&mut bench, RBAR, 0x2000_0000 | set(mpu_rbar::VALID, 9, 1));
        assert_eq!(read(&mut bench, RNR), 5);
        assert!((0..8).all(|number| {
            write(&mut bench, RNR, number);
            read(&mut bench, RBAR) == number
        }));
    }

    #[test]
    fn rasr_keeps_its_fields_and_drops_reserved_bits() {
        let mut bench = bench();
        write(&mut bench, RASR, 0xFFFF_FFFF);
        assert_eq!(read(&mut bench, RASR), 0x173F_FF3F);
    }

    #[test]
    fn a_byte_or_halfword_write_changes_nothing() {
        let mut bench = bench();
        write(&mut bench, RNR, 2);
        let narrow = |bench: &mut Bench, offset: u64, width: Width, value: u32| {
            bench.core.debugger_access(
                Some(u64::from(value)),
                SCS_BASE + offset,
                width,
                VirtualNanos(0),
            );
        };
        narrow(&mut bench, CTRL, Width::W8, 1);
        narrow(&mut bench, RNR, Width::W16, 5);
        narrow(&mut bench, RASR + 2, Width::W16, 0x0300);
        assert_eq!(read(&mut bench, CTRL), 0);
        assert!(!bench.core.mpu.enabled());
        assert_eq!(read(&mut bench, RNR), 2);
        assert_eq!(read(&mut bench, RASR), 0);
    }

    #[test]
    fn the_aliases_reach_the_same_pair() {
        let mut bench = bench();
        for (pair, number) in (0..4).zip([0, 3, 5, 7]) {
            let value = set(mpu_rbar::VALID, 0x2000_0000 + number * 0x100, 1);
            write(
                &mut bench,
                RBAR + 8 * pair,
                set(mpu_rbar::REGION, value, number),
            );
            write(&mut bench, RASR + 8 * pair, attributes(7, number));
        }
        assert_eq!(read(&mut bench, RNR), 7);
        for number in [0, 3, 5, 7] {
            write(&mut bench, RNR, number);
            for pair in 0..4 {
                assert_eq!(
                    read(&mut bench, RBAR + 8 * pair),
                    0x2000_0000 + number * 0x100 + number
                );
                assert_eq!(read(&mut bench, RASR + 8 * pair), attributes(7, number));
            }
        }
    }

    #[test]
    fn a_disabled_mpu_allows_every_data_access() {
        let mut bench = bench();
        region(&mut bench, 0, 0, attributes(31, 0));
        unprivileged(&mut bench);
        for address in [CODE, RAM, DEVICE, 0xA000_0000, 0xE000_ED00, 0xF000_0000] {
            assert!(allows(&mut bench, address, true), "{address:#x}");
            assert!(allows(&mut bench, address, false), "{address:#x}");
        }
    }

    #[test]
    fn the_default_map_refuses_fetches_from_its_execute_never_regions() {
        let bench = bench();
        for (address, runs) in [
            (0x0000_0000, true),
            (0x2000_0000, true),
            (0x4000_0000, false),
            (0x6000_0000, true),
            (0x8000_0000, true),
            (0xA000_0000, false),
            (0xC000_0000, false),
            (0xE000_0000, false),
            (0xFFFF_FFFE, false),
        ] {
            assert_eq!(bench.core.mpu_fetch_allows(address), runs, "{address:#x}");
        }
    }

    #[test]
    fn an_access_no_region_matches_is_refused() {
        let mut bench = bench();
        region(&mut bench, 0, RAM, attributes(15, 3));
        write(&mut bench, CTRL, mpu_ctrl(&[mpu_ctrl::ENABLE]));
        assert!(allows(&mut bench, RAM + 0xFFFC, true));
        assert!(!allows(&mut bench, RAM + 0x1_0000, false));
        assert!(!allows(&mut bench, CODE, false));
        assert!(!bench.core.mpu_fetch_allows(CODE));
        assert!(bench.core.mpu_fetch_allows(RAM));
    }

    #[test]
    fn the_ppb_uses_the_default_map_with_the_mpu_on() {
        let mut bench = bench();
        write(&mut bench, CTRL, mpu_ctrl(&[mpu_ctrl::ENABLE]));
        unprivileged(&mut bench);
        assert!(allows(&mut bench, 0xE000_E010, true));
        assert!(allows(&mut bench, 0xE00F_FFFC, false));
        assert!(!allows(&mut bench, 0xE010_0000, false), "past the PPB");
    }

    #[test]
    fn privdefena_is_a_background_for_privileged_accesses_only() {
        let mut bench = bench();
        write(
            &mut bench,
            CTRL,
            mpu_ctrl(&[mpu_ctrl::ENABLE, mpu_ctrl::PRIVDEFENA]),
        );
        assert!(allows(&mut bench, RAM, true));
        assert!(bench.core.mpu_fetch_allows(CODE));
        assert!(
            !bench.core.mpu_fetch_allows(DEVICE),
            "the background keeps its execute-never"
        );
        unprivileged(&mut bench);
        assert!(!allows(&mut bench, RAM, false));
        assert!(!bench.core.mpu_fetch_allows(CODE));
    }

    #[test]
    fn the_highest_matching_region_wins() {
        let mut bench = bench();
        region(&mut bench, 2, RAM, attributes(15, 0b110));
        region(&mut bench, 5, RAM + 0x100, attributes(7, 0b011));
        region(&mut bench, 1, RAM, attributes(31, 0b000));
        write(&mut bench, CTRL, mpu_ctrl(&[mpu_ctrl::ENABLE]));
        assert!(
            allows(&mut bench, RAM + 0x100, true),
            "region 5 over region 2"
        );
        assert!(
            !allows(&mut bench, RAM + 0x200, true),
            "region 2's read-only"
        );
        assert!(allows(&mut bench, RAM + 0x200, false));
        assert!(!allows(&mut bench, CODE, false), "region 1's no access");
    }

    #[test]
    fn a_disabled_subregion_falls_through() {
        let mut bench = bench();
        region(&mut bench, 0, RAM, attributes(10, 0b110));
        // 2 KB in eighths of 256 bytes, the second and last disabled.
        region(
            &mut bench,
            1,
            RAM,
            set(mpu_rasr::SRD, attributes(10, 0b011), 0b1000_0010),
        );
        write(&mut bench, CTRL, mpu_ctrl(&[mpu_ctrl::ENABLE]));
        assert!(allows(&mut bench, RAM + 0xFC, true));
        assert!(!allows(&mut bench, RAM + 0x100, true), "region 0 below it");
        assert!(allows(&mut bench, RAM + 0x100, false));
        assert!(allows(&mut bench, RAM + 0x200, true));
        assert!(!allows(&mut bench, RAM + 0x700, true));
        write(&mut bench, RNR, 0);
        write(&mut bench, RASR, 0);
        assert!(!allows(&mut bench, RAM + 0x700, false), "nothing below it");
        write(
            &mut bench,
            CTRL,
            mpu_ctrl(&[mpu_ctrl::ENABLE, mpu_ctrl::PRIVDEFENA]),
        );
        assert!(
            allows(&mut bench, RAM + 0x700, true),
            "the background below it"
        );
    }

    #[test]
    fn a_region_of_four_gigabytes_matches_every_address() {
        let mut bench = bench();
        region(&mut bench, 0, 0, attributes(31, 0b010));
        write(&mut bench, CTRL, mpu_ctrl(&[mpu_ctrl::ENABLE]));
        unprivileged(&mut bench);
        for address in [0, RAM, 0x8000_0000, 0xDFFF_FFFC] {
            assert!(allows(&mut bench, address, false), "{address:#x}");
            assert!(!allows(&mut bench, address, true), "{address:#x}");
        }
    }

    #[test]
    fn a_region_of_two_gigabytes_is_half_the_map() {
        let mut bench = bench();
        region(&mut bench, 0, 0x8000_0000, attributes(30, 0b011));
        write(&mut bench, CTRL, mpu_ctrl(&[mpu_ctrl::ENABLE]));
        assert!(allows(&mut bench, 0x8000_0000, true));
        assert!(allows(&mut bench, 0xDFFF_FFFC, true));
        assert!(!allows(&mut bench, 0x7FFF_FFFC, true));
    }

    #[test]
    fn every_ap_encoding_grants_what_the_table_says() {
        // Table B3-15: privileged read, privileged write, unprivileged read, unprivileged write.
        let table = [
            (0b000, [false, false, false, false]),
            (0b001, [true, true, false, false]),
            (0b010, [true, true, true, false]),
            (0b011, [true, true, true, true]),
            (0b100, [false, false, false, false]),
            (0b101, [true, false, false, false]),
            (0b110, [true, false, true, false]),
            (0b111, [true, false, true, false]),
        ];
        for (ap, granted) in table {
            let mut bench = bench();
            region(&mut bench, 4, RAM, attributes(15, ap));
            write(&mut bench, CTRL, mpu_ctrl(&[mpu_ctrl::ENABLE]));
            let mut found = [
                allows(&mut bench, RAM, false),
                allows(&mut bench, RAM, true),
                false,
                false,
            ];
            unprivileged(&mut bench);
            found[2] = allows(&mut bench, RAM, false);
            found[3] = allows(&mut bench, RAM, true);
            assert_eq!(found, granted, "AP {ap:03b}");
        }
    }

    #[test]
    fn an_unprivileged_access_from_privileged_code_is_checked_unprivileged() {
        let mut bench = bench();
        region(&mut bench, 0, RAM, attributes(15, 0b001));
        write(
            &mut bench,
            CTRL,
            mpu_ctrl(&[mpu_ctrl::ENABLE, mpu_ctrl::PRIVDEFENA]),
        );
        bench.core.state.ipsr = 11;
        assert!(bench.core.mpu_check(RAM, Kind::Read, false).is_ok());
        assert_eq!(
            bench.core.mpu_check(RAM, Kind::Read, true),
            Err(Refused::Mpu(RAM))
        );
        assert_eq!(
            bench.core.mpu_check(CODE, Kind::Read, true),
            Err(Refused::Mpu(CODE)),
            "the background is for privileged accesses"
        );
    }

    #[test]
    fn thread_mode_with_npriv_is_unprivileged() {
        let mut bench = bench();
        region(&mut bench, 0, RAM, attributes(15, 0b001));
        write(&mut bench, CTRL, mpu_ctrl(&[mpu_ctrl::ENABLE]));
        unprivileged(&mut bench);
        assert!(!allows(&mut bench, RAM, false));
        bench.core.state.ipsr = 16;
        assert!(allows(&mut bench, RAM, true), "Handler mode is privileged");
    }

    #[test]
    fn hfnmiena_decides_for_handlers_below_priority_zero() {
        let below: [fn(&mut Family); 3] = [
            |core| take(core, NMI),
            |core| take(core, HARD_FAULT),
            |core| core.state.faultmask = 1,
        ];
        for boost in below {
            let mut bench = one_region(0b000);
            boost(&mut bench.core);
            assert!(allows(&mut bench, RAM, true), "the default map");
            assert!(
                bench.core.mpu_check(RAM, Kind::Write, true).is_ok(),
                "Table B3-12: an unprivileged access uses the default map too"
            );
            assert!(!bench.core.mpu_fetch_allows(DEVICE));
            write(
                &mut bench,
                CTRL,
                mpu_ctrl(&[mpu_ctrl::ENABLE, mpu_ctrl::HFNMIENA]),
            );
            assert!(!allows(&mut bench, RAM, false), "the MPU");
        }
        let mut handler = one_region(0b000);
        handler.core.state.ipsr = 4;
        assert!(
            !allows(&mut handler, RAM, false),
            "MemManage is priority 0 or more"
        );
    }

    #[test]
    fn execution_priority_comes_from_the_active_exceptions_not_ipsr() {
        // NMI preempted HardFault and returned to Thread mode, which `CCR.NONBASETHRDENA` allows.
        let mut bench = one_region(0b000);
        take(&mut bench.core, HARD_FAULT);
        take(&mut bench.core, NMI);
        assert!(bench.core.scs.complete(NMI));
        bench.core.state.ipsr = 0;
        assert!(bench.core.mpu_context().below_priority_zero);
        assert!(allows(&mut bench, RAM, true), "HardFault is still active");

        // NMI preempted SysTick at priority 0, and its return has run `DeActivate()` but not yet
        // written `IPSR`.
        let mut bench = one_region(0b000);
        take(&mut bench.core, SYS_TICK);
        take(&mut bench.core, NMI);
        assert!(bench.core.scs.complete(NMI));
        assert_eq!(bench.core.state.ipsr, u32::from(NMI));
        assert!(!bench.core.mpu_context().below_priority_zero);
        assert!(!allows(&mut bench, RAM, false), "SysTick's priority is 0");
    }

    /// The manual's own case: a HardFault handler returns to Thread mode with `nPRIV` set, and
    /// the process stack is in a privileged-only region.
    #[test]
    fn an_unstack_is_checked_as_the_thread_it_returns_to() {
        let mut bench = one_region(0b001);
        let frame = RAM + 0x100;
        bench.core.state.control = mask(control::NPRIV);
        take(&mut bench.core, HARD_FAULT);
        assert_eq!(
            stack_read(&mut bench.core, frame),
            Ok(0),
            "the handler itself runs on the default map"
        );
        // B1.5.8: `CurrentMode` and `DeActivate()` change before `PopStack()` reads anything.
        assert!(bench.core.scs.complete(HARD_FAULT));
        let thread = Context {
            privileged: false,
            ..bench.core.mpu_context()
        };
        assert!(!thread.below_priority_zero);
        let popped = bench
            .core
            .with_mpu_context(thread, |core| stack_read(core, frame + 4));
        assert_eq!(popped, Err(Refused::Mpu(frame + 4)), "MUNSTKERR");
    }

    #[test]
    fn a_push_is_checked_as_the_context_it_preempts() {
        let mut bench = one_region(0b001);
        unprivileged(&mut bench);
        // B1.5.6: `PushStack()` runs before `ExceptionTaken()` makes HardFault active.
        let preempted = bench.core.mpu_context();
        take(&mut bench.core, HARD_FAULT);
        let pushed = bench.core.with_mpu_context(preempted, |core| {
            core.access(
                Request::write(RAM + 0x20, Size::Word, 1),
                Attributes::ALIGNED,
                Position::Processor,
            )
        });
        assert_eq!(pushed, Err(Refused::Mpu(RAM + 0x20)), "MSTKERR");
        assert_eq!(bench.word(RAM + 0x20), 0);
    }

    #[test]
    fn a_stack_context_holds_only_while_it_runs() {
        let mut bench = one_region(0b001);
        let refused = Context {
            privileged: false,
            below_priority_zero: false,
        };
        let bypassed = Context {
            privileged: false,
            below_priority_zero: true,
        };
        let (outer, inner) = bench.core.with_mpu_context(refused, |core| {
            let inner = core.with_mpu_context(bypassed, |core| stack_read(core, RAM));
            (stack_read(core, RAM), inner)
        });
        assert_eq!(inner, Ok(0), "the innermost context decides");
        assert_eq!(
            outer,
            Err(Refused::Mpu(RAM)),
            "and the outer one comes back"
        );
        assert_eq!(
            stack_read(&mut bench.core, RAM),
            Ok(0),
            "then the processor's own"
        );
        assert!(
            !bench
                .core
                .with_mpu_context(refused, |core| core.mpu_fetch_allows(RAM)),
            "a fetch reads it too"
        );
    }

    #[test]
    fn hfnmiena_without_enable_leaves_the_mpu_off() {
        let mut bench = bench();
        region(&mut bench, 0, 0, attributes(31, 0b000));
        write(
            &mut bench,
            CTRL,
            mpu_ctrl(&[mpu_ctrl::HFNMIENA, mpu_ctrl::PRIVDEFENA]),
        );
        assert!(!bench.core.mpu.enabled());
        assert!(allows(&mut bench, RAM, true));
        assert!(bench.core.mpu_fetch_allows(CODE));
    }

    #[test]
    fn a_fetch_needs_read_access_and_xn_clear() {
        let mut bench = bench();
        region(&mut bench, 0, CODE, attributes(15, 0b101));
        region(
            &mut bench,
            1,
            RAM,
            set(mpu_rasr::XN, attributes(15, 0b011), 1),
        );
        region(&mut bench, 2, DEVICE, attributes(15, 0b011));
        write(&mut bench, CTRL, mpu_ctrl(&[mpu_ctrl::ENABLE]));
        assert!(bench.core.mpu_fetch_allows(CODE), "privileged read-only");
        assert!(!bench.core.mpu_fetch_allows(RAM), "XN");
        assert!(allows(&mut bench, RAM, true), "XN leaves data alone");
        assert!(
            bench.core.mpu_fetch_allows(DEVICE),
            "a region's XN replaces the default map's"
        );
        unprivileged(&mut bench);
        assert!(!bench.core.mpu_fetch_allows(CODE), "no unprivileged read");
    }

    #[test]
    fn system_space_stays_execute_never() {
        let mut bench = bench();
        region(&mut bench, 0, 0xE000_0000, attributes(28, 0b011));
        write(&mut bench, CTRL, mpu_ctrl(&[mpu_ctrl::ENABLE]));
        assert!(!bench.core.mpu_fetch_allows(0xE000_0000), "the PPB");
        assert!(!bench.core.mpu_fetch_allows(0xE010_0000));
        assert!(!bench.core.mpu_fetch_allows(0xF000_0000));
        assert!(allows(&mut bench, 0xF000_0000, true));
    }

    #[test]
    fn a_size_below_thirty_two_bytes_acts_as_thirty_two() {
        let mut bench = bench();
        region(&mut bench, 0, RAM, attributes(1, 0b011));
        write(&mut bench, CTRL, mpu_ctrl(&[mpu_ctrl::ENABLE]));
        assert!(allows(&mut bench, RAM + 0x1C, true));
        assert!(!allows(&mut bench, RAM + 0x20, true));
    }

    #[test]
    fn subregions_of_a_small_region_follow_the_pseudocode() {
        let mut bench = bench();
        // 64 bytes in eighths of 8 bytes, the first disabled.
        region(
            &mut bench,
            0,
            RAM,
            set(mpu_rasr::SRD, attributes(5, 0b011), 1),
        );
        write(&mut bench, CTRL, mpu_ctrl(&[mpu_ctrl::ENABLE]));
        assert!(!allows(&mut bench, RAM + 4, false));
        assert!(allows(&mut bench, RAM + 8, false));
        assert!(allows(&mut bench, RAM + 0x3C, false));
        assert!(!allows(&mut bench, RAM + 0x40, false));
    }

    #[test]
    fn a_base_not_aligned_to_its_size_is_aligned_down() {
        let mut bench = bench();
        region(&mut bench, 0, RAM + 0x300, attributes(9, 0b011));
        write(&mut bench, CTRL, mpu_ctrl(&[mpu_ctrl::ENABLE]));
        assert!(allows(&mut bench, RAM, true));
        assert!(allows(&mut bench, RAM + 0x3FC, true));
        assert!(!allows(&mut bench, RAM + 0x400, true));
    }

    #[test]
    fn a_refused_access_never_reaches_memory() {
        let mut bench = bench();
        region(&mut bench, 0, RAM, attributes(15, 0b010));
        write(
            &mut bench,
            CTRL,
            mpu_ctrl(&[mpu_ctrl::ENABLE, mpu_ctrl::PRIVDEFENA]),
        );
        unprivileged(&mut bench);
        let store = |bench: &mut Bench, value| {
            bench.core.access(
                Request::write(RAM + 0x10, Size::Word, value),
                Attributes::default(),
                Position::Processor,
            )
        };
        assert_eq!(
            store(&mut bench, 0x1234_5678),
            Err(Refused::Mpu(RAM + 0x10))
        );
        assert_eq!(bench.word(RAM + 0x10), 0);
        bench.core.state.control = 0;
        assert_eq!(store(&mut bench, 0x1234_5678), Ok(0x1234_5678));
        assert_eq!(bench.word(RAM + 0x10), 0x1234_5678);
        assert!(bench.bus.accesses.is_empty());
    }

    #[test]
    fn every_byte_of_an_unaligned_access_is_checked() {
        let mut bench = bench();
        region(&mut bench, 0, RAM, attributes(4, 0b011));
        write(&mut bench, CTRL, mpu_ctrl(&[mpu_ctrl::ENABLE]));
        let access = |bench: &mut Bench, write, address, size| {
            bench.core.access(
                Request {
                    address,
                    size,
                    write,
                },
                Attributes::default(),
                Position::Processor,
            )
        };
        assert_eq!(access(&mut bench, None, RAM + 0x1B, Size::Word), Ok(0));
        assert_eq!(
            access(&mut bench, None, RAM + 0x1E, Size::Word),
            Err(Refused::Mpu(RAM + 0x20)),
            "MMFAR is the byte refused"
        );
        assert_eq!(
            access(&mut bench, Some(0xBBAA), RAM + 0x1F, Size::Halfword),
            Err(Refused::Mpu(RAM + 0x20))
        );
        assert_eq!(
            bench.word(RAM + 0x1C),
            0xAA00_0000,
            "B2.3.5 stores the bytes before the refused one"
        );
    }

    #[test]
    fn an_unaligned_access_to_device_memory_goes_byte_by_byte() {
        let mut bench = bench();
        // `TEX`, `C` and `B` all clear make it Strongly-ordered, Table B3-13.
        region(&mut bench, 0, RAM, attributes(15, 0b011));
        write(&mut bench, CTRL, mpu_ctrl(&[mpu_ctrl::ENABLE]));
        bench.write(RAM, &[1, 2, 3, 4, 5]);
        let loaded = bench.core.access(
            Request::read(RAM + 1, Size::Word),
            Attributes::default(),
            Position::Processor,
        );
        assert_eq!(loaded, Ok(0x0504_0302));
    }

    #[test]
    fn a_snapshot_keeps_the_mpu() {
        let mut bench = bench();
        region(&mut bench, 3, RAM, attributes(15, 0b110));
        write(&mut bench, CTRL, mpu_ctrl(&[mpu_ctrl::ENABLE]));
        let saved = bench.core.save();
        bench.core.reset();
        assert!(allows(&mut bench, CODE, true));
        bench.core.load(&saved).unwrap();
        assert!(!allows(&mut bench, RAM, true));
        assert!(!allows(&mut bench, CODE, false));
        assert_eq!(read(&mut bench, RNR), 3);
        assert_eq!(read(&mut bench, RBAR), RAM | 3);
    }

    /// A snapshot taken with the MPU on puts back a processor whose every data access is checked,
    /// the ones that would run inline included.
    #[test]
    fn a_snapshot_with_the_mpu_on_checks_every_access_once_loaded() {
        let mut bench = Bench::new(&[STR]);
        region(&mut bench, 0, RAM, attributes(15, 0b110));
        write(
            &mut bench,
            CTRL,
            mpu_ctrl(&[mpu_ctrl::ENABLE, mpu_ctrl::PRIVDEFENA]),
        );
        let saved = bench.core.save();
        bench.core.reset();
        bench.core.load(&saved).unwrap();
        bench.core.state.r[..2].copy_from_slice(&[0x1234, RAM + 0x100]);
        bench.run(1);
        assert_eq!(bench.word(RAM + 0x100), 0, "read-only");
    }

    /// A snapshot whose `MPU_RNR` names a region past the last is refused, since no write leaves
    /// one, B3.5.7, and the next access to `MPU_RBAR` would have nothing to reach.
    #[test]
    fn a_snapshot_naming_a_region_past_the_last_is_refused() {
        let mut bench = bench();
        bench.core.mpu.rnr = u32::from(bench.core.mpu.regions());
        let saved = bench.core.save();
        bench.core.mpu.rnr = 2;
        assert!(bench.core.load(&saved).is_err());
        assert_eq!(read(&mut bench, RBAR), 2, "left as it was");
    }

    /// With the MPU on, a page one region decides for both privilege levels takes inline what that
    /// region grants both, once an access found it out, and a change to the MPU forgets it.
    #[test]
    fn a_page_one_region_decides_is_inline_as_far_as_it_grants_both_privileges() {
        let mut bench = Bench::new(&[STR]);
        region(&mut bench, 0, RAM, attributes(15, 0b010));
        write(
            &mut bench,
            CTRL,
            mpu_ctrl(&[mpu_ctrl::ENABLE, mpu_ctrl::PRIVDEFENA]),
        );
        assert_eq!(bench.core.inline(RAM), Inline::Neither);
        bench.core.state.r[..2].copy_from_slice(&[0x1234, RAM + 0x100]);
        bench.run(1);
        assert_eq!(bench.word(RAM + 0x100), 0x1234, "privileged may write");
        assert_eq!(
            bench.core.inline(RAM),
            Inline::Reads,
            "unprivileged may only read"
        );
        region(&mut bench, 0, RAM, attributes(15, FULL_ACCESS));
        assert_eq!(bench.core.inline(RAM), Inline::Neither, "forgotten");
        bench.core.state.r[15] = CODE;
        bench.run(1);
        assert_eq!(bench.core.inline(RAM), Inline::Both);
    }

    /// B3.5.3: what the regions answer is the same over a page only when one region, or none,
    /// holds every byte of it in enabled subregions.
    #[test]
    fn a_page_is_decided_only_when_one_region_or_none_holds_all_of_it() {
        let page = u32::try_from(crate::emulator::core::PAGE_SIZE).unwrap();
        let mut bench = bench();
        let throughout =
            |bench: &mut Bench, base: u32| bench.core.mpu.inline_throughout(base, page);
        region(&mut bench, 0, RAM, attributes(15, FULL_ACCESS));
        write(&mut bench, CTRL, mpu_ctrl(&[mpu_ctrl::ENABLE]));
        assert_eq!(throughout(&mut bench, RAM), Inline::Both);
        assert_eq!(
            throughout(&mut bench, CODE),
            Inline::Neither,
            "the background"
        );
        region(&mut bench, 1, RAM + 0x20, attributes(4, 0b110));
        assert_eq!(
            throughout(&mut bench, RAM),
            Inline::Neither,
            "split by a region of 32 bytes"
        );
        assert_eq!(throughout(&mut bench, RAM + page), Inline::Both);
        let mut eighths = attributes(13, 0b110);
        eighths = set(mpu_rasr::SRD, eighths, 0b0000_0010);
        region(&mut bench, 1, RAM, eighths);
        assert_eq!(
            throughout(&mut bench, RAM),
            Inline::Reads,
            "the first eighth"
        );
        assert_eq!(
            throughout(&mut bench, RAM + 2 * page),
            Inline::Both,
            "a disabled eighth"
        );
        region(
            &mut bench,
            1,
            RAM,
            set(mpu_rasr::SRD, attributes(10, 0b110), 0b0000_0001),
        );
        assert_eq!(
            throughout(&mut bench, RAM),
            Inline::Neither,
            "half the page disabled"
        );
        region(
            &mut bench,
            1,
            RAM,
            set(mpu_rasr::SRD, attributes(4, 0b110), 0xFF),
        );
        assert_eq!(
            throughout(&mut bench, RAM),
            Inline::Both,
            "every subregion disabled"
        );
    }

    /// B3.5.1: a vector is read through the default map whatever the regions say.
    #[test]
    fn a_vector_is_read_through_the_default_map() {
        let mut bench = one_region(0b011);
        bench.core.scs.pend(PEND_SV);
        assert_eq!(bench.run(0), (Exit::Budget, 0));
        let state = &bench.core.state;
        assert_eq!((state.ipsr, state.locked_up), (u32::from(PEND_SV), 0));
        assert_eq!(bench.core.system.cfsr, 0);
    }

    /// B3.5.3: with the MPU on, a fetch is checked at the privilege it runs at, so code translated
    /// for privileged software doesn't run for unprivileged software.
    #[test]
    fn a_fetch_is_checked_at_the_privilege_it_runs_at() {
        let mut bench = one_region(0b011);
        region(&mut bench, 1, CODE, attributes(15, 0b001));
        assert_eq!(bench.run(1), (Exit::Budget, 1));
        unprivileged(&mut bench);
        bench.core.state.r[15] = CODE;
        assert_eq!(bench.run(1).1, 0, "IACCVIOL");
    }

    /// B1.5.6: `PushStack()` runs before HardFault is active, so with `HFNMIENA` clear the frame
    /// is checked against the regions in the context it preempts.
    #[test]
    fn a_frame_is_pushed_in_the_context_it_preempts() {
        let mut bench = one_region(0b000);
        bench.core.scs.pend(HARD_FAULT);
        assert_eq!(bench.run(0), (Exit::Budget, 0));
        assert_eq!(bench.core.system.cfsr, mask(cfsr::MSTKERR));
    }

    /// B1.5.8: `PopStack()` runs with the privilege of where the return goes, so a frame in a
    /// privileged-only region can't come back to unprivileged Thread mode.
    #[test]
    fn a_frame_is_popped_in_the_context_it_returns_to() {
        let mut bench = one_region(0b001);
        take(&mut bench.core, HARD_FAULT);
        bench.core.state.r[13] = RAM + 0x100;
        unprivileged(&mut bench);
        bench.core.exception_return(0xFFFF_FFF9);
        assert!(is_set(cfsr::MUNSTKERR, bench.core.system.cfsr));
    }

    /// B1.6.3: `PreserveFPState()` runs at the priority of the context that owns the state, which
    /// `FPCCR.HFRDY` clear says was below 0, so with `HFNMIENA` clear the default map takes it.
    #[test]
    fn lazy_preservation_runs_in_the_context_that_owns_the_state() {
        let mut bench = one_region(0b000);
        bench.core.system.fpcar = RAM + 0x100;
        bench.core.system.fpccr = mask(fpccr::LSPACT);
        assert!(bench.core.preserve_fp_state(Position::Processor));
        assert_eq!(bench.core.system.cfsr, 0);
    }

    /// A7.7.66, B3.5.3 and B3.2.17: an `LDRT` from privileged code that a region refuses
    /// unprivileged software runs into MemManage `DACCVIOL` with `MMFAR` the address, stacked at
    /// the `LDRT` and leaving its register alone.
    #[test]
    fn an_ldrt_the_mpu_refuses_runs_into_memmanage() {
        const LDRT_R0_R1: [u16; 2] = [0xF851, 0x0E00];
        const B_SELF: u16 = 0xE7FE;
        const TABLE: u32 = CODE + 0x400;
        const HANDLER: u32 = CODE + 0x800;
        const TOP: u32 = RAM + 0x1_0000;
        let mut bench = Bench::new(&LDRT_R0_R1);
        let vector = TABLE + 4 * u32::from(MEM_MANAGE);
        bench.write(vector, &(HANDLER | 1).to_le_bytes());
        bench.place(HANDLER, &[B_SELF]);
        bench.core.system.vtor = TABLE;
        region(&mut bench, 0, RAM, attributes(15, 0b001));
        write(
            &mut bench,
            CTRL,
            mpu_ctrl(&[mpu_ctrl::ENABLE, mpu_ctrl::PRIVDEFENA]),
        );
        write(&mut bench, 0xD24, mask(shcsr::MEMFAULTENA));
        bench.core.state.r[..2].copy_from_slice(&[7, RAM + 0x100]);
        assert_eq!(bench.run(16), (Exit::Waiting, 1));
        let state = &bench.core.state;
        assert_eq!(
            (state.ipsr, state.r[15], state.r[0]),
            (u32::from(MEM_MANAGE), HANDLER, 7)
        );
        let system = &bench.core.system;
        assert_eq!(
            (system.cfsr, system.mmfar),
            (mask(cfsr::DACCVIOL) | mask(cfsr::MMARVALID), RAM + 0x100)
        );
        assert_eq!(bench.word(TOP - 0x20 + 0x18), CODE, "stacked at the LDRT");
    }
}