darwinscope 0.1.4

Parse and inspect Mach-O binaries - including the Apple Objective-C and Swift runtime metadata they embed
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
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
//! Apple Code Signing decoder.
//!
//! Walks the embedded `LC_CODE_SIGNATURE` payload (a `CS_SuperBlob`)
//! into typed views over its component blobs:
//!
//! - [`Signature`] - the SuperBlob walker entry point.
//! - [`BlobIndex`] / [`Slot`] - per-slot dispatch.
//! - [`CodeDirectory`] - the primary CD plus alternates.
//! - [`Entitlements`], [`DerEntitlements`] - XML and DER plists.
//! - [`Requirements`] - opaque pass-through.
//! - [`CmsSignature`] - embedded CMS size + presence.
//!
//! ## Endianness
//!
//! Code-signing structure fields are **big-endian** on disk, in
//! contrast to every other Mach-O subsystem `darwinscope` decodes.
//! The helpers in [`crate::util`] (`read_u{16,32,64}_be_at`) read
//! them. Cite: `xnu/bsd/kern/ubc_subr.c` (every field is read via
//! `ntohl` / `OSSwapBigToHostInt32`).
//!
//! ## Lifetime model
//!
//! [`Signature<'a>`] borrows the binary's data slice (`'a`) - every
//! blob view (entitlements XML, identifier strings, hash bytes) is
//! a zero-copy reborrow of the same slice.
//!
//! See `RESEARCH.md` §"Code signing" (line 979) and
//! `reference/xnu/osfmk/kern/cs_blobs.h` for the on-disk struct
//! definitions.

use bitflags::bitflags;
use sha2::{Digest, Sha256, Sha384, Sha512};

use crate::util::{read_cstr_at, read_u32_be_at, read_u64_be_at};

/// `CSMAGIC_EMBEDDED_SIGNATURE` - entry point of an embedded
/// SuperBlob (cite: `cs_blobs.h:95`).
pub const CSMAGIC_EMBEDDED_SIGNATURE: u32 = 0xfade_0cc0;
/// `CSMAGIC_EMBEDDED_SIGNATURE_OLD` - legacy embedded form.
pub const CSMAGIC_EMBEDDED_SIGNATURE_OLD: u32 = 0xfade_0b02;
/// `CSMAGIC_CODEDIRECTORY` (cite: `cs_blobs.h:94`).
pub const CSMAGIC_CODEDIRECTORY: u32 = 0xfade_0c02;
/// `CSMAGIC_REQUIREMENT` (cite: `cs_blobs.h:92`).
pub const CSMAGIC_REQUIREMENT: u32 = 0xfade_0c00;
/// `CSMAGIC_REQUIREMENTS` - vector of requirements
/// (cite: `cs_blobs.h:93`).
pub const CSMAGIC_REQUIREMENTS: u32 = 0xfade_0c01;
/// `CSMAGIC_EMBEDDED_ENTITLEMENTS` - XML plist
/// (cite: `cs_blobs.h:97`).
pub const CSMAGIC_EMBEDDED_ENTITLEMENTS: u32 = 0xfade_7171;
/// `CSMAGIC_EMBEDDED_DER_ENTITLEMENTS` - DER plist
/// (cite: `cs_blobs.h:98`).
pub const CSMAGIC_EMBEDDED_DER_ENTITLEMENTS: u32 = 0xfade_7172;
/// `CSMAGIC_BLOBWRAPPER` - CMS signature wrapper
/// (cite: `cs_blobs.h:100`).
pub const CSMAGIC_BLOBWRAPPER: u32 = 0xfade_0b01;

/// Header size of every blob: `magic` (BE u32) + `length` (BE u32).
#[allow(dead_code)] // used by CodeDirectory / Entitlements parsers in subsequent PRs.
pub(crate) const BLOB_HEADER_SIZE: usize = 8;
/// Size of the SuperBlob header before the index array.
const SUPERBLOB_HEADER_SIZE: usize = 12;
/// Size of one `CS_BlobIndex` entry: `type` (BE u32) + `offset`
/// (BE u32).
const BLOB_INDEX_SIZE: usize = 8;

/// Slot kind from `CS_BlobIndex.type` (cite: `cs_blobs.h:110-128`).
///
/// Each entry of a SuperBlob's index array tags its blob with one of
/// these slot numbers. Slot indices `0..=11` identify *special* slots -
/// blobs with a fixed purpose whose CD hash sits in the negative
/// indices of the CodeDirectory hash table. Slot indices in
/// `0x1000..=0x1004` are *alternate* CodeDirectories (used to ship
/// multiple hash algorithms in the same binary). Slots `≥ 0x10000`
/// are top-level wrappers (CMS signature, identification, ticket).
///
/// Special-cased so consumers can pattern-match instead of comparing
/// raw `u32`s. Unknown values are surfaced as [`Slot::Other`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Slot {
    /// `CSSLOT_CODEDIRECTORY = 0` - the canonical CodeDirectory the
    /// kernel hashes for the CDHash. The "primary" CD when only one
    /// hash algorithm is present.
    CodeDirectory,
    /// `CSSLOT_INFOSLOT = 1` - SHA digest of the bundle's
    /// `Info.plist`, used by Gatekeeper to detect plist tampering on
    /// `.app` bundles.
    InfoSlot,
    /// `CSSLOT_REQUIREMENTS = 2` - the internal "designated
    /// requirement" vector, encoded as a [`Requirements`]
    /// (`CSMAGIC_REQUIREMENTS`) blob.
    Requirements,
    /// `CSSLOT_RESOURCEDIR = 3` - SHA digest of
    /// `_CodeSignature/CodeResources` (the per-resource hash list
    /// for bundle resources).
    ResourceDir,
    /// `CSSLOT_APPLICATION = 4` - application-specific slot reserved
    /// for the signer; rarely populated by Apple toolchains.
    Application,
    /// `CSSLOT_ENTITLEMENTS = 5` - XML plist of the entitlements the
    /// binary requested. See [`Entitlements`].
    Entitlements,
    /// `CSSLOT_DER_ENTITLEMENTS = 7` - Apple's DER-encoded
    /// entitlement plist. Required for hardened-runtime / iOS code
    /// signatures since macOS 11 / iOS 14. See [`DerEntitlements`].
    DerEntitlements,
    /// `CSSLOT_LAUNCH_CONSTRAINT_SELF = 8` - declarative constraints
    /// the kernel enforces on *this* binary at launch (introduced
    /// macOS 13 / iOS 16, `LWCRBlob`).
    LaunchConstraintSelf,
    /// `CSSLOT_LAUNCH_CONSTRAINT_PARENT = 9` - constraints the
    /// kernel enforces on the *parent* process at launch.
    LaunchConstraintParent,
    /// `CSSLOT_LAUNCH_CONSTRAINT_RESPONSIBLE = 10` - constraints on
    /// the *responsible* process (the one Privacy & Security reports
    /// the launch under).
    LaunchConstraintResponsible,
    /// `CSSLOT_LIBRARY_CONSTRAINT = 11` - constraints applied when
    /// this binary is loaded *as a library* (dlopen / linkage).
    LibraryConstraint,
    /// `CSSLOT_ALTERNATE_CODEDIRECTORIES + i` (range
    /// `0x1000..=0x1004`). Holds CodeDirectories using an alternate
    /// hash algorithm (e.g. SHA-1 alongside SHA-256), allowing one
    /// signature to satisfy multiple OS versions. The inner `u32` is
    /// the index `i`.
    AlternateCodeDirectory(u32),
    /// `CSSLOT_SIGNATURESLOT = 0x10000` - the CMS / PKCS#7
    /// SignedData wrapper (`CSMAGIC_BLOBWRAPPER`). See
    /// [`CmsSignature`].
    SignatureSlot,
    /// `CSSLOT_IDENTIFICATIONSLOT = 0x10001` - provisioning-style
    /// identification blob; used by some validation paths.
    IdentificationSlot,
    /// `CSSLOT_TICKETSLOT = 0x10002` - notarization stapled ticket
    /// (the response from Apple's notary service).
    TicketSlot,
    /// Any other slot value, surfaced verbatim. Reserved for forward
    /// compatibility with new `CSSLOT_*` constants.
    Other(u32),
}

impl Slot {
    /// Decode a raw `CS_BlobIndex.type` value.
    ///
    /// Inlined because each blob entry of the SuperBlob index calls
    /// this exactly once, and code-signing blobs typically contain
    /// a dozen or more entries.
    #[inline]
    pub fn from_raw(raw: u32) -> Self {
        match raw {
            0 => Self::CodeDirectory,
            1 => Self::InfoSlot,
            2 => Self::Requirements,
            3 => Self::ResourceDir,
            4 => Self::Application,
            5 => Self::Entitlements,
            7 => Self::DerEntitlements,
            8 => Self::LaunchConstraintSelf,
            9 => Self::LaunchConstraintParent,
            10 => Self::LaunchConstraintResponsible,
            11 => Self::LibraryConstraint,
            n if (0x1000..=0x1004).contains(&n) => {
                Self::AlternateCodeDirectory(n.wrapping_sub(0x1000))
            }
            0x10000 => Self::SignatureSlot,
            0x10001 => Self::IdentificationSlot,
            0x10002 => Self::TicketSlot,
            other => Self::Other(other),
        }
    }
}

/// One entry of the SuperBlob's index array - a `(slot, offset)`
/// pair pointing at a typed blob within the SuperBlob payload.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BlobIndex {
    /// Decoded slot kind.
    pub slot: Slot,
    /// Raw `type` value as read from disk.
    pub raw_slot: u32,
    /// Offset of the blob from the start of the SuperBlob, in bytes.
    pub offset: u32,
}

/// Embedded code-signature SuperBlob walker.
///
/// Construct via [`MachoBinary::signature`](crate::binary::MachoBinary::signature).
/// Returns `None` when the binary has no `LC_CODE_SIGNATURE` or
/// the SuperBlob magic doesn't match `CSMAGIC_EMBEDDED_SIGNATURE`.
#[derive(Debug, Clone, Copy)]
pub struct Signature<'a> {
    /// The full Mach-O data slice. Blob offsets translate inside
    /// this slice, gated by `base` (the SuperBlob's start).
    data: &'a [u8],
    /// Absolute byte offset of the SuperBlob within `data`
    /// (i.e. `LC_CODE_SIGNATURE.dataoff`).
    base: usize,
    /// Decoded SuperBlob magic.
    magic: u32,
    /// Decoded SuperBlob length (in bytes, including header).
    length: u32,
    /// Decoded SuperBlob count (number of index entries).
    count: u32,
}

impl<'a> Signature<'a> {
    /// Parse the SuperBlob at `data[base..]`.
    ///
    /// Returns `None` when the magic is not `CSMAGIC_EMBEDDED_SIGNATURE`
    /// or `CSMAGIC_EMBEDDED_SIGNATURE_OLD`, or when the header
    /// overruns the available data.
    pub fn parse(data: &'a [u8], base: usize) -> Option<Self> {
        let header_end = base.checked_add(SUPERBLOB_HEADER_SIZE)?;
        let _ = data.get(base..header_end)?;
        let magic = read_u32_be_at(data, base)?;
        if magic != CSMAGIC_EMBEDDED_SIGNATURE && magic != CSMAGIC_EMBEDDED_SIGNATURE_OLD {
            return None;
        }
        let len_off = base.checked_add(4)?;
        let count_off = base.checked_add(8)?;
        let length = read_u32_be_at(data, len_off)?;
        let count = read_u32_be_at(data, count_off)?;
        // Sanity: total length must cover the index array.
        let need =
            SUPERBLOB_HEADER_SIZE.checked_add((count as usize).checked_mul(BLOB_INDEX_SIZE)?)?;
        if (length as usize) < need {
            return None;
        }
        let blob_end = base.checked_add(length as usize)?;
        if blob_end > data.len() {
            return None;
        }
        Some(Self {
            data,
            base,
            magic,
            length,
            count,
        })
    }

    /// `CS_SuperBlob.magic` - `0xfade0cc0` for embedded signatures.
    pub fn magic(&self) -> u32 {
        self.magic
    }

    /// `CS_SuperBlob.length` - total SuperBlob length in bytes.
    pub fn length(&self) -> u32 {
        self.length
    }

    /// `CS_SuperBlob.count` - number of index entries.
    pub fn blob_count(&self) -> u32 {
        self.count
    }

    /// Iterator over the SuperBlob's `CS_BlobIndex` entries.
    pub fn blobs(&self) -> BlobIter<'a> {
        BlobIter {
            data: self.data,
            base: self.base,
            count: self.count,
            cursor: 0,
        }
    }

    /// Find the blob slot's payload bytes (header + body), if the
    /// SuperBlob has an entry for that slot.
    #[allow(dead_code)] // used by CodeDirectory / Entitlements / Requirements parsers.
    pub(crate) fn find_blob_bytes(&self, target: Slot) -> Option<&'a [u8]> {
        for idx in self.blobs() {
            if idx.slot == target {
                return self.blob_bytes_at(idx.offset);
            }
        }
        None
    }

    #[allow(dead_code)] // used by CodeDirectory / Entitlements / Requirements parsers.
    pub(crate) fn blob_bytes_at(&self, offset: u32) -> Option<&'a [u8]> {
        let abs = self.base.checked_add(offset as usize)?;
        let header = self.data.get(abs..abs.checked_add(BLOB_HEADER_SIZE)?)?;
        let blob_len = read_u32_be_at(header, 4)? as usize;
        if blob_len < BLOB_HEADER_SIZE {
            return None;
        }
        let end = abs.checked_add(blob_len)?;
        self.data.get(abs..end)
    }
}

/// CodeDirectory version constants (cite: `cs_blobs.h:170-176`).
pub mod cd_version {
    /// Base version with all the fields up to `pageSize`.
    pub const BASE: u32 = 0x0002_0001;
    /// Adds `scatterOffset`.
    pub const SUPPORTS_SCATTER: u32 = 0x0002_0100;
    /// Adds `teamOffset`.
    pub const SUPPORTS_TEAM_ID: u32 = 0x0002_0200;
    /// Adds `codeLimit64`.
    pub const SUPPORTS_CODE_LIMIT64: u32 = 0x0002_0300;
    /// Adds `execSegBase` / `execSegLimit` / `execSegFlags`.
    pub const SUPPORTS_EXEC_SEG: u32 = 0x0002_0400;
    /// Adds linkage records.
    pub const SUPPORTS_LINKAGE: u32 = 0x0002_0500;
}

bitflags! {
    /// `CS_*` flags from `CS_CodeDirectory.flags`
    /// (cite: `cs_blobs.h:130-167`). Unknown bits are preserved on
    /// round-trip via `from_bits_retain`.
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    pub struct CdFlags: u32 {
        /// `CS_VALID = 0x1` - dynamically valid (set by kernel).
        const VALID = 0x1;
        /// `CS_ADHOC = 0x2` - adhoc-signed (no real CMS).
        const ADHOC = 0x2;
        /// `CS_GET_TASK_ALLOW = 0x4` - `task_for_pid` allowed.
        const GET_TASK_ALLOW = 0x4;
        /// `CS_INSTALLER = 0x8`.
        const INSTALLER = 0x8;
        /// `CS_FORCED_LV = 0x10` - library validation forced.
        const FORCED_LV = 0x10;
        /// `CS_INVALID_ALLOWED = 0x20`.
        const INVALID_ALLOWED = 0x20;
        /// `CS_HARD = 0x100`.
        const HARD = 0x100;
        /// `CS_KILL = 0x200`.
        const KILL = 0x200;
        /// `CS_CHECK_EXPIRATION = 0x400`.
        const CHECK_EXPIRATION = 0x400;
        /// `CS_RESTRICT = 0x800`.
        const RESTRICT = 0x800;
        /// `CS_ENFORCEMENT = 0x1000`.
        const ENFORCEMENT = 0x1000;
        /// `CS_REQUIRE_LV = 0x2000` - library validation required.
        const REQUIRE_LV = 0x2000;
        /// `CS_ENTITLEMENTS_VALIDATED = 0x4000`.
        const ENTITLEMENTS_VALIDATED = 0x4000;
        /// `CS_NVRAM_UNRESTRICTED = 0x8000`.
        const NVRAM_UNRESTRICTED = 0x8000;
        /// `CS_RUNTIME = 0x10000` - hardened runtime.
        const RUNTIME = 0x10000;
        /// `CS_LINKER_SIGNED = 0x20000` - auto-applied by ld(1).
        const LINKER_SIGNED = 0x20000;
    }
}

/// `CS_CodeDirectory.hashType` - selects the digest algorithm
/// used for the CD's hash slots and the CDHash itself
/// (cite: `cs_blobs.h:182-187`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HashType {
    /// SHA-1 (legacy; `kSecCodeSignatureHashSHA1 = 1`).
    Sha1,
    /// SHA-256 (`kSecCodeSignatureHashSHA256 = 2`) - modern default.
    Sha256,
    /// SHA-256 truncated to 20 bytes (`= 3`).
    Sha256Truncated,
    /// SHA-384 (`= 4`).
    Sha384,
    /// SHA-512 (`= 5`).
    Sha512,
    /// Unknown algorithm; surfaced verbatim.
    Other(u8),
}

impl HashType {
    /// Decode a raw `hashType` byte.
    #[inline]
    pub fn from_raw(raw: u8) -> Self {
        match raw {
            1 => Self::Sha1,
            2 => Self::Sha256,
            3 => Self::Sha256Truncated,
            4 => Self::Sha384,
            5 => Self::Sha512,
            other => Self::Other(other),
        }
    }

    /// Output digest size in bytes, if known.
    #[inline]
    pub fn digest_size(self) -> Option<usize> {
        match self {
            Self::Sha1 => Some(20),
            Self::Sha256 => Some(32),
            Self::Sha256Truncated => Some(20),
            Self::Sha384 => Some(48),
            Self::Sha512 => Some(64),
            Self::Other(_) => None,
        }
    }
}

const CD_FIELD_VERSION: usize = 8;
const CD_FIELD_FLAGS: usize = 12;
const CD_FIELD_HASH_OFFSET: usize = 16;
const CD_FIELD_IDENT_OFFSET: usize = 20;
const CD_FIELD_N_SPECIAL_SLOTS: usize = 24;
const CD_FIELD_N_CODE_SLOTS: usize = 28;
const CD_FIELD_CODE_LIMIT: usize = 32;
const CD_FIELD_HASH_SIZE: usize = 36;
const CD_FIELD_HASH_TYPE: usize = 37;
const CD_FIELD_PLATFORM: usize = 38;
const CD_FIELD_PAGE_SIZE: usize = 39;
const CD_FIELD_TEAM_OFFSET: usize = 48;
const CD_FIELD_CODE_LIMIT_64: usize = 56;
const CD_FIELD_EXEC_SEG_BASE: usize = 64;
const CD_FIELD_EXEC_SEG_LIMIT: usize = 72;
const CD_FIELD_EXEC_SEG_FLAGS: usize = 80;

/// Decoded `CS_CodeDirectory` blob.
///
/// The full blob bytes (header + identifier + team-id strings +
/// hash slots) are referenced verbatim through `&'a [u8]`. CDHash
/// is recomputed from those bytes on demand via `cd_hash` /
/// `cd_hash_truncated`.
#[derive(Debug, Clone, Copy)]
pub struct CodeDirectory<'a> {
    /// The full CD blob bytes (length = self.length).
    blob: &'a [u8],
    version: u32,
    flags: u32,
    /// Offset of code hash slot 0 from the start of the blob;
    /// special slots `-1..-n` precede it at `hash_offset - i*hash_size`,
    /// code slots follow at `hash_offset + j*hash_size`.
    hash_offset: u32,
    ident_offset: u32,
    n_special_slots: u32,
    n_code_slots: u32,
    code_limit: u32,
    hash_size: u8,
    hash_type_raw: u8,
    platform: u8,
    page_size_log2: u8,
    team_offset: u32,
}

impl<'a> CodeDirectory<'a> {
    /// Parse a CodeDirectory blob from the given header-aligned
    /// byte slice (the slice must be exactly the blob's length:
    /// `magic` through trailing hash slots).
    ///
    /// Returns `None` when the blob magic doesn't match
    /// `CSMAGIC_CODEDIRECTORY` or the header is truncated.
    pub fn parse(blob: &'a [u8]) -> Option<Self> {
        if blob.len() < CD_FIELD_PAGE_SIZE.checked_add(1)? {
            return None;
        }
        let magic = read_u32_be_at(blob, 0)?;
        if magic != CSMAGIC_CODEDIRECTORY {
            return None;
        }
        let version = read_u32_be_at(blob, CD_FIELD_VERSION)?;
        let flags = read_u32_be_at(blob, CD_FIELD_FLAGS)?;
        let hash_offset = read_u32_be_at(blob, CD_FIELD_HASH_OFFSET)?;
        let ident_offset = read_u32_be_at(blob, CD_FIELD_IDENT_OFFSET)?;
        let n_special_slots = read_u32_be_at(blob, CD_FIELD_N_SPECIAL_SLOTS)?;
        let n_code_slots = read_u32_be_at(blob, CD_FIELD_N_CODE_SLOTS)?;
        let code_limit = read_u32_be_at(blob, CD_FIELD_CODE_LIMIT)?;
        let hash_size = *blob.get(CD_FIELD_HASH_SIZE)?;
        let hash_type_raw = *blob.get(CD_FIELD_HASH_TYPE)?;
        let platform = *blob.get(CD_FIELD_PLATFORM)?;
        let page_size_log2 = *blob.get(CD_FIELD_PAGE_SIZE)?;

        let team_offset = if version >= cd_version::SUPPORTS_TEAM_ID {
            read_u32_be_at(blob, CD_FIELD_TEAM_OFFSET).unwrap_or(0)
        } else {
            0
        };

        Some(Self {
            blob,
            version,
            flags,
            hash_offset,
            ident_offset,
            n_special_slots,
            n_code_slots,
            code_limit,
            hash_size,
            hash_type_raw,
            platform,
            page_size_log2,
            team_offset,
        })
    }

    /// `CS_CodeDirectory.version` - encodes which trailing fields
    /// are present (≥ `0x20100` ⇒ `scatterOffset`, ≥ `0x20200`
    /// ⇒ `teamOffset`, ≥ `0x20400` ⇒ `execSeg*`).
    pub fn version(&self) -> u32 {
        self.version
    }

    /// Decoded `CS_*` flags.
    pub fn flags(&self) -> CdFlags {
        CdFlags::from_bits_retain(self.flags)
    }

    /// Raw `flags` value (for callers that need bits beyond the
    /// named [`CdFlags`] constants).
    pub fn raw_flags(&self) -> u32 {
        self.flags
    }

    /// Decoded `hashType`.
    pub fn hash_type(&self) -> HashType {
        HashType::from_raw(self.hash_type_raw)
    }

    /// `hashSize` - bytes per hash slot.
    pub fn hash_size(&self) -> u8 {
        self.hash_size
    }

    /// Resolved page size in bytes (`1 << pageSize`). Returns `0`
    /// for the legacy "infinite" sentinel (`pageSize == 0`).
    pub fn page_size(&self) -> u32 {
        if self.page_size_log2 == 0 {
            0
        } else {
            1u32.wrapping_shl(self.page_size_log2 as u32)
        }
    }

    /// `nSpecialSlots` - number of negative-index hash slots
    /// preceding slot 0 (Info.plist, Requirements, ResourceDir,
    /// Application, Entitlements, DerEntitlements).
    pub fn n_special_slots(&self) -> u32 {
        self.n_special_slots
    }

    /// `nCodeSlots` - number of ordinary page hashes following
    /// slot 0.
    pub fn n_code_slots(&self) -> u32 {
        self.n_code_slots
    }

    /// `codeLimit` - byte length of the image region covered by
    /// the code hashes.
    pub fn code_limit(&self) -> u32 {
        self.code_limit
    }

    /// `platform` - platform identifier; `0` for non-platform
    /// binaries.
    pub fn platform(&self) -> u8 {
        self.platform
    }

    /// Identifier string (`identOffset`-relative), if present and
    /// valid UTF-8.
    ///
    /// Returns `None` when `ident_offset` is `0` - the `cs_blobs.h`
    /// convention for an absent identifier - or when the offset is
    /// out of bounds or the string is not valid UTF-8.
    pub fn identifier(&self) -> Option<&'a str> {
        if self.ident_offset == 0 {
            return None;
        }
        read_cstr_at(self.blob, self.ident_offset as usize)
    }

    /// Team ID string (`teamOffset`-relative), if version ≥
    /// `0x20200` and the offset is non-zero. `None` for adhoc
    /// signatures (which lack a team identity).
    pub fn team_id(&self) -> Option<&'a str> {
        if self.version < cd_version::SUPPORTS_TEAM_ID || self.team_offset == 0 {
            return None;
        }
        read_cstr_at(self.blob, self.team_offset as usize)
    }

    /// CDHash - full digest of the canonical CD blob bytes,
    /// computed using [`hash_type`](Self::hash_type).
    ///
    /// Returns an empty `Vec` for hash types `darwinscope` does
    /// not implement (`Sha1`, `Sha256Truncated`, `Other`); the
    /// `sha2` crate covers SHA-256 / SHA-384 / SHA-512.
    pub fn cd_hash(&self) -> Vec<u8> {
        match self.hash_type() {
            HashType::Sha256 => Sha256::digest(self.blob).to_vec(),
            HashType::Sha384 => Sha384::digest(self.blob).to_vec(),
            HashType::Sha512 => Sha512::digest(self.blob).to_vec(),
            HashType::Sha1 | HashType::Sha256Truncated | HashType::Other(_) => Vec::new(),
        }
    }

    /// CDHash truncated to the first 20 bytes - the form AMFI
    /// compares against. Zero-padded if the underlying digest is
    /// shorter than 20 bytes (only possible for unimplemented hash
    /// types, where the source digest is empty).
    ///
    /// Computes the digest directly into the 20-byte output buffer
    /// rather than going through [`cd_hash`](Self::cd_hash) - avoids
    /// a heap allocation for the full digest just to copy 20 bytes
    /// out. AMFI invokes this once per binary at load time, so the
    /// allocation savings matter when batch-scanning a filesystem.
    pub fn cd_hash_truncated(&self) -> [u8; 20] {
        let mut out = [0u8; 20];
        // GenericArray from sha2 derefs to &[u8]; we copy the prefix
        // into the fixed output buffer without going through Vec.
        match self.hash_type() {
            HashType::Sha256 => copy_prefix(&mut out, &Sha256::digest(self.blob)),
            HashType::Sha384 => copy_prefix(&mut out, &Sha384::digest(self.blob)),
            HashType::Sha512 => copy_prefix(&mut out, &Sha512::digest(self.blob)),
            HashType::Sha1 | HashType::Sha256Truncated | HashType::Other(_) => {}
        }
        out
    }

    /// The canonical CD blob bytes (`magic` through trailing hash
    /// slots) - i.e. the input that hashes to CDHash. Useful for
    /// callers that want to compute the hash with their own
    /// algorithm (e.g. SHA-1, which `darwinscope` does not bundle).
    pub fn blob_bytes(&self) -> &'a [u8] {
        self.blob
    }

    /// `codeLimit64` - present only in CDs of version
    /// `≥ 0x20300`. Returns `None` for older CDs.
    pub fn code_limit_64(&self) -> Option<u64> {
        if self.version < cd_version::SUPPORTS_CODE_LIMIT64 {
            return None;
        }
        read_u64_be_at(self.blob, CD_FIELD_CODE_LIMIT_64)
    }

    /// `execSegBase` - VM offset of the first executable segment.
    /// `Some` for CDs of version `≥ 0x20400`, `None` otherwise.
    pub fn exec_seg_base(&self) -> Option<u64> {
        if self.version < cd_version::SUPPORTS_EXEC_SEG {
            return None;
        }
        read_u64_be_at(self.blob, CD_FIELD_EXEC_SEG_BASE)
    }

    /// `execSegLimit` - byte length of the executable segment
    /// region.
    pub fn exec_seg_limit(&self) -> Option<u64> {
        if self.version < cd_version::SUPPORTS_EXEC_SEG {
            return None;
        }
        read_u64_be_at(self.blob, CD_FIELD_EXEC_SEG_LIMIT)
    }

    /// `execSegFlags` - `CS_EXECSEG_*` flag bits.
    pub fn exec_seg_flags(&self) -> Option<u64> {
        if self.version < cd_version::SUPPORTS_EXEC_SEG {
            return None;
        }
        read_u64_be_at(self.blob, CD_FIELD_EXEC_SEG_FLAGS)
    }

    /// Iterator over the special hash slots (`-1, -2, ..., -n`).
    ///
    /// Each yielded entry is `(slot_index, &hash_bytes)`. Slot
    /// indices are negative because they precede slot 0 (the first
    /// code-page hash) in the on-disk layout: slot `-i` is at
    /// `hash_offset - i * hash_size`. The mapping for the first
    /// six special slots:
    ///
    /// | slot | what it hashes        |
    /// |------|------------------------|
    /// | `-1` | Info.plist             |
    /// | `-2` | Requirements blob      |
    /// | `-3` | ResourceDir            |
    /// | `-4` | Application slot       |
    /// | `-5` | XML entitlements blob  |
    /// | `-7` | DER entitlements blob  |
    pub fn special_hashes(&self) -> SpecialHashIter<'a> {
        SpecialHashIter {
            blob: self.blob,
            hash_offset: self.hash_offset,
            hash_size: self.hash_size,
            n_special: self.n_special_slots,
            cursor: 0,
        }
    }

    /// Iterator over the code hash slots (`0, 1, ..., n_code-1`).
    ///
    /// Slot `j` covers bytes `j * page_size .. (j+1) * page_size`
    /// of the image's signed range and is at byte offset
    /// `hash_offset + j * hash_size` within the CD blob.
    pub fn code_hashes(&self) -> CodeHashIter<'a> {
        CodeHashIter {
            blob: self.blob,
            hash_offset: self.hash_offset,
            hash_size: self.hash_size,
            n_code: self.n_code_slots,
            cursor: 0,
        }
    }
}

/// Iterator over special hash slots (negative indices `-1..-n`).
///
/// Yields `(slot_index, &'a [u8])` pairs in `slot_index = -1`,
/// `-2`, `-3`, ... order.
pub struct SpecialHashIter<'a> {
    blob: &'a [u8],
    hash_offset: u32,
    hash_size: u8,
    n_special: u32,
    cursor: u32,
}

impl<'a> Iterator for SpecialHashIter<'a> {
    type Item = (i32, &'a [u8]);
    fn next(&mut self) -> Option<Self::Item> {
        if self.cursor >= self.n_special {
            return None;
        }
        let i = self.cursor.checked_add(1)?;
        self.cursor = i;
        // slot -i is at hash_offset - i * hash_size
        let off_back = (i as usize).checked_mul(self.hash_size as usize)?;
        let off = (self.hash_offset as usize).checked_sub(off_back)?;
        let end = off.checked_add(self.hash_size as usize)?;
        let bytes = self.blob.get(off..end)?;
        let slot_idx = i32::try_from(i).ok()?.wrapping_neg();
        Some((slot_idx, bytes))
    }
}

/// Iterator over code hash slots (non-negative indices).
pub struct CodeHashIter<'a> {
    blob: &'a [u8],
    hash_offset: u32,
    hash_size: u8,
    n_code: u32,
    cursor: u32,
}

impl<'a> Iterator for CodeHashIter<'a> {
    type Item = &'a [u8];
    fn next(&mut self) -> Option<Self::Item> {
        if self.cursor >= self.n_code {
            return None;
        }
        let i = self.cursor;
        self.cursor = self.cursor.checked_add(1)?;
        let off_fwd = (i as usize).checked_mul(self.hash_size as usize)?;
        let off = (self.hash_offset as usize).checked_add(off_fwd)?;
        let end = off.checked_add(self.hash_size as usize)?;
        self.blob.get(off..end)
    }
}

impl<'a> Signature<'a> {
    /// Primary CodeDirectory (slot `CodeDirectory = 0`), if
    /// present and parseable.
    pub fn primary_code_directory(&self) -> Option<CodeDirectory<'a>> {
        let bytes = self.find_blob_bytes(Slot::CodeDirectory)?;
        CodeDirectory::parse(bytes)
    }

    /// Iterator over alternate CodeDirectories (slots
    /// `0x1000..=0x1004`). Modern Apple-signed binaries carry
    /// 0-4 alternates plus the primary CD; adhoc binaries carry
    /// only the primary so this iterator is empty.
    pub fn alternate_code_directories(&self) -> CodeDirectoryIter<'a> {
        CodeDirectoryIter {
            sig: *self,
            cursor: 0,
        }
    }

    /// XML entitlements blob (`CSMAGIC_EMBEDDED_ENTITLEMENTS`,
    /// `0xfade7171`), if the SuperBlob has a `CSSLOT_ENTITLEMENTS`
    /// (slot `5`) entry.
    pub fn entitlements(&self) -> Option<Entitlements<'a>> {
        let blob = self.find_blob_bytes(Slot::Entitlements)?;
        Entitlements::parse(blob)
    }

    /// DER-encoded entitlements blob
    /// (`CSMAGIC_EMBEDDED_DER_ENTITLEMENTS`, `0xfade7172`).
    /// `darwinscope` exposes the raw bytes plus a top-level key
    /// list; deeper decode is v0.2.
    pub fn der_entitlements(&self) -> Option<DerEntitlements<'a>> {
        let blob = self.find_blob_bytes(Slot::DerEntitlements)?;
        DerEntitlements::parse(blob)
    }

    /// Embedded CMS signature wrapper (`CSMAGIC_BLOBWRAPPER`,
    /// `0xfade0b01`) at slot `CSSLOT_SIGNATURESLOT`.
    /// Always returned when the slot exists - even adhoc
    /// signatures carry an empty wrapper. Use
    /// [`CmsSignature::is_present`] to distinguish empty
    /// placeholders from real CMS payloads.
    pub fn cms(&self) -> Option<CmsSignature<'a>> {
        let blob = self.find_blob_bytes(Slot::SignatureSlot)?;
        CmsSignature::parse(blob)
    }

    /// Internal-requirements vector (`CSMAGIC_REQUIREMENTS`,
    /// `0xfade0c01`). Surfaced as opaque bytes for v0.1 - the
    /// CSEL / CSCO requirement-expression DSL is a follow-up.
    pub fn requirements(&self) -> Option<Requirements<'a>> {
        let blob = self.find_blob_bytes(Slot::Requirements)?;
        Requirements::parse(blob)
    }
}

/// Iterator over alternate CodeDirectories (slots
/// `0x1000..=0x1004`).
pub struct CodeDirectoryIter<'a> {
    sig: Signature<'a>,
    /// Index into the alternate-CD slot range (0..5).
    cursor: u32,
}

impl<'a> Iterator for CodeDirectoryIter<'a> {
    type Item = CodeDirectory<'a>;
    fn next(&mut self) -> Option<CodeDirectory<'a>> {
        // Cap at 5 (CSSLOT_ALTERNATE_CODEDIRECTORY_MAX).
        while self.cursor < 5 {
            let i = self.cursor;
            self.cursor = self.cursor.checked_add(1)?;
            let target = Slot::AlternateCodeDirectory(i);
            if let Some(blob) = self.sig.find_blob_bytes(target)
                && let Some(cd) = CodeDirectory::parse(blob)
            {
                return Some(cd);
            }
        }
        None
    }
}

/// XML-form entitlements blob (`CSMAGIC_EMBEDDED_ENTITLEMENTS =
/// 0xfade7171`, cite: `cs_blobs.h:97`).
///
/// Carried in slot [`Slot::Entitlements`] of the SuperBlob. The
/// on-disk payload is a Property List in XML form - the same format
/// `codesign --entitlements` extracts and `codesign --sign` ingests.
/// The 8-byte `(magic, length)` header from the enclosing blob is
/// stripped from `payload`.
///
/// [`raw`](Self::raw) returns the verbatim XML bytes for callers
/// that want to hash or pretty-print the original;
/// [`parsed`](Self::parsed) decodes them into a [`plist::Value`] via
/// the `plist` crate. Both views borrow from the binary's data
/// slice - no allocation beyond what `plist` needs.
#[derive(Debug, Clone, Copy)]
pub struct Entitlements<'a> {
    payload: &'a [u8],
}

impl<'a> Entitlements<'a> {
    /// Parse an entitlements blob - returns `None` if the magic
    /// doesn't match or the blob is truncated.
    pub fn parse(blob: &'a [u8]) -> Option<Self> {
        if blob.len() < BLOB_HEADER_SIZE {
            return None;
        }
        let magic = read_u32_be_at(blob, 0)?;
        if magic != CSMAGIC_EMBEDDED_ENTITLEMENTS {
            return None;
        }
        let len = read_u32_be_at(blob, 4)? as usize;
        if len < BLOB_HEADER_SIZE || len > blob.len() {
            return None;
        }
        let payload = blob.get(BLOB_HEADER_SIZE..len)?;
        Some(Self { payload })
    }

    /// Raw XML plist bytes (the blob payload, sans 8-byte header).
    pub fn raw(&self) -> &'a [u8] {
        self.payload
    }

    /// Parsed plist value, or `None` if the XML failed to parse.
    pub fn parsed(&self) -> Option<plist::Value> {
        plist::Value::from_reader(std::io::Cursor::new(self.payload)).ok()
    }
}

/// DER-encoded entitlements blob
/// (`CSMAGIC_EMBEDDED_DER_ENTITLEMENTS = 0xfade7172`, cite:
/// `cs_blobs.h:98`).
///
/// Carried in slot [`Slot::DerEntitlements`]. macOS 11 / iOS 14 made
/// this blob mandatory for hardened-runtime and iOS signatures -
/// AMFI parses the DER form, not the XML. An XML entitlements blob
/// without a matching DER blob will be rejected at launch on those
/// OS versions.
///
/// The on-disk encoding is Apple's container DER (Apple ASN.1):
///
/// ```text
/// [APPLICATION 16] CONSTRUCTED {
///     INTEGER version,
///     [0] CONSTRUCTED SET OF SEQUENCE {
///         UTF8String key,
///         value             -- BOOLEAN | INTEGER | UTF8String | …
///     }
/// }
/// ```
///
/// v0.1 surfaces the raw payload and a sorted top-level key list via
/// [`keys`](Self::keys); the value side (which may be Boolean,
/// Integer, String, Array, …) is left for a v0.2 typed decoder.
#[derive(Debug, Clone, Copy)]
pub struct DerEntitlements<'a> {
    payload: &'a [u8],
}

impl<'a> DerEntitlements<'a> {
    /// Parse a DER-entitlements blob - returns `None` on bad
    /// magic or truncation.
    pub fn parse(blob: &'a [u8]) -> Option<Self> {
        if blob.len() < BLOB_HEADER_SIZE {
            return None;
        }
        let magic = read_u32_be_at(blob, 0)?;
        if magic != CSMAGIC_EMBEDDED_DER_ENTITLEMENTS {
            return None;
        }
        let len = read_u32_be_at(blob, 4)? as usize;
        if len < BLOB_HEADER_SIZE || len > blob.len() {
            return None;
        }
        let payload = blob.get(BLOB_HEADER_SIZE..len)?;
        Some(Self { payload })
    }

    /// Raw DER bytes (the blob payload, sans 8-byte header).
    pub fn raw(&self) -> &'a [u8] {
        self.payload
    }

    /// Sorted-deduplicated list of top-level entitlement keys.
    ///
    /// Walks the canonical Apple DER container shape; if the
    /// outer wrapper deviates, the walker returns whatever keys
    /// it could extract. Empty when the blob is malformed or
    /// truncated.
    pub fn keys(&self) -> Vec<String> {
        let mut out = der_collect_keys(self.payload);
        out.sort();
        out.dedup();
        out
    }

    /// Decoded top-level entitlement key/value pairs, in on-disk order.
    ///
    /// Reads both the `UTF8String` key and the typed value of each
    /// entry - [`Boolean`](DerEntitlementValue::Bool),
    /// [`Integer`](DerEntitlementValue::Integer),
    /// [`String`](DerEntitlementValue::String), or
    /// [`Array`](DerEntitlementValue::Array) (nested `SEQUENCE`/`SET`).
    /// Values with a tag the walker does not model degrade to
    /// [`Other`](DerEntitlementValue::Other). Empty when the blob is
    /// malformed or truncated.
    pub fn pairs(&self) -> Vec<(String, DerEntitlementValue)> {
        der_collect_pairs(self.payload)
    }
}

/// A decoded DER-entitlement value (`fade7172` entries).
///
/// Mirrors the small set of plist types Apple emits in the DER
/// entitlements container. Arbitrarily-nested containers are captured
/// as [`Array`](Self::Array); anything else is preserved as
/// [`Other`](Self::Other) carrying the raw DER tag.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DerEntitlementValue {
    /// ASN.1 `BOOLEAN`.
    Bool(bool),
    /// ASN.1 `INTEGER` (folded into an `i64`; larger values saturate).
    Integer(i64),
    /// ASN.1 `UTF8String`.
    String(String),
    /// A nested `SEQUENCE`/`SET` of values.
    Array(Vec<DerEntitlementValue>),
    /// A value whose DER tag the walker does not model; carries the tag.
    Other(u8),
}

impl DerEntitlementValue {
    /// Short kind label (`bool` / `integer` / `string` / `array` /
    /// `data`), matching the vocabulary the XML-entitlement decoder
    /// uses.
    #[must_use]
    pub fn kind_label(&self) -> &'static str {
        match self {
            Self::Bool(_) => "bool",
            Self::Integer(_) => "integer",
            Self::String(_) => "string",
            Self::Array(_) => "array",
            Self::Other(_) => "data",
        }
    }

    /// Flattened, human-readable rendering of the value.
    #[must_use]
    pub fn display(&self) -> String {
        match self {
            Self::Bool(b) => b.to_string(),
            Self::Integer(i) => i.to_string(),
            Self::String(s) => s.clone(),
            Self::Array(items) => {
                let inner: Vec<String> = items.iter().map(Self::display).collect();
                format!("[{}]", inner.join(", "))
            }
            Self::Other(tag) => format!("<der tag 0x{tag:02x}>"),
        }
    }
}

/// Hard cap on decoded items in one DER array, bounding work on a
/// corrupt container.
const MAX_DER_ARRAY_ITEMS: usize = 1024;
/// Maximum nesting depth for DER value decoding.
const MAX_DER_VALUE_DEPTH: u32 = 32;

/// Internal-requirements vector blob (`CSMAGIC_REQUIREMENTS =
/// 0xfade0c01`, cite: `cs_blobs.h:93`).
///
/// Carried in slot [`Slot::Requirements`]. Holds the binary's
/// "designated requirement" - the predicate the kernel evaluates to
/// decide whether *this* signing identity is allowed to claim the
/// binary's Team ID / bundle ID. Each entry of the vector is itself
/// a [`CSMAGIC_REQUIREMENT`] blob using
/// the CSEL / CSCO bytecode grammar (`security cdhash` /
/// `csreq -t`).
///
/// On-disk shape: 8-byte `(magic, length)` header, then `count`
/// (BE u32), then `count` `(type, offset)` pairs each pointing at a
/// single nested Requirement blob. The structured CSEL / CSCO
/// grammar decoder is a v0.2 follow-up; v0.1 exposes the raw bytes
/// verbatim plus the entry count.
#[derive(Debug, Clone, Copy)]
pub struct Requirements<'a> {
    blob: &'a [u8],
    count: u32,
}

impl<'a> Requirements<'a> {
    /// Parse a requirements blob - returns `None` on bad magic
    /// or truncation.
    pub fn parse(blob: &'a [u8]) -> Option<Self> {
        if blob.len() < BLOB_HEADER_SIZE {
            return None;
        }
        let magic = read_u32_be_at(blob, 0)?;
        if magic != CSMAGIC_REQUIREMENTS {
            return None;
        }
        let len = read_u32_be_at(blob, 4)? as usize;
        if len < BLOB_HEADER_SIZE || len > blob.len() {
            return None;
        }
        // count follows the 8-byte header, if present.
        let count = if len >= 12 {
            read_u32_be_at(blob, 8).unwrap_or(0)
        } else {
            0
        };
        Some(Self {
            blob: blob.get(..len)?,
            count,
        })
    }

    /// Full blob bytes (header + count + per-requirement index).
    pub fn raw(&self) -> &'a [u8] {
        self.blob
    }

    /// `count` field - number of requirement entries indexed
    /// from this vector. `0` for the empty placeholder that
    /// `codesign -s -` writes by default.
    pub fn count(&self) -> u32 {
        self.count
    }

    /// Total blob length (matches the SuperBlob's recorded
    /// length for this slot).
    pub fn len(&self) -> usize {
        self.blob.len()
    }

    /// Whether the blob carries any requirement entries.
    pub fn is_empty(&self) -> bool {
        self.count == 0
    }

    /// Decodes every indexed requirement into its human-readable
    /// expression text (the form `codesign -d -r-` / `csreq -t`
    /// print).
    ///
    /// Walks the vector's `(type, offset)` index, follows each offset
    /// to its nested [`CSMAGIC_REQUIREMENT`] blob, and evaluates the
    /// CSEL / CSCO expression bytecode into a string such as
    /// `identifier "com.example.app" and anchor apple generic`.
    /// Entries that are truncated or use an unknown blob shape are
    /// skipped; unknown opcodes degrade to a `/* opcode N */` marker
    /// rather than aborting the whole expression.
    pub fn decoded(&self) -> Vec<DecodedRequirement> {
        let mut out = Vec::new();
        // Bound the loop by both the recorded count and a hard cap so
        // a corrupt `count` can't spin - real signatures carry ≤ 5.
        let count = core::cmp::min(self.count as usize, MAX_REQUIREMENT_ENTRIES);
        for i in 0..count {
            let Some(entry_off) =
                REQUIREMENTS_INDEX_OFFSET.checked_add(i.saturating_mul(BLOB_INDEX_SIZE))
            else {
                break;
            };
            let (Some(type_raw), Some(blob_off)) = (
                read_u32_be_at(self.blob, entry_off),
                read_u32_be_at(self.blob, entry_off.saturating_add(4)),
            ) else {
                break;
            };
            let kind = RequirementKind::from_raw(type_raw);
            if let Some(text) = decode_requirement_blob(self.blob, blob_off as usize) {
                out.push(DecodedRequirement { kind, text });
            }
        }
        out
    }
}

/// Offset of the `(type, offset)` index array within a
/// `CSMAGIC_REQUIREMENTS` blob: past the 8-byte header and the 4-byte
/// `count`.
const REQUIREMENTS_INDEX_OFFSET: usize = 12;
/// Hard cap on decoded requirement entries - a defensive bound against
/// a corrupt `count`. Apple binaries carry at most five (one per
/// [`RequirementKind`]).
const MAX_REQUIREMENT_ENTRIES: usize = 32;
/// Maximum recursion depth for the requirement-expression evaluator,
/// bounding stack use on adversarial `And`/`Or`/`Not` nesting.
const MAX_REQUIREMENT_DEPTH: u32 = 64;

/// The purpose of one requirement within a requirements vector
/// (cite: `requirement.h` `SecRequirementType`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RequirementKind {
    /// `kSecHostRequirementType = 1` - what hosts may run us.
    Host,
    /// `kSecGuestRequirementType = 2` - what guests we may run.
    Guest,
    /// `kSecDesignatedRequirementType = 3` - the designated
    /// requirement, the predicate that identifies this code.
    Designated,
    /// `kSecLibraryRequirementType = 4` - what libraries we may link.
    Library,
    /// `kSecPluginRequirementType = 5` - what plug-ins we may load.
    Plugin,
    /// Any other / unrecognized requirement type code.
    Other(u32),
}

impl RequirementKind {
    /// Maps a raw `CS_BlobIndex.type` code to a [`RequirementKind`].
    #[must_use]
    pub fn from_raw(raw: u32) -> Self {
        match raw {
            1 => Self::Host,
            2 => Self::Guest,
            3 => Self::Designated,
            4 => Self::Library,
            5 => Self::Plugin,
            other => Self::Other(other),
        }
    }

    /// Human-readable label (e.g. `"designated"`).
    #[must_use]
    pub fn label(&self) -> &'static str {
        match self {
            Self::Host => "host",
            Self::Guest => "guest",
            Self::Designated => "designated",
            Self::Library => "library",
            Self::Plugin => "plugin",
            Self::Other(_) => "requirement",
        }
    }
}

/// One decoded requirement: its [`RequirementKind`] and the evaluated
/// expression text.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DecodedRequirement {
    /// What this requirement governs (designated, host, library, …).
    pub kind: RequirementKind,
    /// The human-readable requirement expression, e.g.
    /// `identifier "com.example" and anchor apple generic`.
    pub text: String,
}

/// Embedded CMS signature wrapper (`CSMAGIC_BLOBWRAPPER =
/// 0xfade0b01`, cite: `cs_blobs.h:100`).
///
/// Carried in slot [`Slot::SignatureSlot`]. The wrapper is just an
/// 8-byte `(magic, length)` envelope around an opaque CMS / PKCS#7
/// `SignedData` blob (RFC 5652) - the signer-chain certificates,
/// signature timestamp, and the signed CDHash digest live inside.
/// `codesign` calls into Apple's `CMSDecoder` to verify the
/// envelope; `darwinscope` v0.1 reports presence and size only,
/// leaving the signer-chain / x509 decoder for a follow-up.
///
/// **Adhoc** signatures (`codesign -s -`) carry an *empty* wrapper
/// (header only, payload length zero) - the kernel skips CMS
/// verification entirely and only checks the CDHash against the
/// in-memory pages. [`is_present`](Self::is_present) discriminates
/// the two cases.
#[derive(Debug, Clone, Copy)]
pub struct CmsSignature<'a> {
    payload: &'a [u8],
}

impl<'a> CmsSignature<'a> {
    /// Parse a CMS BlobWrapper - returns `None` on bad magic or
    /// truncation.
    pub fn parse(blob: &'a [u8]) -> Option<Self> {
        if blob.len() < BLOB_HEADER_SIZE {
            return None;
        }
        let magic = read_u32_be_at(blob, 0)?;
        if magic != CSMAGIC_BLOBWRAPPER {
            return None;
        }
        let len = read_u32_be_at(blob, 4)? as usize;
        if len < BLOB_HEADER_SIZE || len > blob.len() {
            return None;
        }
        let payload = blob.get(BLOB_HEADER_SIZE..len)?;
        Some(Self { payload })
    }

    /// Raw CMS bytes (the wrapper payload, sans 8-byte header).
    pub fn raw(&self) -> &'a [u8] {
        self.payload
    }

    /// `true` when the wrapper carries a non-empty CMS payload.
    /// `false` for the adhoc placeholder (empty payload).
    pub fn is_present(&self) -> bool {
        !self.payload.is_empty()
    }

    /// Length of the CMS payload in bytes (excluding the 8-byte
    /// wrapper header).
    pub fn len(&self) -> usize {
        self.payload.len()
    }

    /// `true` when the payload is empty (the adhoc placeholder).
    pub fn is_empty(&self) -> bool {
        self.payload.is_empty()
    }
}

// === Internal DER walker ===
//
// Minimal tag/length parser sufficient to extract the top-level
// key list from Apple's canonical entitlements DER shape. Not a
// general-purpose ASN.1 reader - it knows just the few tags used.

fn der_collect_keys(payload: &[u8]) -> Vec<String> {
    let mut out: Vec<String> = Vec::new();
    // The canonical Apple shape:
    //   [APPLICATION 16] CONSTRUCTED { INTEGER, [0] CONSTRUCTED SET-LIKE { ... entries ... } }
    // Some legacy variants drop the outer wrapper. Try both:
    // first, descend through the outer wrapper if present;
    // otherwise treat `payload` itself as the entries SET.
    let entries = der_locate_entries(payload).unwrap_or(payload);
    let mut cursor = 0usize;
    while cursor < entries.len() {
        let Some(remaining) = entries.get(cursor..) else {
            break;
        };
        let Some(hdr) = der_read_header(remaining) else {
            break;
        };
        let body_start = match cursor.checked_add(hdr.header_len) {
            Some(v) => v,
            None => break,
        };
        let body_end = match body_start.checked_add(hdr.length) {
            Some(v) => v,
            None => break,
        };
        if body_end > entries.len() {
            break;
        }
        // Each entry is a SEQUENCE (tag 0x30) whose first child
        // is the UTF8String key.
        if hdr.tag == 0x30
            && let Some(seq_body) = entries.get(body_start..body_end)
            && let Some(key) = der_first_utf8_string(seq_body)
        {
            out.push(key);
        }
        cursor = body_end;
    }
    out
}

/// Descend the outer Apple DER wrapper (if present) and return
/// the bytes of the inner entries SET. Returns `None` if the
/// shape is not recognised; the caller falls back to scanning
/// `payload` directly.
fn der_locate_entries(payload: &[u8]) -> Option<&[u8]> {
    // Outer: any single tag wrapping the body. Common values
    // observed: 0x70 (=APPLICATION 16, primitive class), 0x30
    // (SEQUENCE), 0x31 (SET).
    let outer = der_read_header(payload)?;
    let outer_body_start = outer.header_len;
    let outer_body_end = outer_body_start.checked_add(outer.length)?;
    let outer_body = payload.get(outer_body_start..outer_body_end)?;

    // First TLV inside the outer wrapper: optional INTEGER
    // version. Skip it.
    let mut cursor = 0usize;
    let inner = loop {
        let remaining = outer_body.get(cursor..)?;
        if remaining.is_empty() {
            return None;
        }
        let hdr = der_read_header(remaining)?;
        let body_start = cursor.checked_add(hdr.header_len)?;
        let body_end = body_start.checked_add(hdr.length)?;
        // INTEGER tag = 0x02
        if hdr.tag == 0x02 {
            cursor = body_end;
            continue;
        }
        // The entries container: [0] CONSTRUCTED (0xa0) or
        // SET (0x31) or SEQUENCE (0x30) or [16] (0xb0).
        if matches!(hdr.tag, 0x30 | 0x31 | 0xa0 | 0xb0) {
            break outer_body.get(body_start..body_end)?;
        }
        // Unknown - bail.
        return None;
    };
    Some(inner)
}

/// Like [`der_collect_keys`] but decodes each entry's value as well,
/// preserving on-disk order (no sort/dedup - order is meaningful for
/// display).
fn der_collect_pairs(payload: &[u8]) -> Vec<(String, DerEntitlementValue)> {
    let mut out: Vec<(String, DerEntitlementValue)> = Vec::new();
    let entries = der_locate_entries(payload).unwrap_or(payload);
    let mut cursor = 0usize;
    while cursor < entries.len() {
        let Some(remaining) = entries.get(cursor..) else {
            break;
        };
        let Some(hdr) = der_read_header(remaining) else {
            break;
        };
        let Some(body_start) = cursor.checked_add(hdr.header_len) else {
            break;
        };
        let Some(body_end) = body_start.checked_add(hdr.length) else {
            break;
        };
        if body_end > entries.len() {
            break;
        }
        if hdr.tag == 0x30
            && let Some(seq_body) = entries.get(body_start..body_end)
            && let Some(pair) = der_entry_pair(seq_body)
        {
            out.push(pair);
        }
        cursor = body_end;
    }
    out
}

/// Decodes one `SEQUENCE { UTF8String key, value }` entry.
fn der_entry_pair(seq_body: &[u8]) -> Option<(String, DerEntitlementValue)> {
    let khdr = der_read_header(seq_body)?;
    if khdr.tag != 0x0c {
        return None;
    }
    let kstart = khdr.header_len;
    let kend = kstart.checked_add(khdr.length)?;
    let kbytes = seq_body.get(kstart..kend)?;
    let key = core::str::from_utf8(kbytes).ok()?.to_string();
    let value = seq_body
        .get(kend..)
        .and_then(|rest| der_decode_value(rest, 0))
        .unwrap_or(DerEntitlementValue::Other(0));
    Some((key, value))
}

/// Decodes one DER value TLV starting at the front of `buf`.
fn der_decode_value(buf: &[u8], depth: u32) -> Option<DerEntitlementValue> {
    if depth > MAX_DER_VALUE_DEPTH {
        return Some(DerEntitlementValue::Other(0));
    }
    let hdr = der_read_header(buf)?;
    let start = hdr.header_len;
    let end = start.checked_add(hdr.length)?;
    let body = buf.get(start..end)?;
    let value = match hdr.tag {
        0x01 => DerEntitlementValue::Bool(body.first().copied().unwrap_or(0) != 0),
        0x02 => DerEntitlementValue::Integer(der_decode_integer(body)),
        0x0c => DerEntitlementValue::String(String::from_utf8_lossy(body).into_owned()),
        0x30 | 0x31 | 0xa0 | 0xb0 => {
            let mut items: Vec<DerEntitlementValue> = Vec::new();
            let mut cursor = 0usize;
            while cursor < body.len() && items.len() < MAX_DER_ARRAY_ITEMS {
                let Some(rem) = body.get(cursor..) else {
                    break;
                };
                let Some(h) = der_read_header(rem) else {
                    break;
                };
                let Some(bs) = cursor.checked_add(h.header_len) else {
                    break;
                };
                let Some(be) = bs.checked_add(h.length) else {
                    break;
                };
                if be > body.len() {
                    break;
                }
                if let Some(item) = body.get(cursor..be).and_then(|tlv| {
                    der_decode_value(tlv, depth.checked_add(1).unwrap_or(MAX_DER_VALUE_DEPTH))
                }) {
                    items.push(item);
                }
                cursor = be;
            }
            DerEntitlementValue::Array(items)
        }
        other => DerEntitlementValue::Other(other),
    };
    Some(value)
}

/// Folds a big-endian DER `INTEGER` body into an `i64` (values wider
/// than 8 bytes keep only the low 8).
fn der_decode_integer(body: &[u8]) -> i64 {
    let mut v: i64 = 0;
    for b in body.iter().take(8) {
        v = v.wrapping_shl(8) | i64::from(*b);
    }
    v
}

fn der_first_utf8_string(seq_body: &[u8]) -> Option<String> {
    let hdr = der_read_header(seq_body)?;
    if hdr.tag != 0x0c {
        return None;
    }
    let body_start = hdr.header_len;
    let body_end = body_start.checked_add(hdr.length)?;
    let body = seq_body.get(body_start..body_end)?;
    // Validate UTF-8 *before* allocating, so a malformed key does
    // not pay for a Vec just to have it dropped.
    core::str::from_utf8(body).ok().map(String::from)
}

/// Copy the prefix of `src` into `dst`, leaving any trailing bytes
/// in `dst` untouched.
///
/// Used by [`CodeDirectory::cd_hash_truncated`] to land a SHA-256 /
/// SHA-384 / SHA-512 digest into a fixed 20-byte AMFI buffer
/// without an intermediate `Vec`. Both halves of the
/// `copy_from_slice` are sub-sliced to the same `n`, so the call
/// can never panic (the lengths are equal by construction).
fn copy_prefix(dst: &mut [u8], src: &[u8]) {
    let n = core::cmp::min(dst.len(), src.len());
    if let (Some(dst_head), Some(src_head)) = (dst.get_mut(..n), src.get(..n)) {
        dst_head.copy_from_slice(src_head);
    }
}

struct DerHeader {
    tag: u8,
    length: usize,
    header_len: usize,
}

fn der_read_header(buf: &[u8]) -> Option<DerHeader> {
    let tag = *buf.first()?;
    let len_byte = *buf.get(1)?;
    if len_byte < 0x80 {
        return Some(DerHeader {
            tag,
            length: len_byte as usize,
            header_len: 2,
        });
    }
    let n = (len_byte & 0x7f) as usize;
    if n == 0 || n > 4 {
        return None;
    }
    let mut length = 0usize;
    for i in 0..n {
        let b = *buf.get(2usize.checked_add(i)?)?;
        length = length.wrapping_shl(8) | (b as usize);
    }
    Some(DerHeader {
        tag,
        length,
        header_len: 2usize.checked_add(n)?,
    })
}

// === Internal requirement-expression evaluator ===
//
// Ports the CSEL / CSCO opcode grammar (Apple `requirement.h`,
// cross-checked against blacktop/go-macho `requirement.go`). Every
// field is big-endian, like the rest of the code-signing payload.

/// `exprForm` opcode values (Apple `requirement.h` `ExprOp`).
mod req_op {
    pub const FALSE: u32 = 0;
    pub const TRUE: u32 = 1;
    pub const IDENT: u32 = 2;
    pub const APPLE_ANCHOR: u32 = 3;
    pub const ANCHOR_HASH: u32 = 4;
    pub const INFO_KEY_VALUE: u32 = 5;
    pub const AND: u32 = 6;
    pub const OR: u32 = 7;
    pub const CD_HASH: u32 = 8;
    pub const NOT: u32 = 9;
    pub const INFO_KEY_FIELD: u32 = 10;
    pub const CERT_FIELD: u32 = 11;
    pub const TRUSTED_CERT: u32 = 12;
    pub const TRUSTED_CERTS: u32 = 13;
    pub const CERT_GENERIC: u32 = 14;
    pub const APPLE_GENERIC_ANCHOR: u32 = 15;
    pub const ENTITLEMENT_FIELD: u32 = 16;
    pub const CERT_POLICY: u32 = 17;
    pub const NAMED_ANCHOR: u32 = 18;
    pub const NAMED_CODE: u32 = 19;
}

/// High-byte flag bits on an opcode (`opFlagMask` / `opGeneric*`).
const REQ_OP_FLAG_MASK: u32 = 0xFF00_0000;
const REQ_OP_GENERIC_FALSE: u32 = 0x8000_0000;
const REQ_OP_GENERIC_SKIP: u32 = 0x4000_0000;

/// Match-suffix opcodes for field comparisons (`MatchOperation`).
mod match_op {
    pub const EXISTS: u32 = 0;
    pub const EQUAL: u32 = 1;
    pub const CONTAINS: u32 = 2;
    pub const BEGINS_WITH: u32 = 3;
    pub const ENDS_WITH: u32 = 4;
    pub const LESS_THAN: u32 = 5;
    pub const GREATER_THAN: u32 = 6;
    pub const LESS_EQUAL: u32 = 7;
    pub const GREATER_EQUAL: u32 = 8;
}

/// Syntax-nesting levels controlling expression parenthesization.
const SL_PRIMARY: u32 = 0;
const SL_AND: u32 = 1;
const SL_OR: u32 = 2;
const SL_TOP: u32 = 3;

/// Forward big-endian byte cursor over requirement-expression bytes.
struct ReqCursor<'a> {
    buf: &'a [u8],
    pos: usize,
}

impl<'a> ReqCursor<'a> {
    fn new(buf: &'a [u8]) -> Self {
        Self { buf, pos: 0 }
    }

    /// Reads a big-endian `u32` and advances the cursor.
    fn u32(&mut self) -> Option<u32> {
        let v = read_u32_be_at(self.buf, self.pos)?;
        self.pos = self.pos.checked_add(4)?;
        Some(v)
    }

    /// Reads a length-prefixed, 4-byte-aligned data field, returning
    /// its `length` significant bytes (the alignment padding is
    /// consumed but not returned).
    fn data(&mut self) -> Option<&'a [u8]> {
        let len = self.u32()? as usize;
        let end = self.pos.checked_add(len)?;
        let slice = self.buf.get(self.pos..end)?;
        let aligned = len.checked_add(3)? & !3usize;
        self.pos = self.pos.checked_add(aligned)?;
        Some(slice)
    }
}

/// Locates and evaluates the requirement blob at `off` within the
/// requirements vector, returning its expression text.
fn decode_requirement_blob(vector: &[u8], off: usize) -> Option<String> {
    // Nested blob: [magic(0xfade0c00)][length][kind][expr…].
    let magic = read_u32_be_at(vector, off)?;
    if magic != CSMAGIC_REQUIREMENT {
        return None;
    }
    let length = read_u32_be_at(vector, off.checked_add(4)?)? as usize;
    let blob_end = off.checked_add(length)?;
    // `kind` (exprForm == 1) occupies +8; the expression starts at +12.
    let expr_start = off.checked_add(12)?;
    let expr = vector.get(expr_start..blob_end)?;
    let mut cursor = ReqCursor::new(expr);
    eval_expression(&mut cursor, SL_TOP, 0)
}

/// Evaluates one requirement-expression node into text.
fn eval_expression(cursor: &mut ReqCursor<'_>, syntax_level: u32, depth: u32) -> Option<String> {
    if depth > MAX_REQUIREMENT_DEPTH {
        return Some("/* … */".to_string());
    }
    let next = depth.checked_add(1)?;
    let op = cursor.u32()?;
    match op {
        req_op::FALSE => Some("never".to_string()),
        req_op::TRUE => Some("always".to_string()),
        req_op::IDENT => Some(format!("identifier \"{}\"", utf8_lossy(cursor.data()?))),
        req_op::APPLE_ANCHOR => Some("anchor apple".to_string()),
        req_op::APPLE_GENERIC_ANCHOR => Some("anchor apple generic".to_string()),
        req_op::ANCHOR_HASH => {
            let slot = get_cert_slot(cursor)?;
            let data = cursor.data()?;
            Some(format!("certificate {slot} = H\"{}\"", hex_encode(data)))
        }
        req_op::INFO_KEY_VALUE => {
            let key = utf8_lossy(cursor.data()?);
            let value = utf8_lossy(cursor.data()?);
            Some(format!("info[{key}] = \"{value}\""))
        }
        req_op::AND => {
            let paren = syntax_level < SL_AND;
            let left = eval_expression(cursor, SL_AND, next)?;
            let right = eval_expression(cursor, SL_AND, next)?;
            Some(wrap(paren, format!("{left} and {right}")))
        }
        req_op::OR => {
            let paren = syntax_level < SL_OR;
            let left = eval_expression(cursor, SL_OR, next)?;
            let right = eval_expression(cursor, SL_OR, next)?;
            Some(wrap(paren, format!("{left} or {right}")))
        }
        req_op::NOT => Some(format!("! {}", eval_expression(cursor, SL_PRIMARY, next)?)),
        req_op::CD_HASH => Some(format!("cdhash H\"{}\"", hex_encode(cursor.data()?))),
        req_op::INFO_KEY_FIELD => {
            let key = utf8_lossy(cursor.data()?);
            let m = get_match(cursor)?;
            Some(format!("info[{key}]{m}"))
        }
        req_op::ENTITLEMENT_FIELD => {
            let key = utf8_lossy(cursor.data()?);
            let m = get_match(cursor)?;
            Some(format!("entitlement[{key}]{m}"))
        }
        req_op::CERT_FIELD => {
            let slot = get_cert_slot(cursor)?;
            let field = utf8_lossy(cursor.data()?);
            let m = get_match(cursor)?;
            Some(format!("certificate {slot}[{field}]{m}"))
        }
        req_op::CERT_GENERIC => {
            let slot = get_cert_slot(cursor)?;
            let oid = decode_oid(cursor.data()?);
            let m = get_match(cursor)?;
            Some(format!("certificate {slot}[field.{oid}]{m}"))
        }
        req_op::CERT_POLICY => {
            let slot = get_cert_slot(cursor)?;
            let oid = decode_oid(cursor.data()?);
            let m = get_match(cursor)?;
            Some(format!("certificate {slot}[policy.{oid}]{m}"))
        }
        req_op::TRUSTED_CERT => Some(format!("certificate {} trusted", get_cert_slot(cursor)?)),
        req_op::TRUSTED_CERTS => Some("anchor trusted".to_string()),
        req_op::NAMED_ANCHOR => Some(format!("anchor apple {}", utf8_lossy(cursor.data()?))),
        req_op::NAMED_CODE => Some(format!("({})", utf8_lossy(cursor.data()?))),
        other => {
            if other & REQ_OP_GENERIC_FALSE != 0 {
                Some(format!("false /* opcode {} */", other & !REQ_OP_FLAG_MASK))
            } else if other & REQ_OP_GENERIC_SKIP != 0 {
                Some(format!("/* opcode {} */", other & !REQ_OP_FLAG_MASK))
            } else {
                Some(format!("/* unknown opcode {other} */"))
            }
        }
    }
}

/// Reads a match-suffix operator and operand into text.
fn get_match(cursor: &mut ReqCursor<'_>) -> Option<String> {
    let op = cursor.u32()?;
    let text = match op {
        match_op::EXISTS => " /* exists */".to_string(),
        match_op::EQUAL => format!(" = \"{}\"", utf8_lossy(cursor.data()?)),
        match_op::CONTAINS => format!(" ~ \"{}\"", utf8_lossy(cursor.data()?)),
        match_op::BEGINS_WITH => format!(" = \"{}*\"", utf8_lossy(cursor.data()?)),
        match_op::ENDS_WITH => format!(" = \"*{}\"", utf8_lossy(cursor.data()?)),
        match_op::LESS_THAN => format!(" < \"{}\"", utf8_lossy(cursor.data()?)),
        match_op::GREATER_THAN => format!(" > \"{}\"", utf8_lossy(cursor.data()?)),
        match_op::LESS_EQUAL => format!(" <= \"{}\"", utf8_lossy(cursor.data()?)),
        match_op::GREATER_EQUAL => format!(" >= \"{}\"", utf8_lossy(cursor.data()?)),
        _ => " /* match? */".to_string(),
    };
    Some(text)
}

/// Reads a certificate-slot index into text (`leaf` / `root` / N).
fn get_cert_slot(cursor: &mut ReqCursor<'_>) -> Option<String> {
    let slot = cursor.u32()? as i32;
    Some(match slot {
        0 => "leaf".to_string(),
        -1 => "root".to_string(),
        n => n.to_string(),
    })
}

/// Decodes a DER-style OID body (base-128 varints) into dotted form.
fn decode_oid(data: &[u8]) -> String {
    let mut pos = 0usize;
    let Some(first) = oid_component(data, &mut pos) else {
        return String::new();
    };
    let q1 = core::cmp::min(first.checked_div(40).unwrap_or(0), 2);
    let second = first.saturating_sub(q1.saturating_mul(40));
    let mut out = format!("{q1}.{second}");
    while let Some(v) = oid_component(data, &mut pos) {
        out.push('.');
        out.push_str(&v.to_string());
    }
    out
}

/// Reads one base-128 OID component starting at `*pos`, advancing it.
fn oid_component(data: &[u8], pos: &mut usize) -> Option<u32> {
    let mut result: u32 = 0;
    loop {
        let b = *data.get(*pos)?;
        *pos = pos.checked_add(1)?;
        result = result.wrapping_mul(128).wrapping_add((b & 0x7f) as u32);
        if b & 0x80 == 0 {
            break;
        }
    }
    Some(result)
}

/// Wraps `s` in parentheses when `paren` is set.
fn wrap(paren: bool, s: String) -> String {
    if paren { format!("({s})") } else { s }
}

/// Lossy UTF-8 rendering of a byte slice for display.
fn utf8_lossy(data: &[u8]) -> String {
    String::from_utf8_lossy(data).into_owned()
}

/// Lowercase hex encoding of a byte slice.
fn hex_encode(data: &[u8]) -> String {
    use core::fmt::Write as _;
    let mut out = String::with_capacity(data.len().saturating_mul(2));
    for b in data {
        let _ = write!(out, "{b:02x}");
    }
    out
}

/// Iterator over [`BlobIndex`] entries in a SuperBlob.
pub struct BlobIter<'a> {
    data: &'a [u8],
    base: usize,
    count: u32,
    cursor: u32,
}

impl<'a> Iterator for BlobIter<'a> {
    type Item = BlobIndex;
    fn next(&mut self) -> Option<BlobIndex> {
        if self.cursor >= self.count {
            return None;
        }
        let i = self.cursor;
        self.cursor = self.cursor.checked_add(1)?;
        let entry_off = self
            .base
            .checked_add(SUPERBLOB_HEADER_SIZE)?
            .checked_add((i as usize).checked_mul(BLOB_INDEX_SIZE)?)?;
        let raw = read_u32_be_at(self.data, entry_off)?;
        let off_off = entry_off.checked_add(4)?;
        let offset = read_u32_be_at(self.data, off_off)?;
        Some(BlobIndex {
            slot: Slot::from_raw(raw),
            raw_slot: raw,
            offset,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn slot_round_trip_known_values() {
        for (raw, want) in [
            (0u32, Slot::CodeDirectory),
            (1, Slot::InfoSlot),
            (2, Slot::Requirements),
            (3, Slot::ResourceDir),
            (4, Slot::Application),
            (5, Slot::Entitlements),
            (7, Slot::DerEntitlements),
            (8, Slot::LaunchConstraintSelf),
            (9, Slot::LaunchConstraintParent),
            (10, Slot::LaunchConstraintResponsible),
            (11, Slot::LibraryConstraint),
            (0x1000, Slot::AlternateCodeDirectory(0)),
            (0x1004, Slot::AlternateCodeDirectory(4)),
            (0x10000, Slot::SignatureSlot),
            (0x10001, Slot::IdentificationSlot),
            (0x10002, Slot::TicketSlot),
        ] {
            assert_eq!(Slot::from_raw(raw), want);
        }
        assert_eq!(Slot::from_raw(99), Slot::Other(99));
        assert_eq!(Slot::from_raw(0x1005), Slot::Other(0x1005));
    }

    #[test]
    fn signature_parse_rejects_wrong_magic() {
        // Header with magic 0x12345678 (not an embedded signature).
        let bytes = [
            0x12, 0x34, 0x56, 0x78, // magic
            0x00, 0x00, 0x00, 0x0c, // length
            0x00, 0x00, 0x00, 0x00, // count
        ];
        assert!(Signature::parse(&bytes, 0).is_none());
    }

    #[test]
    fn signature_parse_accepts_embedded_magic() {
        // Empty SuperBlob: magic + length=12 + count=0.
        let bytes = [
            0xfa, 0xde, 0x0c, 0xc0, // CSMAGIC_EMBEDDED_SIGNATURE
            0x00, 0x00, 0x00, 0x0c, // length
            0x00, 0x00, 0x00, 0x00, // count
        ];
        let sig = Signature::parse(&bytes, 0).unwrap();
        assert_eq!(sig.magic(), CSMAGIC_EMBEDDED_SIGNATURE);
        assert_eq!(sig.length(), 12);
        assert_eq!(sig.blob_count(), 0);
        assert_eq!(sig.blobs().count(), 0);
    }

    #[test]
    fn signature_blob_iter_returns_index_entries() {
        // SuperBlob with one index entry: slot=2 (Requirements),
        // offset=0x1c. The blob payload at 0x1c isn't required for
        // iter() to enumerate - only for blob_bytes_at().
        let mut bytes = vec![
            0xfa, 0xde, 0x0c, 0xc0, // magic
            0x00, 0x00, 0x00, 0x1c, // length = 28
            0x00, 0x00, 0x00, 0x01, // count = 1
            // index[0]:
            0x00, 0x00, 0x00, 0x02, // type=2 (Requirements)
            0x00, 0x00, 0x00, 0x14, // offset=20 (0x14)
        ];
        // pad to length 28
        bytes.extend([0; 8]);
        let sig = Signature::parse(&bytes, 0).unwrap();
        let blobs: Vec<_> = sig.blobs().collect();
        assert_eq!(blobs.len(), 1);
        assert_eq!(blobs[0].slot, Slot::Requirements);
        assert_eq!(blobs[0].raw_slot, 2);
        assert_eq!(blobs[0].offset, 20);
    }

    #[test]
    fn requirements_decode_designated_expression() {
        // A designated requirement: identifier "a" and anchor apple generic.
        let mut v: Vec<u8> = Vec::new();
        v.extend(CSMAGIC_REQUIREMENTS.to_be_bytes()); // magic
        v.extend(52u32.to_be_bytes()); // total length
        v.extend(1u32.to_be_bytes()); // count
        v.extend(3u32.to_be_bytes()); // type = designated
        v.extend(20u32.to_be_bytes()); // offset of the requirement blob
        // requirement blob at offset 20:
        v.extend(CSMAGIC_REQUIREMENT.to_be_bytes()); // magic
        v.extend(32u32.to_be_bytes()); // blob length
        v.extend(1u32.to_be_bytes()); // kind = exprForm
        // expression: And( Ident("a"), AppleGenericAnchor )
        v.extend(6u32.to_be_bytes()); // opAnd
        v.extend(2u32.to_be_bytes()); // opIdent
        v.extend(1u32.to_be_bytes()); // data length = 1
        v.extend([0x61, 0x00, 0x00, 0x00]); // "a" + 4-byte alignment pad
        v.extend(15u32.to_be_bytes()); // opAppleGenericAnchor
        assert_eq!(v.len(), 52);

        let reqs = Requirements::parse(&v).expect("parse requirements");
        let decoded = reqs.decoded();
        assert_eq!(decoded.len(), 1);
        assert_eq!(decoded[0].kind, RequirementKind::Designated);
        assert_eq!(decoded[0].text, "identifier \"a\" and anchor apple generic");
    }

    #[test]
    fn der_entitlement_pairs_decode_key_and_value() {
        // A single SEQUENCE { UTF8String "k", BOOLEAN true }.
        let payload: [u8; 8] = [0x30, 0x06, 0x0c, 0x01, 0x6b, 0x01, 0x01, 0xff];
        let pairs = der_collect_pairs(&payload);
        assert_eq!(pairs.len(), 1);
        assert_eq!(pairs[0].0, "k");
        assert_eq!(pairs[0].1, DerEntitlementValue::Bool(true));
        assert_eq!(pairs[0].1.kind_label(), "bool");
        assert_eq!(pairs[0].1.display(), "true");
    }
}