IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

  1. #1
    Chroniqueur Actualités

    Homme Profil pro
    Administrateur de base de données
    Inscrit en
    Mars 2013
    Messages
    8 456
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Canada

    Informations professionnelles :
    Activité : Administrateur de base de données

    Informations forums :
    Inscription : Mars 2013
    Messages : 8 456
    Points : 197 830
    Points
    197 830
    Par défaut Le nom Reality OS qu'Apple utiliserait pour désigner l'OS tournant sur son casque AR/VR apparaît dans un dépôt
    Des références à un nouvel OS d'Apple appelé Reality OS émergent dans des référentiels GitHub utilisés par l'entreprise,
    suggérant qu'Apple prépare un OS dédié à la réalité augmentée

    Les développeurs logiciels ont découvert des références apparentes à un nouveau système d'exploitation Apple appelé realityOS dans les journaux de téléchargement de l'App Store et dans les référentiels GitHub utilisés par l'entreprise. Les références ont été largement partagées par les développeurs sur Twitter.

    Il n'y a plus beaucoup de place pour le doute : des éléments indiquent qu'Apple prépare bien un système d'exploitation spécifiquement dédié à la réalité augmentée. En parcourant la portion de code open source utilisée par l'App Store et publiée sur GitHub, des développeurs ont trouvé des lignes de code qui évoquent un nouveau système baptisé « realityOS », qui sera sans doute lié au projet de casque AR/VR d'Apple. Des liens entre iOS et ce nouveau système sont mentionnés, mais aussi un simulateur utilisé par les développeurs pour tester leurs applications sans avoir le matériel sous la main.

    Code C++ : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    #include <stdlib.h>
    #include <assert.h>
    #include <string.h>
    #include <stdio.h>
    #include <sys/stat.h>
    #include <sys/types.h>
    #include <sys/errno.h>
    #include <sys/fcntl.h>
    #include <unistd.h>
    #include <TargetConditionals.h>
    #include <mach/host_info.h>
    #include <mach/mach.h>
    #include <mach/mach_host.h>
     
    #include "Array.h"
    #include "MachOFile.h"
    #include "SupportedArchs.h"
     
    #if BUILDING_DYLD || BUILDING_LIBDYLD
        // define away restrict until rdar://60166935 is fixed
        #define restrict
        #include <subsystem.h>
    #endif
     
    namespace dyld3 {
     
    ////////////////////////////  posix wrappers ////////////////////////////////////////
     
    // <rdar://problem/10111032> wrap calls to stat() with check for EAGAIN
    int stat(const char* path, struct stat* buf)
    {
        int result;
        do {
    #if BUILDING_DYLD
            result = ::stat_with_subsystem(path, buf);
    #else
            result = ::stat(path, buf);
    #endif
        } while ((result == -1) && ((errno == EAGAIN) || (errno == EINTR)));
     
        return result;
    }
     
    // <rdar://problem/13805025> dyld should retry open() if it gets an EGAIN
    int open(const char* path, int flag, int other)
    {
        int result;
        do {
    #if BUILDING_DYLD
            if (flag & O_CREAT)
                result = ::open(path, flag, other);
            else
                result = ::open_with_subsystem(path, flag);
    #else
            result = ::open(path, flag, other);
    #endif
        } while ((result == -1) && ((errno == EAGAIN) || (errno == EINTR)));
     
        return result;
    }
     
     
    ////////////////////////////  FatFile ////////////////////////////////////////
     
    const FatFile* FatFile::isFatFile(const void* fileStart)
    {
        const FatFile* fileStartAsFat = (FatFile*)fileStart;
        if ( (fileStartAsFat->magic == OSSwapBigToHostInt32(FAT_MAGIC)) || (fileStartAsFat->magic == OSSwapBigToHostInt32(FAT_MAGIC_64)) )
            return fileStartAsFat;
        else
            return nullptr;
    }
     
    bool FatFile::isValidSlice(Diagnostics& diag, uint64_t fileLen, uint32_t sliceIndex,
                               uint32_t sliceCpuType, uint32_t sliceCpuSubType, uint64_t sliceOffset, uint64_t sliceLen) const {
        if ( greaterThanAddOrOverflow(sliceOffset, sliceLen, fileLen) ) {
            diag.error("slice %d extends beyond end of file", sliceIndex);
            return false;
        }
        const dyld3::MachOFile* mf = (const dyld3::MachOFile*)((uint8_t*)this+sliceOffset);
        if (!mf->isMachO(diag, sliceLen))
            return false;
        if ( mf->cputype != (cpu_type_t)sliceCpuType ) {
            diag.error("cpu type in slice (0x%08X) does not match fat header (0x%08X)", mf->cputype, sliceCpuType);
            return false;
        }
        else if ( (mf->cpusubtype & ~CPU_SUBTYPE_MASK) != (sliceCpuSubType & ~CPU_SUBTYPE_MASK) ) {
            diag.error("cpu subtype in slice (0x%08X) does not match fat header (0x%08X)", mf->cpusubtype, sliceCpuSubType);
            return false;
        }
        uint32_t pageSizeMask = mf->uses16KPages() ? 0x3FFF : 0xFFF;
        if ( (sliceOffset & pageSizeMask) != 0 ) {
            // slice not page aligned
            if ( strncmp((char*)this+sliceOffset, "!<arch>", 7) == 0 )
                diag.error("file is static library");
            else
                diag.error("slice is not page aligned");
            return false;
        }
        return true;
    }
     
    void FatFile::forEachSlice(Diagnostics& diag, uint64_t fileLen, bool validate,
                               void (^callback)(uint32_t sliceCpuType, uint32_t sliceCpuSubType, const void* sliceStart, uint64_t sliceSize, bool& stop)) const
    {
    	if ( this->magic == OSSwapBigToHostInt32(FAT_MAGIC) ) {
            const uint64_t maxArchs = ((4096 - sizeof(fat_header)) / sizeof(fat_arch));
            const uint32_t numArchs = OSSwapBigToHostInt32(nfat_arch);
            if ( numArchs > maxArchs ) {
                diag.error("fat header too large: %u entries", numArchs);
                return;
            }
            bool stop = false;
            const fat_arch* const archs = (fat_arch*)(((char*)this)+sizeof(fat_header));
            for (uint32_t i=0; i < numArchs; ++i) {
                uint32_t cpuType    = OSSwapBigToHostInt32(archs[i].cputype);
                uint32_t cpuSubType = OSSwapBigToHostInt32(archs[i].cpusubtype);
                uint32_t offset     = OSSwapBigToHostInt32(archs[i].offset);
                uint32_t len        = OSSwapBigToHostInt32(archs[i].size);
                Diagnostics sliceDiag;
                if ( !validate || isValidSlice(sliceDiag, fileLen, i, cpuType, cpuSubType, offset, len) )
                    callback(cpuType, cpuSubType, (uint8_t*)this+offset, len, stop);
                if ( stop )
                    break;
                if ( sliceDiag.hasError() )
                    diag.appendError("%s, ", sliceDiag.errorMessageCStr());
            }
     
            // Look for one more slice
            if ( numArchs != maxArchs ) {
                uint32_t cpuType    = OSSwapBigToHostInt32(archs[numArchs].cputype);
                uint32_t cpuSubType = OSSwapBigToHostInt32(archs[numArchs].cpusubtype);
                uint32_t offset     = OSSwapBigToHostInt32(archs[numArchs].offset);
                uint32_t len        = OSSwapBigToHostInt32(archs[numArchs].size);
                if ((cpuType == CPU_TYPE_ARM64) && ((cpuSubType == CPU_SUBTYPE_ARM64_ALL || cpuSubType == CPU_SUBTYPE_ARM64_V8))) {
                    if ( !validate || isValidSlice(diag, fileLen, numArchs, cpuType, cpuSubType, offset, len) )
                        callback(cpuType, cpuSubType, (uint8_t*)this+offset, len, stop);
                }
            }
        }
        else if ( this->magic == OSSwapBigToHostInt32(FAT_MAGIC_64) ) {
            if ( OSSwapBigToHostInt32(nfat_arch) > ((4096 - sizeof(fat_header)) / sizeof(fat_arch)) ) {
                diag.error("fat header too large: %u entries", OSSwapBigToHostInt32(nfat_arch));
                return;
            }
            bool stop = false;
            const fat_arch_64* const archs = (fat_arch_64*)(((char*)this)+sizeof(fat_header));
            for (uint32_t i=0; i < OSSwapBigToHostInt32(nfat_arch); ++i) {
                uint32_t cpuType    = OSSwapBigToHostInt32(archs[i].cputype);
                uint32_t cpuSubType = OSSwapBigToHostInt32(archs[i].cpusubtype);
                uint64_t offset     = OSSwapBigToHostInt64(archs[i].offset);
                uint64_t len        = OSSwapBigToHostInt64(archs[i].size);
                if ( !validate || isValidSlice(diag, fileLen, i, cpuType, cpuSubType, offset, len) )
                    callback(cpuType, cpuSubType, (uint8_t*)this+offset, len, stop);
                if ( stop )
                    break;
            }
        }
        else {
            diag.error("not a fat file");
        }
    }
     
    void FatFile::forEachSlice(Diagnostics& diag, uint64_t fileLen, void (^callback)(uint32_t sliceCpuType, uint32_t sliceCpuSubType, const void* sliceStart, uint64_t sliceSize, bool& stop)) const
    {
        forEachSlice(diag, fileLen, true, callback);
    }
     
    const char* FatFile::archNames(char strBuf[256]) const
    {
        strBuf[0] = '\0';
        Diagnostics   diag;
        __block bool  needComma = false;
        this->forEachSlice(diag, 0xFFFFFFFF, false, ^(uint32_t sliceCpuType, uint32_t sliceCpuSubType, const void* sliceStart, uint64_t sliceSize, bool& stop) {
            if ( needComma )
                strlcat(strBuf, ",", 256);
            strlcat(strBuf, MachOFile::archName(sliceCpuType, sliceCpuSubType), 256);
            needComma = true;
        });
        return strBuf;
    }
     
    bool FatFile::isFatFileWithSlice(Diagnostics& diag, uint64_t fileLen, const GradedArchs& archs, bool isOSBinary,
                                     uint64_t& sliceOffset, uint64_t& sliceLen, bool& missingSlice) const
    {
        missingSlice = false;
        if ( (this->magic != OSSwapBigToHostInt32(FAT_MAGIC)) && (this->magic != OSSwapBigToHostInt32(FAT_MAGIC_64)) )
            return false;
     
        __block int bestGrade = 0;
        forEachSlice(diag, fileLen, ^(uint32_t sliceCpuType, uint32_t sliceCpuSubType, const void* sliceStart, uint64_t sliceSize, bool& stop) {
            if (int sliceGrade = archs.grade(sliceCpuType, sliceCpuSubType, isOSBinary)) {
                if ( sliceGrade > bestGrade ) {
                    sliceOffset = (char*)sliceStart - (char*)this;
                    sliceLen    = sliceSize;
                    bestGrade   = sliceGrade;
                }
            }
        });
        if ( diag.hasError() )
            return false;
     
        if ( bestGrade == 0 )
            missingSlice = true;
     
        return (bestGrade != 0);
    }
     
     
    ////////////////////////////  GradedArchs ////////////////////////////////////////
     
     
    #define GRADE_i386        CPU_TYPE_I386,       CPU_SUBTYPE_I386_ALL,    false
    #define GRADE_x86_64      CPU_TYPE_X86_64,     CPU_SUBTYPE_X86_64_ALL,  false
    #define GRADE_x86_64h     CPU_TYPE_X86_64,     CPU_SUBTYPE_X86_64_H,    false
    #define GRADE_armv7       CPU_TYPE_ARM,        CPU_SUBTYPE_ARM_V7,      false
    #define GRADE_armv7s      CPU_TYPE_ARM,        CPU_SUBTYPE_ARM_V7S,     false
    #define GRADE_armv7k      CPU_TYPE_ARM,        CPU_SUBTYPE_ARM_V7K,     false
    #define GRADE_arm64       CPU_TYPE_ARM64,      CPU_SUBTYPE_ARM64_ALL,   false
    #define GRADE_arm64e      CPU_TYPE_ARM64,      CPU_SUBTYPE_ARM64E,      false
    #define GRADE_arm64e_pb   CPU_TYPE_ARM64,      CPU_SUBTYPE_ARM64E,      true
    #define GRADE_arm64_32    CPU_TYPE_ARM64_32,   CPU_SUBTYPE_ARM64_32_V8, false
     
    const GradedArchs GradedArchs::i386              = { {{GRADE_i386,    1}} };
    const GradedArchs GradedArchs::x86_64            = { {{GRADE_x86_64,  1}} };
    const GradedArchs GradedArchs::x86_64h           = { {{GRADE_x86_64h, 2}, {GRADE_x86_64, 1}} };
    const GradedArchs GradedArchs::arm64             = { {{GRADE_arm64,   1}} };
    #if SUPPORT_ARCH_arm64e
    const GradedArchs GradedArchs::arm64e_keysoff    = { {{GRADE_arm64e,    2}, {GRADE_arm64, 1}} };
    const GradedArchs GradedArchs::arm64e_keysoff_pb = { {{GRADE_arm64e_pb, 2}, {GRADE_arm64, 1}} };
    const GradedArchs GradedArchs::arm64e            = { {{GRADE_arm64e,    1}} };
    const GradedArchs GradedArchs::arm64e_pb         = { {{GRADE_arm64e_pb, 1}} };
    #endif
    const GradedArchs GradedArchs::armv7             = { {{GRADE_armv7,   1}} };
    const GradedArchs GradedArchs::armv7s            = { {{GRADE_armv7s,  2}, {GRADE_armv7, 1}} };
    const GradedArchs GradedArchs::armv7k            = { {{GRADE_armv7k,  1}} };
    #if SUPPORT_ARCH_arm64_32
    const GradedArchs GradedArchs::arm64_32          = { {{GRADE_arm64_32, 1}} };
    #endif
     
    int GradedArchs::grade(uint32_t cputype, uint32_t cpusubtype, bool isOSBinary) const
    {
        for (const CpuGrade* p = _orderedCpuTypes; p->type != 0; ++p) {
            if ( (p->type == cputype) && (p->subtype == (cpusubtype & ~CPU_SUBTYPE_MASK)) ) {
                if ( p->osBinary ) {
                    if ( isOSBinary )
                        return p->grade;
                }
                else {
                    return p->grade;
                }
            }
        }
        return 0;
    }
     
    const char* GradedArchs::name() const
    {
        return MachOFile::archName(_orderedCpuTypes[0].type, _orderedCpuTypes[0].subtype);
    }
     
    bool GradedArchs::checksOSBinary() const
    {
        for (const CpuGrade* p = _orderedCpuTypes; p->type != 0; ++p) {
            if ( p->osBinary )
                return true;
        }
        return false;
    }
     
    #if __x86_64__
    static bool isHaswell()
    {
        // FIXME: figure out a commpage way to check this
        struct host_basic_info info;
        mach_msg_type_number_t count = HOST_BASIC_INFO_COUNT;
        mach_port_t hostPort = mach_host_self();
        kern_return_t result = host_info(hostPort, HOST_BASIC_INFO, (host_info_t)&info, &count);
        mach_port_deallocate(mach_task_self(), hostPort);
        return (result == KERN_SUCCESS) && (info.cpu_subtype == CPU_SUBTYPE_X86_64_H);
    }
    #endif
     
    const GradedArchs& GradedArchs::forCurrentOS(bool keysOff, bool osBinariesOnly)
    {
    #if __arm64e__
        if ( osBinariesOnly )
            return (keysOff ? arm64e_keysoff_pb : arm64e_pb);
        else
            return (keysOff ? arm64e_keysoff : arm64e);
    #elif __ARM64_ARCH_8_32__
        return arm64_32;
    #elif __arm64__
        return arm64;
    #elif __ARM_ARCH_7K__
        return armv7k;
    #elif __ARM_ARCH_7S__
        return armv7s;
    #elif __ARM_ARCH_7A__
        return armv7;
    #elif __x86_64__
     #if TARGET_OS_SIMULATOR
        return x86_64;
      #else
        return isHaswell() ? x86_64h : x86_64;
      #endif
    #elif __i386__
        return i386;
    #else
        #error unknown platform
    #endif
    }
     
    const GradedArchs& GradedArchs::forName(const char* archName, bool keysOff)
    {
        if (strcmp(archName, "x86_64h") == 0 )
            return x86_64h;
        else if (strcmp(archName, "x86_64") == 0 )
            return x86_64;
    #if SUPPORT_ARCH_arm64e
        else if (strcmp(archName, "arm64e") == 0 )
            return keysOff ? arm64e_keysoff : arm64e;
    #endif
        else if (strcmp(archName, "arm64") == 0 )
            return arm64;
        else if (strcmp(archName, "armv7k") == 0 )
            return armv7k;
        else if (strcmp(archName, "armv7s") == 0 )
            return armv7s;
        else if (strcmp(archName, "armv7") == 0 )
            return armv7;
    #if SUPPORT_ARCH_arm64_32
        else if (strcmp(archName, "arm64_32") == 0 )
            return arm64_32;
    #endif
        else if (strcmp(archName, "i386") == 0 )
            return i386;
        assert(0 && "unknown arch name");
    }
     
     
     
    ////////////////////////////  MachOFile ////////////////////////////////////////
     
     
    const MachOFile::ArchInfo MachOFile::_s_archInfos[] = {
        { "x86_64",   CPU_TYPE_X86_64,   CPU_SUBTYPE_X86_64_ALL  },
        { "x86_64h",  CPU_TYPE_X86_64,   CPU_SUBTYPE_X86_64_H    },
        { "i386",     CPU_TYPE_I386,     CPU_SUBTYPE_I386_ALL    },
        { "arm64",    CPU_TYPE_ARM64,    CPU_SUBTYPE_ARM64_ALL   },
    #if SUPPORT_ARCH_arm64e
        { "arm64e",   CPU_TYPE_ARM64,    CPU_SUBTYPE_ARM64E     },
    #endif
    #if SUPPORT_ARCH_arm64_32
        { "arm64_32", CPU_TYPE_ARM64_32, CPU_SUBTYPE_ARM64_32_V8 },
    #endif
        { "armv7k",   CPU_TYPE_ARM,      CPU_SUBTYPE_ARM_V7K     },
        { "armv7s",   CPU_TYPE_ARM,      CPU_SUBTYPE_ARM_V7S     },
        { "armv7",    CPU_TYPE_ARM,      CPU_SUBTYPE_ARM_V7      }
    };
     
    const MachOFile::PlatformInfo MachOFile::_s_platformInfos[] = {
        { "macOS",       Platform::macOS,             LC_VERSION_MIN_MACOSX   },
        { "iOS",         Platform::iOS,               LC_VERSION_MIN_IPHONEOS },
        { "tvOS",        Platform::tvOS,              LC_VERSION_MIN_TVOS     },
        { "watchOS",     Platform::watchOS,           LC_VERSION_MIN_WATCHOS  },
        { "bridgeOS",    Platform::bridgeOS,          LC_BUILD_VERSION        },
        { "MacCatalyst", Platform::iOSMac,            LC_BUILD_VERSION        },
        { "iOS-sim",     Platform::iOS_simulator,     LC_BUILD_VERSION        },
        { "tvOS-sim",    Platform::tvOS_simulator,    LC_BUILD_VERSION        },
        { "watchOS-sim", Platform::watchOS_simulator, LC_BUILD_VERSION        },
        { "driverKit",   Platform::driverKit,         LC_BUILD_VERSION        },
    };
     
     
     
    bool MachOFile::is64() const
    {
        return (this->magic == MH_MAGIC_64);
    }
     
    size_t MachOFile::machHeaderSize() const
    {
        return is64() ? sizeof(mach_header_64) : sizeof(mach_header);
    }
     
    uint32_t MachOFile::maskedCpuSubtype() const
    {
        return (this->cpusubtype & ~CPU_SUBTYPE_MASK);
    }
     
    uint32_t MachOFile::pointerSize() const
    {
        if (this->magic == MH_MAGIC_64)
            return 8;
        else
            return 4;
    }
     
    bool MachOFile::uses16KPages() const
    {
        switch (this->cputype) {
            case CPU_TYPE_ARM64:
            case CPU_TYPE_ARM64_32:
                return true;
            case CPU_TYPE_ARM:
                // iOS is 16k aligned for armv7/armv7s and watchOS armv7k is 16k aligned
                return this->cpusubtype == CPU_SUBTYPE_ARM_V7K;
            default:
                return false;
        }
    }
     
    bool MachOFile::isArch(const char* aName) const
    {
        return (strcmp(aName, archName(this->cputype, this->cpusubtype)) == 0);
    }
     
    const char* MachOFile::archName(uint32_t cputype, uint32_t cpusubtype)
    {
        for (const ArchInfo& info : _s_archInfos) {
            if ( (cputype == info.cputype) && ((cpusubtype & ~CPU_SUBTYPE_MASK) == info.cpusubtype) ) {
                return info.name;
            }
        }
        return "unknown";
    }
     
    uint32_t MachOFile::cpuTypeFromArchName(const char* archName)
    {
        for (const ArchInfo& info : _s_archInfos) {
            if ( strcmp(archName, info.name) == 0 ) {
                return info.cputype;
            }
        }
        return 0;
    }
     
    uint32_t MachOFile::cpuSubtypeFromArchName(const char* archName)
    {
        for (const ArchInfo& info : _s_archInfos) {
            if ( strcmp(archName, info.name) == 0 ) {
                return info.cpusubtype;
            }
        }
        return 0;
    }
     
    const char* MachOFile::archName() const
    {
        return archName(this->cputype, this->cpusubtype);
    }
     
    static void appendDigit(char*& s, unsigned& num, unsigned place, bool& startedPrinting)
    {
        if ( num >= place ) {
            unsigned dig = (num/place);
            *s++ = '0' + dig;
            num -= (dig*place);
            startedPrinting = true;
        }
        else if ( startedPrinting ) {
            *s++ = '0';
        }
    }
     
    static void appendNumber(char*& s, unsigned num)
    {
        assert(num < 99999);
        bool startedPrinting = false;
        appendDigit(s, num, 10000, startedPrinting);
        appendDigit(s, num,  1000, startedPrinting);
        appendDigit(s, num,   100, startedPrinting);
        appendDigit(s, num,    10, startedPrinting);
        appendDigit(s, num,     1, startedPrinting);
        if ( !startedPrinting )
            *s++ = '0';
    }
     
    void MachOFile::packedVersionToString(uint32_t packedVersion, char versionString[32])
    {
        // sprintf(versionString, "%d.%d.%d", (packedVersion >> 16), ((packedVersion >> 8) & 0xFF), (packedVersion & 0xFF));
        char* s = versionString;
        appendNumber(s, (packedVersion >> 16));
        *s++ = '.';
        appendNumber(s, (packedVersion >> 8) & 0xFF);
        *s++ = '.';
        appendNumber(s, (packedVersion & 0xFF));
        *s++ = '\0';
    }
     
    bool MachOFile::builtForPlatform(Platform reqPlatform, bool onlyOnePlatform) const
    {
        __block bool foundRequestedPlatform = false;
        __block bool foundOtherPlatform     = false;
        forEachSupportedPlatform(^(Platform platform, uint32_t minOS, uint32_t sdk) {
            if ( platform == reqPlatform )
                foundRequestedPlatform = true;
            else
                foundOtherPlatform = true;
        });
        // if checking that this binary is built for exactly one platform, fail if more
        if ( foundOtherPlatform && onlyOnePlatform )
            return false;
        if ( foundRequestedPlatform )
            return true;
     
        // binary has no explict load command to mark platform
        // could be an old macOS binary, look at arch
        if  ( !foundOtherPlatform && (reqPlatform == Platform::macOS) ) {
            if ( this->cputype == CPU_TYPE_X86_64 )
                return true;
            if ( this->cputype == CPU_TYPE_I386 )
                return true;
        }
     
    #if BUILDING_DYLDINFO
        // Allow offline tools to analyze binaries dyld doesn't load, ie, those with platforms
        if ( !foundOtherPlatform && (reqPlatform == Platform::unknown) )
            return true;
    #endif
     
        return false;
    }
     
    bool MachOFile::loadableIntoProcess(Platform processPlatform, const char* path) const
    {
        if ( this->builtForPlatform(processPlatform) )
            return true;
     
        // Some host macOS dylibs can be loaded into simulator processes
        if ( MachOFile::isSimulatorPlatform(processPlatform) && this->builtForPlatform(Platform::macOS)) {
            static const char* const macOSHost[] = {
                "/usr/lib/system/libsystem_kernel.dylib",
                "/usr/lib/system/libsystem_platform.dylib",
                "/usr/lib/system/libsystem_pthread.dylib",
                "/usr/lib/system/libsystem_platform_debug.dylib",
                "/usr/lib/system/libsystem_pthread_debug.dylib",
                "/usr/lib/system/host/liblaunch_sim.dylib",
            };
            for (const char* libPath : macOSHost) {
                if (strcmp(libPath, path) == 0)
                    return true;
            }
        }
     
        // If this is being called on main executable where we expect a macOS program, Catalyst programs are also runnable
        if ( (this->filetype == MH_EXECUTE) && (processPlatform == Platform::macOS) && this->builtForPlatform(Platform::iOSMac, true) )
            return true;
    #if (TARGET_OS_OSX && TARGET_CPU_ARM64)
        if ( (this->filetype == MH_EXECUTE) && (processPlatform == Platform::macOS) && this->builtForPlatform(Platform::iOS, true) )
            return true;
    #endif
     
    #if TARGET_FEATURE_REALITYOS
        // allow iOS executables to use realityOS dylibs
        if ( (processPlatform == Platform::iOS) && this->builtForPlatform(Platform::realityOS, true) )
            return true;
     
        // allow iOS_Sim executables to use realityOS_Sim dylibs
        if ( (processPlatform == Platform::iOS_simulator) && this->builtForPlatform(Platform::realityOS_simulator, true) )
            return true;
    #endif
     
        bool iOSonMac = (processPlatform == Platform::iOSMac);
    #if (TARGET_OS_OSX && TARGET_CPU_ARM64)
        // allow iOS binaries in iOSApp
        if ( processPlatform == Platform::iOS ) {
            // can load Catalyst binaries into iOS process
            if ( this->builtForPlatform(Platform::iOSMac) )
                return true;
            iOSonMac = true;
        }
    #endif
        // macOS dylibs can be loaded into iOSMac processes
        if ( (iOSonMac) && this->builtForPlatform(Platform::macOS, true) )
            return true;
     
     
        return false;
    }
     
    bool MachOFile::isZippered() const
    {
        __block bool macOS = false;
        __block bool iOSMac = false;
        forEachSupportedPlatform(^(Platform platform, uint32_t minOS, uint32_t sdk) {
            if ( platform == Platform::macOS )
                macOS = true;
            else if ( platform == Platform::iOSMac )
                iOSMac = true;
        });
        return macOS && iOSMac;
    }
     
    bool MachOFile::inDyldCache() const {
        return (this->flags & MH_DYLIB_IN_CACHE);
    }
     
    Platform MachOFile::currentPlatform()
    {
    #if TARGET_OS_SIMULATOR
      #if TARGET_OS_WATCH
        return Platform::watchOS_simulator;
      #elif TARGET_OS_TV
        return Platform::tvOS_simulator;
      #elif TARGET_FEATURE_REALITYOS
        return Platform::realityOS_simulator;
      #else
        return Platform::iOS_simulator;
      #endif
    #elif TARGET_OS_BRIDGE
        return Platform::bridgeOS;
    #elif TARGET_OS_WATCH
        return Platform::watchOS;
    #elif TARGET_OS_TV
        return Platform::tvOS;
    #elif TARGET_OS_IOS
        return Platform::iOS;
    #elif TARGET_FEATURE_REALITYOS
        return Platform::realityOS;
    #elif TARGET_OS_OSX
        return Platform::macOS;
    #elif TARGET_OS_DRIVERKIT
        return Platform::driverKit;
    #else
        #error unknown platform
    #endif
    }
     
    Platform MachOFile::basePlatform(dyld3::Platform reqPlatform) {
        switch(reqPlatform) {
            case Platform::unknown:               return Platform::unknown;
            case Platform::macOS:                 return Platform::macOS;
            case Platform::iOS:                   return Platform::iOS;
            case Platform::tvOS:                  return Platform::tvOS;
            case Platform::watchOS:               return Platform::watchOS;
            case Platform::bridgeOS:              return Platform::bridgeOS;
            case Platform::iOSMac:                return Platform::iOS;
            case Platform::iOS_simulator:         return Platform::iOS;
            case Platform::tvOS_simulator:        return Platform::tvOS;
            case Platform::watchOS_simulator:     return Platform::watchOS;
            case Platform::driverKit:             return Platform::driverKit;
            default:                              return Platform::unknown;
        }
    }
     
     
    const char* MachOFile::currentArchName()
    {
    #if __ARM_ARCH_7K__
        return "armv7k";
    #elif __ARM_ARCH_7A__
        return "armv7";
    #elif __ARM_ARCH_7S__
        return "armv7s";
    #elif __arm64e__
        return "arm64e";
    #elif __arm64__
    #if __LP64__
        return "arm64";
    #else
        return "arm64_32";
    #endif
    #elif __x86_64__
        return isHaswell() ? "x86_64h" : "x86_64";
    #elif __i386__
        return "i386";
    #else
        #error unknown arch
    #endif
    }
     
    bool MachOFile::isSimulatorPlatform(Platform platform, Platform* basePlatform)
    {
        switch ( platform ) {
            case Platform::iOS_simulator:
                if ( basePlatform )
                    *basePlatform = Platform::iOS;
                return true;
            case Platform::watchOS_simulator:
                if ( basePlatform )
                    *basePlatform = Platform::watchOS;
                return true;
            case Platform::tvOS_simulator:
                if ( basePlatform )
                    *basePlatform = Platform::tvOS;
                return true;
           default:
                return false;
        }
    }
     
    bool MachOFile::isDyldManaged() const {
        switch ( this->filetype ) {
            case MH_BUNDLE:
            case MH_EXECUTE:
            case MH_DYLIB:
                return true;
            default:
                break;
        }
        return false;
    }
     
    bool MachOFile::isDylib() const
    {
        return (this->filetype == MH_DYLIB);
    }
     
    bool MachOFile::isBundle() const
    {
        return (this->filetype == MH_BUNDLE);
    }
     
    bool MachOFile::isMainExecutable() const
    {
        return (this->filetype == MH_EXECUTE);
    }
     
    bool MachOFile::isDynamicExecutable() const
    {
        if ( this->filetype != MH_EXECUTE )
            return false;
     
        // static executables do not have dyld load command
        return hasLoadCommand(LC_LOAD_DYLINKER);
    }
     
    bool MachOFile::isStaticExecutable() const
    {
        if ( this->filetype != MH_EXECUTE )
            return false;
     
        // static executables do not have dyld load command
        return !hasLoadCommand(LC_LOAD_DYLINKER);
    }
     
    bool MachOFile::isKextBundle() const
    {
        return (this->filetype == MH_KEXT_BUNDLE);
    }
     
    bool MachOFile::isFileSet() const
    {
        return (this->filetype == MH_FILESET);
    }
     
    bool MachOFile::isPIE() const
    {
        return (this->flags & MH_PIE);
    }
     
    bool MachOFile::isPreload() const
    {
        return (this->filetype == MH_PRELOAD);
    }
     
    const char* MachOFile::platformName(Platform reqPlatform)
    {
        for (const PlatformInfo& info : _s_platformInfos) {
            if ( info.platform == reqPlatform )
                return info.name;
        }
        return "unknown";
    }
     
    void MachOFile::forEachSupportedPlatform(void (^handler)(Platform platform, uint32_t minOS, uint32_t sdk)) const
    {
        Diagnostics diag;
        __block bool foundPlatform = false;
        forEachLoadCommand(diag, ^(const load_command* cmd, bool& stop) {
            const build_version_command* buildCmd = (build_version_command *)cmd;
            const version_min_command*   versCmd  = (version_min_command*)cmd;
            uint32_t                     sdk;
            switch ( cmd->cmd ) {
                case LC_BUILD_VERSION:
                    handler((Platform)(buildCmd->platform), buildCmd->minos, buildCmd->sdk);
                    foundPlatform = true;
                    break;
                case LC_VERSION_MIN_MACOSX:
                    sdk = versCmd->sdk;
                    // The original LC_VERSION_MIN_MACOSX did not have an sdk field, assume sdk is same as minOS for those old binaries
                    if ( sdk == 0 )
                        sdk = versCmd->version;
                    handler(Platform::macOS, versCmd->version, sdk);
                    foundPlatform = true;
                    break;
                case LC_VERSION_MIN_IPHONEOS:
                    if ( (this->cputype == CPU_TYPE_X86_64) || (this->cputype == CPU_TYPE_I386) )
                        handler(Platform::iOS_simulator, versCmd->version, versCmd->sdk); // old sim binary
                    else
                        handler(Platform::iOS, versCmd->version, versCmd->sdk);
                    foundPlatform = true;
                    break;
                case LC_VERSION_MIN_TVOS:
                    if ( this->cputype == CPU_TYPE_X86_64 )
                        handler(Platform::tvOS_simulator, versCmd->version, versCmd->sdk); // old sim binary
                    else
                        handler(Platform::tvOS, versCmd->version, versCmd->sdk);
                    foundPlatform = true;
                    break;
                case LC_VERSION_MIN_WATCHOS:
                    if ( (this->cputype == CPU_TYPE_X86_64) || (this->cputype == CPU_TYPE_I386) )
                        handler(Platform::watchOS_simulator, versCmd->version, versCmd->sdk); // old sim binary
                    else
                        handler(Platform::watchOS, versCmd->version, versCmd->sdk);
                    foundPlatform = true;
                    break;
            }
        });
        if ( !foundPlatform ) {
            // old binary with no explicit platform
    #if (BUILDING_DYLD || BUILDING_CLOSURE_UTIL) && TARGET_OS_OSX
            if ( this->cputype == CPU_TYPE_X86_64 )
                handler(Platform::macOS, 0x000A0500, 0x000A0500); // guess it is a macOS 10.5 binary
            // <rdar://problem/75343399>
            // The Go linker emits non-standard binaries without a platform and we have to live with it.
            if ( this->cputype == CPU_TYPE_ARM64 )
                handler(Platform::macOS, 0x000B0000, 0x000B0000); // guess it is a macOS 11.0 binary
    #endif
        }
        diag.assertNoError();   // any malformations in the file should have been caught by earlier validate() call
    }
     
     
    bool MachOFile::isMachO(Diagnostics& diag, uint64_t fileSize) const
    {
        if ( !hasMachOMagic() ) {
            // old PPC slices are not currently valid "mach-o" but should not cause an error
            if ( !hasMachOBigEndianMagic() )
                diag.error("file does not start with MH_MAGIC[_64]");
            return false;
        }
        if ( this->sizeofcmds + machHeaderSize() > fileSize ) {
            diag.error("load commands exceed length of first segment");
            return false;
        }
        forEachLoadCommand(diag, ^(const load_command* cmd, bool& stop) { });
        return diag.noError();
    }
     
    bool MachOFile::hasMachOMagic() const
    {
        return ( (this->magic == MH_MAGIC) || (this->magic == MH_MAGIC_64) );
    }
     
    bool MachOFile::hasMachOBigEndianMagic() const
    {
        return ( (this->magic == MH_CIGAM) || (this->magic == MH_CIGAM_64) );
    }
     
     
    void MachOFile::forEachLoadCommand(Diagnostics& diag, void (^callback)(const load_command* cmd, bool& stop)) const
    {
        bool stop = false;
        const load_command* startCmds = nullptr;
        if ( this->magic == MH_MAGIC_64 )
            startCmds = (load_command*)((char *)this + sizeof(mach_header_64));
        else if ( this->magic == MH_MAGIC )
            startCmds = (load_command*)((char *)this + sizeof(mach_header));
        else if ( hasMachOBigEndianMagic() )
            return;  // can't process big endian mach-o
        else {
            const uint32_t* h = (uint32_t*)this;
            diag.error("file does not start with MH_MAGIC[_64]: 0x%08X 0x%08X", h[0], h [1]);
            return;  // not a mach-o file
        }
        const load_command* const cmdsEnd = (load_command*)((char*)startCmds + this->sizeofcmds);
        const load_command* cmd = startCmds;
        for (uint32_t i = 0; i < this->ncmds; ++i) {
            const load_command* nextCmd = (load_command*)((char *)cmd + cmd->cmdsize);
            if ( cmd->cmdsize < 8 ) {
                diag.error("malformed load command #%d of %d at %p with mh=%p, size (0x%X) too small", i, this->ncmds, cmd, this, cmd->cmdsize);
                return;
            }
            // FIXME: add check the cmdsize is pointer aligned (might reveal bin compat issues)
            if ( (nextCmd > cmdsEnd) || (nextCmd < startCmds) ) {
                diag.error("malformed load command #%d of %d at %p with mh=%p, size (0x%X) is too large, load commands end at %p", i, this->ncmds, cmd, this, cmd->cmdsize, cmdsEnd);
                return;
            }
            callback(cmd, stop);
            if ( stop )
                return;
            cmd = nextCmd;
        }
    }
     
    void MachOFile::removeLoadCommand(Diagnostics& diag, void (^callback)(const load_command* cmd, bool& remove, bool& stop))
    {
        bool stop = false;
        const load_command* startCmds = nullptr;
        if ( this->magic == MH_MAGIC_64 )
            startCmds = (load_command*)((char *)this + sizeof(mach_header_64));
        else if ( this->magic == MH_MAGIC )
            startCmds = (load_command*)((char *)this + sizeof(mach_header));
        else if ( hasMachOBigEndianMagic() )
            return;  // can't process big endian mach-o
        else {
            const uint32_t* h = (uint32_t*)this;
            diag.error("file does not start with MH_MAGIC[_64]: 0x%08X 0x%08X", h[0], h [1]);
            return;  // not a mach-o file
        }
        const load_command* const cmdsEnd = (load_command*)((char*)startCmds + this->sizeofcmds);
        auto cmd = (load_command*)startCmds;
        const uint32_t origNcmds = this->ncmds;
        unsigned bytesRemaining = this->sizeofcmds;
        for (uint32_t i = 0; i < origNcmds; ++i) {
            bool remove = false;
            auto nextCmd = (load_command*)((char *)cmd + cmd->cmdsize);
            if ( cmd->cmdsize < 8 ) {
                diag.error("malformed load command #%d of %d at %p with mh=%p, size (0x%X) too small", i, this->ncmds, cmd, this, cmd->cmdsize);
                return;
            }
            if ( (nextCmd > cmdsEnd) || (nextCmd < startCmds) ) {
                diag.error("malformed load command #%d of %d at %p with mh=%p, size (0x%X) is too large, load commands end at %p", i, this->ncmds, cmd, this, cmd->cmdsize, cmdsEnd);
                return;
            }
            callback(cmd, remove, stop);
            if ( remove ) {
                this->sizeofcmds -= cmd->cmdsize;
                ::memmove((void*)cmd, (void*)nextCmd, bytesRemaining);
                this->ncmds--;
            } else {
                bytesRemaining -= cmd->cmdsize;
                cmd = nextCmd;
            }
            if ( stop )
                break;
        }
        if ( cmd )
         ::bzero(cmd, bytesRemaining);
    }
     
    const char* MachOFile::installName() const
    {
        const char*  name;
        uint32_t     compatVersion;
        uint32_t     currentVersion;
        if ( getDylibInstallName(&name, &compatVersion, &currentVersion) )
            return name;
        return nullptr;
    }
     
    bool MachOFile::getDylibInstallName(const char** installName, uint32_t* compatVersion, uint32_t* currentVersion) const
    {
        Diagnostics diag;
        __block bool found = false;
        forEachLoadCommand(diag, ^(const load_command* cmd, bool& stop) {
            if ( cmd->cmd == LC_ID_DYLIB ) {
                const dylib_command*  dylibCmd = (dylib_command*)cmd;
                *compatVersion  = dylibCmd->dylib.compatibility_version;
                *currentVersion = dylibCmd->dylib.current_version;
                *installName    = (char*)dylibCmd + dylibCmd->dylib.name.offset;
                found = true;
                stop = true;
            }
        });
        diag.assertNoError();   // any malformations in the file should have been caught by earlier validate() call
        return found;
    }
     
    bool MachOFile::getUuid(uuid_t uuid) const
    {
        Diagnostics diag;
        __block bool found = false;
        forEachLoadCommand(diag, ^(const load_command* cmd, bool& stop) {
            if ( cmd->cmd == LC_UUID ) {
                const uuid_command* uc = (const uuid_command*)cmd;
                memcpy(uuid, uc->uuid, sizeof(uuid_t));
                found = true;
                stop = true;
            }
        });
        diag.assertNoError();   // any malformations in the file should have been caught by earlier validate() call
        if ( !found )
            bzero(uuid, sizeof(uuid_t));
        return found;
    }
     
    void MachOFile::forEachDependentDylib(void (^callback)(const char* loadPath, bool isWeak, bool isReExport, bool isUpward, uint32_t compatVersion, uint32_t curVersion, bool& stop)) const
    {
        Diagnostics       diag;
        __block unsigned  count   = 0;
        __block bool      stopped = false;
        forEachLoadCommand(diag, ^(const load_command* cmd, bool& stop) {
             switch ( cmd->cmd ) {
                case LC_LOAD_DYLIB:
                case LC_LOAD_WEAK_DYLIB:
                case LC_REEXPORT_DYLIB:
                case LC_LOAD_UPWARD_DYLIB: {
                    const dylib_command* dylibCmd = (dylib_command*)cmd;
                    const char* loadPath = (char*)dylibCmd + dylibCmd->dylib.name.offset;
                    callback(loadPath, (cmd->cmd == LC_LOAD_WEAK_DYLIB), (cmd->cmd == LC_REEXPORT_DYLIB), (cmd->cmd == LC_LOAD_UPWARD_DYLIB),
                                        dylibCmd->dylib.compatibility_version, dylibCmd->dylib.current_version, stop);
                    ++count;
                    if ( stop )
                        stopped = true;
                }
                break;
            }
        });
        // everything must link with something
        if ( (count == 0) && !stopped ) {
            // The dylibs that make up libSystem can link with nothing
            // except for dylibs in libSystem.dylib which are ok to link with nothing (they are on bottom)
            if ( this->builtForPlatform(Platform::driverKit, true) ) {
                if ( !this->isDylib() || (strncmp(this->installName(), "/System/DriverKit/usr/lib/system/", 33) != 0) )
                    callback("/System/DriverKit/usr/lib/libSystem.B.dylib", false, false, false, 0x00010000, 0x00010000, stopped);
            }
            else {
                if ( !this->isDylib() || (strncmp(this->installName(), "/usr/lib/system/", 16) != 0) )
                    callback("/usr/lib/libSystem.B.dylib", false, false, false, 0x00010000, 0x00010000, stopped);
            }
        }
        diag.assertNoError();   // any malformations in the file should have been caught by earlier validate() call
    }
     
    void MachOFile::forDyldEnv(void (^callback)(const char* envVar, bool& stop)) const
    {
        Diagnostics diag;
        forEachLoadCommand(diag, ^(const load_command* cmd, bool& stop) {
             if ( cmd->cmd == LC_DYLD_ENVIRONMENT ) {
                const dylinker_command* envCmd = (dylinker_command*)cmd;
                const char* keyEqualsValue = (char*)envCmd + envCmd->name.offset;
                // only process variables that start with DYLD_ and end in _PATH
                if ( (strncmp(keyEqualsValue, "DYLD_", 5) == 0) ) {
                    const char* equals = strchr(keyEqualsValue, '=');
                    if ( equals != NULL ) {
                        if ( strncmp(&equals[-5], "_PATH", 5) == 0 ) {
                            callback(keyEqualsValue, stop);
                        }
                    }
                }
            }
        });
        diag.assertNoError();   // any malformations in the file should have been caught by earlier validate() call
    }
     
    bool MachOFile::enforceCompatVersion() const
    {
        __block bool result = true;
        forEachSupportedPlatform(^(Platform platform, uint32_t minOS, uint32_t sdk) {
            switch ( platform ) {
                case Platform::macOS:
                    if ( minOS >= 0x000A0E00 )  // macOS 10.14
                        result = false;
                    break;
                case Platform::iOS:
                case Platform::tvOS:
                case Platform::iOS_simulator:
                case Platform::tvOS_simulator:
                    if ( minOS >= 0x000C0000 )  // iOS 12.0
                        result = false;
                    break;
                case Platform::watchOS:
                case Platform::watchOS_simulator:
                    if ( minOS >= 0x00050000 )  // watchOS 5.0
                        result = false;
                    break;
                case Platform::bridgeOS:
                    if ( minOS >= 0x00030000 )  // bridgeOS 3.0
                        result = false;
                    break;
                case Platform::driverKit:
                case Platform::iOSMac:
                    result = false;
                    break;
                case Platform::unknown:
                    break;
            }
        });
        return result;
    }
     
    const thread_command* MachOFile::unixThreadLoadCommand() const {
        Diagnostics diag;
        __block const thread_command* command = nullptr;
        forEachLoadCommand(diag, ^(const load_command* cmd, bool& stop) {
            if ( cmd->cmd == LC_UNIXTHREAD ) {
                command = (const thread_command*)cmd;
                stop = true;
            }
        });
        return command;
    }
     
     
    uint32_t MachOFile::entryAddrRegisterIndexForThreadCmd() const
    {
        switch ( this->cputype ) {
            case CPU_TYPE_I386:
                return 10; // i386_thread_state_t.eip
            case CPU_TYPE_X86_64:
                return 16; // x86_thread_state64_t.rip
            case CPU_TYPE_ARM:
                return 15; // arm_thread_state_t.pc
            case CPU_TYPE_ARM64:
                return 32; // arm_thread_state64_t.__pc
        }
        return ~0U;
    }
     
     
    uint64_t MachOFile::entryAddrFromThreadCmd(const thread_command* cmd) const
    {
        assert(cmd->cmd == LC_UNIXTHREAD);
        const uint32_t* regs32 = (uint32_t*)(((char*)cmd) + 16);
        const uint64_t* regs64 = (uint64_t*)(((char*)cmd) + 16);
     
        uint32_t index = entryAddrRegisterIndexForThreadCmd();
        if (index == ~0U)
            return 0;
     
        return is64() ? regs64[index] : regs32[index];
    }
     
     
    void MachOFile::forEachSegment(void (^callback)(const SegmentInfo& info, bool& stop)) const
    {
        Diagnostics diag;
        const bool  intel32  = (this->cputype == CPU_TYPE_I386);
        __block uint32_t segIndex = 0;
        forEachLoadCommand(diag, ^(const load_command* cmd, bool& stop) {
            if ( cmd->cmd == LC_SEGMENT_64 ) {
                const segment_command_64* segCmd = (segment_command_64*)cmd;
                uint64_t sizeOfSections = segCmd->vmsize;
                uint8_t p2align = 0;
                const section_64* const sectionsStart = (section_64*)((char*)segCmd + sizeof(struct segment_command_64));
                const section_64* const sectionsEnd   = &sectionsStart[segCmd->nsects];
                for (const section_64* sect=sectionsStart; sect < sectionsEnd; ++sect) {
                    sizeOfSections = sect->addr + sect->size - segCmd->vmaddr;
                    if ( sect->align > p2align )
                        p2align = sect->align;
                }
                SegmentInfo info;
                info.fileOffset        = segCmd->fileoff;
                info.fileSize          = segCmd->filesize;
                info.vmAddr            = segCmd->vmaddr;
                info.vmSize            = segCmd->vmsize;
                info.sizeOfSections    = sizeOfSections;
                info.segName           = segCmd->segname;
                info.loadCommandOffset = (uint32_t)((uint8_t*)segCmd - (uint8_t*)this);
                info.protections       = segCmd->initprot;
                info.textRelocs        = false;
                info.readOnlyData      = ((segCmd->flags & SG_READ_ONLY) != 0);
                info.isProtected       = (segCmd->flags & SG_PROTECTED_VERSION_1) ? 1 : 0;
                info.hasZeroFill       = (segCmd->initprot == 3) && (segCmd->filesize < segCmd->vmsize);
                info.p2align           = p2align;
                info.segIndex          = segIndex;
                callback(info, stop);
                ++segIndex;
            }
            else if ( cmd->cmd == LC_SEGMENT ) {
                const segment_command* segCmd = (segment_command*)cmd;
                uint64_t sizeOfSections = segCmd->vmsize;
                uint8_t p2align = 0;
                bool  hasTextRelocs = false;
                const section* const sectionsStart = (section*)((char*)segCmd + sizeof(struct segment_command));
                const section* const sectionsEnd   = &sectionsStart[segCmd->nsects];
                for (const section* sect=sectionsStart; sect < sectionsEnd; ++sect) {
                    sizeOfSections = sect->addr + sect->size - segCmd->vmaddr;
                    if ( sect->align > p2align )
                        p2align = sect->align;
                    if ( sect->flags & (S_ATTR_EXT_RELOC|S_ATTR_LOC_RELOC) )
                        hasTextRelocs = true;
               }
                SegmentInfo info;
                info.fileOffset        = segCmd->fileoff;
                info.fileSize          = segCmd->filesize;
                info.vmAddr            = segCmd->vmaddr;
                info.vmSize            = segCmd->vmsize;
                info.sizeOfSections    = sizeOfSections;
                info.segName           = segCmd->segname;
                info.loadCommandOffset = (uint32_t)((uint8_t*)segCmd - (uint8_t*)this);
                info.protections       = segCmd->initprot;
                info.textRelocs        = intel32 && !info.writable() && hasTextRelocs;
                info.readOnlyData      = ((segCmd->flags & SG_READ_ONLY) != 0);
                info.isProtected       = (segCmd->flags & SG_PROTECTED_VERSION_1) ? 1 : 0;
                info.hasZeroFill       = (segCmd->initprot == 3) && (segCmd->filesize < segCmd->vmsize);
                info.p2align           = p2align;
                info.segIndex          = segIndex;
                callback(info, stop);
                ++segIndex;
            }
        });
        diag.assertNoError();   // any malformations in the file should have been caught by earlier validate() call
    }
     
    uint64_t MachOFile::preferredLoadAddress() const
    {
        __block uint64_t textVmAddr = 0;
        forEachSegment(^(const SegmentInfo& info, bool& stop) {
            if ( strcmp(info.segName, "__TEXT") == 0 ) {
                textVmAddr = info.vmAddr;
                stop = true;
            }
        });
        return textVmAddr;
    }
     
    void MachOFile::forEachSection(void (^callback)(const SectionInfo& sectInfo, bool malformedSectionRange, bool& stop)) const
    {
        Diagnostics diag;
        BLOCK_ACCCESSIBLE_ARRAY(char, sectNameCopy, 20);  // read as:  char sectNameCopy[20];
        const bool intel32 = (this->cputype == CPU_TYPE_I386);
        __block uint32_t segIndex = 0;
        forEachLoadCommand(diag, ^(const load_command* cmd, bool& stop) {
            SectionInfo sectInfo;
            if ( cmd->cmd == LC_SEGMENT_64 ) {
                const segment_command_64* segCmd = (segment_command_64*)cmd;
                uint64_t sizeOfSections = segCmd->vmsize;
                uint8_t p2align = 0;
                const section_64* const sectionsStart = (section_64*)((char*)segCmd + sizeof(struct segment_command_64));
                const section_64* const sectionsEnd   = &sectionsStart[segCmd->nsects];
                for (const section_64* sect=sectionsStart; sect < sectionsEnd; ++sect) {
                    sizeOfSections = sect->addr + sect->size - segCmd->vmaddr;
                    if ( sect->align > p2align )
                        p2align = sect->align;
                }
                sectInfo.segInfo.fileOffset        = segCmd->fileoff;
                sectInfo.segInfo.fileSize          = segCmd->filesize;
                sectInfo.segInfo.vmAddr            = segCmd->vmaddr;
                sectInfo.segInfo.vmSize            = segCmd->vmsize;
                sectInfo.segInfo.sizeOfSections    = sizeOfSections;
                sectInfo.segInfo.segName           = segCmd->segname;
                sectInfo.segInfo.loadCommandOffset = (uint32_t)((uint8_t*)segCmd - (uint8_t*)this);
                sectInfo.segInfo.protections       = segCmd->initprot;
                sectInfo.segInfo.textRelocs        = false;
                sectInfo.segInfo.readOnlyData      = ((segCmd->flags & SG_READ_ONLY) != 0);
                sectInfo.segInfo.isProtected       = (segCmd->flags & SG_PROTECTED_VERSION_1) ? 1 : 0;
                sectInfo.segInfo.p2align           = p2align;
                sectInfo.segInfo.segIndex          = segIndex;
                for (const section_64* sect=sectionsStart; !stop && (sect < sectionsEnd); ++sect) {
                    const char* sectName = sect->sectname;
                    if ( sectName[15] != '\0' ) {
                        strlcpy(sectNameCopy, sectName, 17);
                        sectName = sectNameCopy;
                    }
                    bool malformedSectionRange = (sect->addr < segCmd->vmaddr) || greaterThanAddOrOverflow(sect->addr, sect->size, segCmd->vmaddr + segCmd->filesize);
                    sectInfo.sectName       = sectName;
                    sectInfo.sectFileOffset = sect->offset;
                    sectInfo.sectFlags      = sect->flags;
                    sectInfo.sectAddr       = sect->addr;
                    sectInfo.sectSize       = sect->size;
                    sectInfo.sectAlignP2    = sect->align;
                    sectInfo.reserved1      = sect->reserved1;
                    sectInfo.reserved2      = sect->reserved2;
                    callback(sectInfo, malformedSectionRange, stop);
                }
                ++segIndex;
            }
            else if ( cmd->cmd == LC_SEGMENT ) {
                const segment_command* segCmd = (segment_command*)cmd;
                uint64_t sizeOfSections = segCmd->vmsize;
                uint8_t p2align = 0;
                bool  hasTextRelocs = false;
                const section* const sectionsStart = (section*)((char*)segCmd + sizeof(struct segment_command));
                const section* const sectionsEnd   = &sectionsStart[segCmd->nsects];
                for (const section* sect=sectionsStart; sect < sectionsEnd; ++sect) {
                    sizeOfSections = sect->addr + sect->size - segCmd->vmaddr;
                    if ( sect->align > p2align )
                        p2align = sect->align;
                    if ( sect->flags & (S_ATTR_EXT_RELOC|S_ATTR_LOC_RELOC) )
                        hasTextRelocs = true;
                }
                sectInfo.segInfo.fileOffset        = segCmd->fileoff;
                sectInfo.segInfo.fileSize          = segCmd->filesize;
                sectInfo.segInfo.vmAddr            = segCmd->vmaddr;
                sectInfo.segInfo.vmSize            = segCmd->vmsize;
                sectInfo.segInfo.sizeOfSections    = sizeOfSections;
                sectInfo.segInfo.segName           = segCmd->segname;
                sectInfo.segInfo.loadCommandOffset = (uint32_t)((uint8_t*)segCmd - (uint8_t*)this);
                sectInfo.segInfo.protections       = segCmd->initprot;
                sectInfo.segInfo.textRelocs        = intel32 && !sectInfo.segInfo.writable() && hasTextRelocs;
                sectInfo.segInfo.readOnlyData      = ((segCmd->flags & SG_READ_ONLY) != 0);
                sectInfo.segInfo.isProtected       = (segCmd->flags & SG_PROTECTED_VERSION_1) ? 1 : 0;
                sectInfo.segInfo.p2align           = p2align;
                sectInfo.segInfo.segIndex          = segIndex;
                for (const section* sect=sectionsStart; !stop && (sect < sectionsEnd); ++sect) {
                    const char* sectName = sect->sectname;
                    if ( sectName[15] != '\0' ) {
                        strlcpy(sectNameCopy, sectName, 17);
                        sectName = sectNameCopy;
                    }
                    bool malformedSectionRange = (sect->addr < segCmd->vmaddr) || greaterThanAddOrOverflow(sect->addr, sect->size, segCmd->vmaddr + segCmd->filesize);
                    sectInfo.sectName       = sectName;
                    sectInfo.sectFileOffset = sect->offset;
                    sectInfo.sectFlags      = sect->flags;
                    sectInfo.sectAddr       = sect->addr;
                    sectInfo.sectSize       = sect->size;
                    sectInfo.sectAlignP2    = sect->align;
                    sectInfo.reserved1      = sect->reserved1;
                    sectInfo.reserved2      = sect->reserved2;
                    callback(sectInfo, malformedSectionRange, stop);
                }
                ++segIndex;
            }
        });
        diag.assertNoError();   // any malformations in the file should have been caught by earlier validate() call
    }
     
    void MachOFile::forEachInterposingSection(Diagnostics& diag, void (^handler)(uint64_t vmOffset, uint64_t vmSize, bool& stop)) const
    {
        const unsigned ptrSize   = pointerSize();
        const unsigned entrySize = 2 * ptrSize;
        forEachSection(^(const MachOFile::SectionInfo& info, bool malformedSectionRange, bool &stop) {
            if ( ((info.sectFlags & SECTION_TYPE) == S_INTERPOSING) || ((strcmp(info.sectName, "__interpose") == 0) && ((strncmp(info.segInfo.segName, "__DATA", 6) == 0) || strncmp(info.segInfo.segName, "__AUTH", 6) == 0)) ) {
                if ( info.sectSize % entrySize != 0 ) {
                    diag.error("interposing section %s/%s has bad size", info.segInfo.segName, info.sectName);
                    stop = true;
                    return;
                }
                if ( malformedSectionRange ) {
                    diag.error("interposing section %s/%s extends beyond the end of the segment", info.segInfo.segName, info.sectName);
                    stop = true;
                    return;
                }
                if ( (info.sectAddr % ptrSize) != 0 ) {
                    diag.error("interposing section %s/%s is not pointer aligned", info.segInfo.segName, info.sectName);
                    stop = true;
                    return;
                }
                handler(info.sectAddr - preferredLoadAddress(), info.sectSize, stop);
            }
        });
    }
     
    bool MachOFile::isRestricted() const
    {
        __block bool result = false;
        forEachSection(^(const MachOFile::SectionInfo& info, bool malformedSectionRange, bool &stop) {
            if ( (strcmp(info.segInfo.segName, "__RESTRICT") == 0) && (strcmp(info.sectName, "__restrict") == 0) ) {
                result = true;
                stop = true;
            }
        });
        return result;
    }
     
    bool MachOFile::hasWeakDefs() const
    {
        return (this->flags & MH_WEAK_DEFINES);
    }
     
    bool MachOFile::usesWeakDefs() const
    {
        return (this->flags & MH_BINDS_TO_WEAK);
    }
     
    bool MachOFile::hasThreadLocalVariables() const
    {
        return (this->flags & MH_HAS_TLV_DESCRIPTORS);
    }
     
    static bool endsWith(const char* str, const char* suffix)
    {
        size_t strLen    = strlen(str);
        size_t suffixLen = strlen(suffix);
        if ( strLen < suffixLen )
            return false;
        return (strcmp(&str[strLen-suffixLen], suffix) == 0);
    }
     
    bool MachOFile::isSharedCacheEligiblePath(const char* dylibName) {
        return (   (strncmp(dylibName, "/usr/lib/", 9) == 0)
                || (strncmp(dylibName, "/System/Library/", 16) == 0)
                || (strncmp(dylibName, "/System/iOSSupport/usr/lib/", 27) == 0)
                || (strncmp(dylibName, "/System/iOSSupport/System/Library/", 34) == 0)
                || (strncmp(dylibName, "/Library/Apple/usr/lib/", 23) == 0)
                || (strncmp(dylibName, "/Library/Apple/System/Library/", 30) == 0)
                || (strncmp(dylibName, "/System/DriverKit/", 18) == 0));
    }
     
    static bool startsWith(const char* buffer, const char* valueToFind) {
        return strncmp(buffer, valueToFind, strlen(valueToFind)) == 0;
    }
     
    static bool platformExcludesSharedCache_macOS(const char* installName) {
        // Note: This function basically matches dontCache() from update dyld shared cache
     
        if ( startsWith(installName, "/usr/lib/system/introspection/") )
            return true;
        if ( startsWith(installName, "/System/Library/QuickTime/") )
            return true;
        if ( startsWith(installName, "/System/Library/Tcl/") )
            return true;
        if ( startsWith(installName, "/System/Library/Perl/") )
            return true;
        if ( startsWith(installName, "/System/Library/MonitorPanels/") )
            return true;
        if ( startsWith(installName, "/System/Library/Accessibility/") )
            return true;
        if ( startsWith(installName, "/usr/local/") )
            return true;
        if ( startsWith(installName, "/usr/lib/pam/") )
            return true;
        // We no longer support ROSP, so skip all paths which start with the special prefix
        if ( startsWith(installName, "/System/Library/Templates/Data/") )
            return true;
     
        // anything inside a .app bundle is specific to app, so should not be in shared cache
        if ( strstr(installName, ".app/") != NULL )
            return true;
     
        return false;
    }
     
    static bool platformExcludesSharedCache_iOS(const char* installName) {
        if ( strcmp(installName, "/System/Library/Caches/com.apple.xpc/sdk.dylib") == 0 )
            return true;
        if ( strcmp(installName, "/System/Library/Caches/com.apple.xpcd/xpcd_cache.dylib") == 0 )
            return true;
        return false;
    }
     
    // Returns true if the current platform requires that this install name be excluded from the shared cache
    // Note that this overrides any exclusion from anywhere else.
    static bool platformExcludesSharedCache(Platform platform, const char* installName) {
        if ( MachOFile::isSimulatorPlatform(platform) )
            return false;
        if ( (platform == dyld3::Platform::macOS) || (platform == dyld3::Platform::iOSMac) )
            return platformExcludesSharedCache_macOS(installName);
        // Everything else is based on iOS so just use that value
        return platformExcludesSharedCache_iOS(installName);
    }
     
     
    bool MachOFile::canBePlacedInDyldCache(const char* path, void (^failureReason)(const char*)) const
    {
     
        if ( !isSharedCacheEligiblePath(path) ) {
            // Dont spam the user with an error about paths when we know these are never eligible.
            return false;
        }
     
        // only dylibs can go in cache
        if ( this->filetype != MH_DYLIB ) {
            failureReason("Not MH_DYLIB");
            return false; // cannot continue, installName() will assert() if not a dylib
        }
     
     
        const char* dylibName = installName();
        if ( dylibName[0] != '/' ) {
            failureReason("install name not an absolute path");
            // Don't continue as we don't want to spam the log with errors we don't need.
            return false;
        }
        else if ( strcmp(dylibName, path) != 0 ) {
            failureReason("install path does not match install name");
            return false;
        }
        else if ( strstr(dylibName, "//") != 0 ) {
            failureReason("install name should not include //");
            return false;
        }
        else if ( strstr(dylibName, "./") != 0 ) {
            failureReason("install name should not include ./");
            return false;
        }
     
        __block bool platformExcludedFile = false;
        forEachSupportedPlatform(^(Platform platform, uint32_t minOS, uint32_t sdk) {
            if ( platformExcludedFile )
                return;
            if ( platformExcludesSharedCache(platform, dylibName) ) {
                platformExcludedFile = true;
                return;
            }
        });
        if ( platformExcludedFile ) {
            failureReason("install name is not shared cache eligible on platform");
            return false;
        }
     
        bool retval = true;
     
        // flat namespace files cannot go in cache
        if ( (this->flags & MH_TWOLEVEL) == 0 ) {
            retval = false;
            failureReason("Not built with two level namespaces");
        }
     
        // don't put debug variants into dyld cache
        if ( endsWith(path, "_profile.dylib") || endsWith(path, "_debug.dylib") || endsWith(path, "_profile") || endsWith(path, "_debug") || endsWith(path, "/CoreADI") ) {
            retval = false;
            failureReason("Variant image");
        }
     
        // dylib must have extra info for moving DATA and TEXT segments apart
        __block bool hasExtraInfo = false;
        __block bool hasDyldInfo = false;
        __block bool hasExportTrie = false;
        Diagnostics diag;
        forEachLoadCommand(diag, ^(const load_command* cmd, bool& stop) {
            if ( cmd->cmd == LC_SEGMENT_SPLIT_INFO )
                hasExtraInfo = true;
            if ( cmd->cmd == LC_DYLD_INFO_ONLY )
                hasDyldInfo = true;
            if ( cmd->cmd == LC_DYLD_EXPORTS_TRIE )
                hasExportTrie = true;
        });
        if ( !hasExtraInfo ) {
            retval = false;
            failureReason("Missing split seg info");
        }
        if ( !hasDyldInfo && !hasExportTrie ) {
            retval = false;
            failureReason("Old binary, missing dyld info or export trie");
        }
     
        // dylib can only depend on other dylibs in the shared cache
        __block bool allDepPathsAreGood = true;
        forEachDependentDylib(^(const char* loadPath, bool isWeak, bool isReExport, bool isUpward, uint32_t compatVersion, uint32_t curVersion, bool& stop) {
            // Skip weak links.  They are allowed to be missing
            if ( isWeak )
                return;
            if ( !isSharedCacheEligiblePath(loadPath) ) {
                allDepPathsAreGood = false;
                stop = true;
            }
        });
        if ( !allDepPathsAreGood ) {
            retval = false;
            failureReason("Depends on dylibs ineligable for dyld cache");
        }
     
        // dylibs with interposing info cannot be in cache
        if ( hasInterposingTuples() ) {
            retval = false;
            failureReason("Has interposing tuples");
        }
     
        // Temporarily kick out swift binaries out of dyld cache on watchOS simulators as they have missing split seg
        if ( (this->cputype == CPU_TYPE_I386) && builtForPlatform(Platform::watchOS_simulator) ) {
            if ( strncmp(dylibName, "/usr/lib/swift/", 15) == 0 ) {
                retval = false;
                failureReason("i386 swift binary");
            }
        }
     
        return retval;
    }
     
    #if BUILDING_APP_CACHE_UTIL
    bool MachOFile::canBePlacedInKernelCollection(const char* path, void (^failureReason)(const char*)) const
    {
        // only dylibs and the kernel itself can go in cache
        if ( this->filetype == MH_EXECUTE ) {
            // xnu
        } else if ( this->isKextBundle() ) {
            // kext's
        } else {
            failureReason("Not MH_KEXT_BUNDLE");
            return false;
        }
     
        if ( this->filetype == MH_EXECUTE ) {
            // xnu
     
            // two-level namespace binaries cannot go in cache
            if ( (this->flags & MH_TWOLEVEL) != 0 ) {
                failureReason("Built with two level namespaces");
                return false;
            }
     
            // xnu kernel cannot have a page zero
            __block bool foundPageZero = false;
            forEachSegment(^(const SegmentInfo &segmentInfo, bool &stop) {
                if ( strcmp(segmentInfo.segName, "__PAGEZERO") == 0 ) {
                    foundPageZero = true;
                    stop = true;
                }
            });
            if (foundPageZero) {
                failureReason("Has __PAGEZERO");
                return false;
            }
     
            // xnu must have an LC_UNIXTHREAD to point to the entry point
            __block bool foundMainLC = false;
            __block bool foundUnixThreadLC = false;
            Diagnostics diag;
            forEachLoadCommand(diag, ^(const load_command* cmd, bool& stop) {
                if ( cmd->cmd == LC_MAIN ) {
                    foundMainLC = true;
                    stop = true;
                }
                else if ( cmd->cmd == LC_UNIXTHREAD ) {
                    foundUnixThreadLC = true;
                }
            });
            if (foundMainLC) {
                failureReason("Found LC_MAIN");
                return false;
            }
            if (!foundUnixThreadLC) {
                failureReason("Expected LC_UNIXTHREAD");
                return false;
            }
     
            if (diag.hasError()) {
                failureReason("Error parsing load commands");
                return false;
            }
     
            // The kernel should be a static executable, not a dynamic one
            if ( !isStaticExecutable() ) {
                failureReason("Expected static executable");
                return false;
            }
     
            // The kernel must be built with -pie
            if ( !isPIE() ) {
                failureReason("Expected pie");
                return false;
            }
        }
     
        if ( isArch("arm64e") && isKextBundle() && !hasChainedFixups() ) {
            failureReason("Missing fixup information");
            return false;
        }
     
        // dylibs with interposing info cannot be in cache
        if ( hasInterposingTuples() ) {
            failureReason("Has interposing tuples");
            return false;
        }
     
        // Only x86_64 is allowed to have RWX segments
        if ( !isArch("x86_64") && !isArch("x86_64h") ) {
            __block bool foundBadSegment = false;
            forEachSegment(^(const SegmentInfo &info, bool &stop) {
                if ( (info.protections & (VM_PROT_WRITE | VM_PROT_EXECUTE)) == (VM_PROT_WRITE | VM_PROT_EXECUTE) ) {
                    failureReason("Segments are not allowed to be both writable and executable");
                    foundBadSegment = true;
                    stop = true;
                }
            });
            if ( foundBadSegment )
                return false;
        }
     
        return true;
    }
    #endif
     
    static bool platformExcludesPrebuiltClosure_macOS(const char* path) {
        // We no longer support ROSP, so skip all paths which start with the special prefix
        if ( startsWith(path, "/System/Library/Templates/Data/") )
            return true;
     
        // anything inside a .app bundle is specific to app, so should not get a prebuilt closure
        if ( strstr(path, ".app/") != NULL )
            return true;
     
        return false;
    }
     
    static bool platformExcludesPrebuiltClosure_iOS(const char* path) {
        if ( strcmp(path, "/System/Library/Caches/com.apple.xpc/sdk.dylib") == 0 )
            return true;
        if ( strcmp(path, "/System/Library/Caches/com.apple.xpcd/xpcd_cache.dylib") == 0 )
            return true;
        return false;
    }
     
    // Returns true if the current platform requires that this install name be excluded from the shared cache
    // Note that this overrides any exclusion from anywhere else.
    static bool platformExcludesPrebuiltClosure(Platform platform, const char* path) {
        if ( MachOFile::isSimulatorPlatform(platform) )
            return false;
        if ( (platform == dyld3::Platform::macOS) || (platform == dyld3::Platform::iOSMac) )
            return platformExcludesPrebuiltClosure_macOS(path);
        // Everything else is based on iOS so just use that value
        return platformExcludesPrebuiltClosure_iOS(path);
    }
     
    bool MachOFile::canHavePrecomputedDlopenClosure(const char* path, void (^failureReason)(const char*)) const
    {
        __block bool retval = true;
     
        // only dylibs can go in cache
        if ( (this->filetype != MH_DYLIB) && (this->filetype != MH_BUNDLE) ) {
            retval = false;
            failureReason("not MH_DYLIB or MH_BUNDLE");
        }
     
        // flat namespace files cannot go in cache
        if ( (this->flags & MH_TWOLEVEL) == 0 ) {
            retval = false;
            failureReason("not built with two level namespaces");
        }
     
        // can only depend on other dylibs with absolute paths
        __block bool allDepPathsAreGood = true;
        forEachDependentDylib(^(const char* loadPath, bool isWeak, bool isReExport, bool isUpward, uint32_t compatVersion, uint32_t curVersion, bool& stop) {
            if ( loadPath[0] != '/' ) {
                allDepPathsAreGood = false;
                stop = true;
            }
        });
        if ( !allDepPathsAreGood ) {
            retval = false;
            failureReason("depends on dylibs that are not absolute paths");
        }
     
        __block bool platformExcludedFile = false;
        forEachSupportedPlatform(^(Platform platform, uint32_t minOS, uint32_t sdk) {
            if ( platformExcludedFile )
                return;
            if ( platformExcludesPrebuiltClosure(platform, path) ) {
                platformExcludedFile = true;
                return;
            }
        });
        if ( platformExcludedFile ) {
            failureReason("file cannot get a prebuilt closure on this platform");
            return false;
        }
     
        // dylibs with interposing info cannot have dlopen closure pre-computed
        if ( hasInterposingTuples() ) {
            retval = false;
            failureReason("has interposing tuples");
        }
     
        // special system dylib overrides cannot have closure pre-computed
        if ( strncmp(path, "/usr/lib/system/introspection/", 30) == 0 ) {
            retval = false;
            failureReason("override of OS dylib");
        }
     
        return retval;
    }
     
    bool MachOFile::hasInterposingTuples() const
    {
        __block bool hasInterposing = false;
        Diagnostics diag;
        forEachInterposingSection(diag, ^(uint64_t vmOffset, uint64_t vmSize, bool &stop) {
            hasInterposing = true;
            stop = true;
        });
        return hasInterposing;
    }
     
    bool MachOFile::isFairPlayEncrypted(uint32_t& textOffset, uint32_t& size) const
    {
        if ( const encryption_info_command* encCmd = findFairPlayEncryptionLoadCommand() ) {
           if ( encCmd->cryptid == 1 ) {
                // Note: cryptid is 0 in just-built apps.  The AppStore sets cryptid to 1
                textOffset = encCmd->cryptoff;
                size       = encCmd->cryptsize;
                return true;
            }
        }
        textOffset = 0;
        size = 0;
        return false;
    }
     
    bool MachOFile::canBeFairPlayEncrypted() const
    {
        return (findFairPlayEncryptionLoadCommand() != nullptr);
    }
     
    const encryption_info_command* MachOFile::findFairPlayEncryptionLoadCommand() const
    {
        __block const encryption_info_command* result = nullptr;
        Diagnostics diag;
        forEachLoadCommand(diag, ^(const load_command* cmd, bool& stop) {
             if ( (cmd->cmd == LC_ENCRYPTION_INFO) || (cmd->cmd == LC_ENCRYPTION_INFO_64) ) {
                result = (encryption_info_command*)cmd;
                stop = true;
            }
        });
        if ( diag.noError() )
            return result;
        else
            return nullptr;
    }
     
     
    bool MachOFile::hasLoadCommand(uint32_t cmdNum) const
    {
        __block bool hasLC = false;
        Diagnostics diag;
        forEachLoadCommand(diag, ^(const load_command* cmd, bool& stop) {
            if ( cmd->cmd == cmdNum ) {
                hasLC = true;
                stop = true;
            }
        });
        return hasLC;
    }
     
    bool MachOFile::allowsAlternatePlatform() const
    {
        __block bool result = false;
        forEachSection(^(const SectionInfo& info, bool malformedSectionRange, bool& stop) {
            if ( (strcmp(info.sectName, "__allow_alt_plat") == 0) && (strncmp(info.segInfo.segName, "__DATA", 6) == 0) ) {
                result = true;
                stop = true;
            }
        });
        return result;
    }
     
    bool MachOFile::hasChainedFixups() const
    {
    #if SUPPORT_ARCH_arm64e
        // arm64e always uses chained fixups
        if ( (this->cputype == CPU_TYPE_ARM64) && (this->maskedCpuSubtype() == CPU_SUBTYPE_ARM64E) ) {
            // Not all binaries have fixups at all so check for the load commands
            return hasLoadCommand(LC_DYLD_INFO_ONLY) || hasLoadCommand(LC_DYLD_CHAINED_FIXUPS);
        }
    #endif
        return hasLoadCommand(LC_DYLD_CHAINED_FIXUPS);
    }
     
    bool MachOFile::hasChainedFixupsLoadCommand() const
    {
        return hasLoadCommand(LC_DYLD_CHAINED_FIXUPS);
    }
     
    bool MachOFile::hasOpcodeFixups() const
    {
        return hasLoadCommand(LC_DYLD_INFO_ONLY) || hasLoadCommand(LC_DYLD_INFO) ;
    }
     
    uint64_t MachOFile::read_uleb128(Diagnostics& diag, const uint8_t*& p, const uint8_t* end)
    {
        uint64_t result = 0;
        int         bit = 0;
        do {
            if ( p == end ) {
                diag.error("malformed uleb128");
                break;
            }
            uint64_t slice = *p & 0x7f;
     
            if ( bit > 63 ) {
                diag.error("uleb128 too big for uint64");
                break;
            }
            else {
                result |= (slice << bit);
                bit += 7;
            }
        }
        while (*p++ & 0x80);
        return result;
    }
     
     
    int64_t MachOFile::read_sleb128(Diagnostics& diag, const uint8_t*& p, const uint8_t* end)
    {
        int64_t  result = 0;
        int      bit = 0;
        uint8_t  byte = 0;
        do {
            if ( p == end ) {
                diag.error("malformed sleb128");
                break;
            }
            byte = *p++;
            result |= (((int64_t)(byte & 0x7f)) << bit);
            bit += 7;
        } while (byte & 0x80);
        // sign extend negative numbers
        if ( ((byte & 0x40) != 0) && (bit < 64) )
            result |= (~0ULL) << bit;
        return result;
    }
     
     
    const MachOFile* MachOFile::compatibleSlice(Diagnostics& diag, const void* fileContent, size_t contentSize, const char* path, Platform platform, bool isOSBinary, const GradedArchs& archs)
    {
        const MachOFile* mf = nullptr;
        if ( const dyld3::FatFile* ff = dyld3::FatFile::isFatFile(fileContent) ) {
            uint64_t  sliceOffset;
            uint64_t  sliceLen;
            bool      missingSlice;
            if ( ff->isFatFileWithSlice(diag, contentSize, archs, isOSBinary, sliceOffset, sliceLen, missingSlice) ) {
                mf = (MachOFile*)((long)fileContent + sliceOffset);
            }
            else {
                char strBuf[256];
                diag.error("fat file, but missing compatible architecture (have '%s', need '%s')", ff->archNames(strBuf), archs.name());
                return nullptr;
            }
        }
        else {
            mf = (MachOFile*)fileContent;
        }
     
        if ( !mf->hasMachOMagic() || !mf->isMachO(diag, contentSize) ) {
            diag.error("not a mach-o file");
            return nullptr;
        }
     
        if ( archs.grade(mf->cputype, mf->cpusubtype, isOSBinary) == 0 ) {
            diag.error("mach-o file, but is an incompatible architecture (have '%s', need '%s')", mf->archName(), archs.name());
            return nullptr;
        }
     
        if ( !mf->loadableIntoProcess(platform, path) ) {
            __block Platform havePlatform = Platform::unknown;
            mf->forEachSupportedPlatform(^(Platform aPlat, uint32_t minOS, uint32_t sdk) {
                havePlatform = aPlat;
            });
            diag.error("mach-o file (%s), but incompatible platform (have '%s', need '%s')", path, MachOFile::platformName(havePlatform), MachOFile::platformName(platform));
            return nullptr;
        }
     
        return mf;
    }
     
     
    } // namespace dyld3
    }

    Les références ont été largement partagées par les développeurs Rens Verhoeven et Steve Troughton-Smith sur Twitter. Verhoeven a tweeté :

    Nom : un.png
Affichages : 1184
Taille : 34,5 Ko

    Le tweet était accompagné d'une capture d'écran des journaux qui incluait "com.apple.platform.realityos" ainsi qu'une référence similaire pour une plateforme existante, "com.apple.platform.watchos".

    Et tout en citant sur Twitter une légende de la découverte du référentiel GitHub par Nicolás Álvarez, Troughton-Smith a tweeté ce qui suit :

    Nom : deux.png
Affichages : 1109
Taille : 112,7 Ko

    Les captures d'écran accompagnant ce tweet incluaient des commentaires de code tels que "// autoriser les exécutables iOS à utiliser les dylibs de realityOS" et "// autoriser les exécutables iOS_Sim à utiliser les dylibs de realityOS_Sim".

    Le fait qu'Apple travaille sur une plateforme de réalité mixte n'est cependant pas nouveau. Basée sur des offres d'emploi sur le site Carrières d'Apple, de nombreux rapports fiables et d'autres sources, la plateforme de réalité mixte d'Apple est en développement depuis des années, avec une équipe de milliers de personnes.

    La plateforme de réalité mixte a cependant fait face à plusieurs retards. Par exemple, Bloomberg a rapporté en 2017 que le premier casque d'Apple visait une date de sortie en 2019. Ce rapport a appelé le système d'exploitation personnalisé d'Apple pour les appareils de réalité mixte "rOS".

    Des analystes comme Ming-chi Kuo et des journalistes comme Mark Gurman de Bloomberg affirment qu'un casque de réalité mixte haut de gamme arrive depuis un moment. Certains rapports indiquaient qu'un casque viendrait cette année, mais d'autres ont récemment affirmé qu'un casque pourrait arriver en 2023 à la place. Les détails sont flous et contradictoires.

    Par exemple, Kuo a déclaré que l'appareil comportera son propre processeur équivalent à M1. Cela suggère qu'il peut être autonome et ne nécessitera pas d'iPhone ou de Mac à proximité. Mais un autre rapport récent a affirmé qu'Apple prévoyait de s'appuyer sur le traitement sur un appareil mobile à proximité.

    Certaines de ces différences pourraient être dues au fait qu'Apple travaille sur au moins deux appareils différents. L'un devrait être un casque haut de gamme compatible VR pour le contenu immersif, c'est celui attendu cette année ou la prochaine. Un autre appareil serait des lunettes AR destinées à être portées en se promenant dans les espaces publics. Mais l'entreprise pourrait également encore expérimenter une variété de concepts de produits, avec des conceptions et des caractéristiques distinctives encore à finaliser.

    Sources : code source, Rens, Steve

    Et vous ?

    Quelle lecture en faites-vous ?

    Voir aussi :

    Réalité virtuelle : le casque VR d'Apple pourrait coûter 3000 dollars, comporter des écrans 8K et plus d'une douzaine de caméras
    Apple : bientôt des casques utilisant le port Lightening sur les iDevices ? Cupertino a ajouté des spécificités à son programme MFI
    Contribuez au club : Corrections, suggestions, critiques, ... : Contactez le service news et Rédigez des actualités

  2. #2
    Chroniqueur Actualités

    Homme Profil pro
    Administrateur de base de données
    Inscrit en
    Mars 2013
    Messages
    8 456
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Canada

    Informations professionnelles :
    Activité : Administrateur de base de données

    Informations forums :
    Inscription : Mars 2013
    Messages : 8 456
    Points : 197 830
    Points
    197 830
    Par défaut Le nom Reality OS qu'Apple utiliserait pour désigner l'OS tournant sur son casque AR/VR apparaît dans un dépôt
    Le nom Reality OS qu'Apple utiliserait pour désigner l'OS tournant sur son casque AR/VR apparaît dans un dépôt de marque,
    suggérant qu'une annonce pourrait être imminente

    RealityOS, le nom qu'Apple utiliserait pour le système d'exploitation fonctionnant sur son casque de réalité virtuelle et augmentée supposé, est apparu dans un dépôt de marque.

    Il n'y a plus beaucoup de place pour le doute : des éléments indiquent qu'Apple prépare bien un système d'exploitation spécifiquement dédié à la réalité augmentée. En parcourant la portion de code open source utilisée par l'App Store et publiée sur GitHub, des développeurs ont trouvé en février des lignes de code qui évoquent un nouveau système baptisé « realityOS », qui sera sans doute lié au projet de casque AR/VR d'Apple. Des liens entre iOS et ce nouveau système sont mentionnés, mais aussi un simulateur utilisé par les développeurs pour tester leurs applications sans avoir le matériel sous la main.

    Code C++ : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    #include <stdlib.h>
    #include <assert.h>
    #include <string.h>
    #include <stdio.h>
    #include <sys/stat.h>
    #include <sys/types.h>
    #include <sys/errno.h>
    #include <sys/fcntl.h>
    #include <unistd.h>
    #include <TargetConditionals.h>
    #include <mach/host_info.h>
    #include <mach/mach.h>
    #include <mach/mach_host.h>
     
    #include "Array.h"
    #include "MachOFile.h"
    #include "SupportedArchs.h"
     
    #if BUILDING_DYLD || BUILDING_LIBDYLD
        // define away restrict until rdar://60166935 is fixed
        #define restrict
        #include <subsystem.h>
    #endif
     
    namespace dyld3 {
     
    ////////////////////////////  posix wrappers ////////////////////////////////////////
     
    // <rdar://problem/10111032> wrap calls to stat() with check for EAGAIN
    int stat(const char* path, struct stat* buf)
    {
        int result;
        do {
    #if BUILDING_DYLD
            result = ::stat_with_subsystem(path, buf);
    #else
            result = ::stat(path, buf);
    #endif
        } while ((result == -1) && ((errno == EAGAIN) || (errno == EINTR)));
     
        return result;
    }
     
    // <rdar://problem/13805025> dyld should retry open() if it gets an EGAIN
    int open(const char* path, int flag, int other)
    {
        int result;
        do {
    #if BUILDING_DYLD
            if (flag & O_CREAT)
                result = ::open(path, flag, other);
            else
                result = ::open_with_subsystem(path, flag);
    #else
            result = ::open(path, flag, other);
    #endif
        } while ((result == -1) && ((errno == EAGAIN) || (errno == EINTR)));
     
        return result;
    }
     
     
    ////////////////////////////  FatFile ////////////////////////////////////////
     
    const FatFile* FatFile::isFatFile(const void* fileStart)
    {
        const FatFile* fileStartAsFat = (FatFile*)fileStart;
        if ( (fileStartAsFat->magic == OSSwapBigToHostInt32(FAT_MAGIC)) || (fileStartAsFat->magic == OSSwapBigToHostInt32(FAT_MAGIC_64)) )
            return fileStartAsFat;
        else
            return nullptr;
    }
     
    bool FatFile::isValidSlice(Diagnostics& diag, uint64_t fileLen, uint32_t sliceIndex,
                               uint32_t sliceCpuType, uint32_t sliceCpuSubType, uint64_t sliceOffset, uint64_t sliceLen) const {
        if ( greaterThanAddOrOverflow(sliceOffset, sliceLen, fileLen) ) {
            diag.error("slice %d extends beyond end of file", sliceIndex);
            return false;
        }
        const dyld3::MachOFile* mf = (const dyld3::MachOFile*)((uint8_t*)this+sliceOffset);
        if (!mf->isMachO(diag, sliceLen))
            return false;
        if ( mf->cputype != (cpu_type_t)sliceCpuType ) {
            diag.error("cpu type in slice (0x%08X) does not match fat header (0x%08X)", mf->cputype, sliceCpuType);
            return false;
        }
        else if ( (mf->cpusubtype & ~CPU_SUBTYPE_MASK) != (sliceCpuSubType & ~CPU_SUBTYPE_MASK) ) {
            diag.error("cpu subtype in slice (0x%08X) does not match fat header (0x%08X)", mf->cpusubtype, sliceCpuSubType);
            return false;
        }
        uint32_t pageSizeMask = mf->uses16KPages() ? 0x3FFF : 0xFFF;
        if ( (sliceOffset & pageSizeMask) != 0 ) {
            // slice not page aligned
            if ( strncmp((char*)this+sliceOffset, "!<arch>", 7) == 0 )
                diag.error("file is static library");
            else
                diag.error("slice is not page aligned");
            return false;
        }
        return true;
    }
     
    void FatFile::forEachSlice(Diagnostics& diag, uint64_t fileLen, bool validate,
                               void (^callback)(uint32_t sliceCpuType, uint32_t sliceCpuSubType, const void* sliceStart, uint64_t sliceSize, bool& stop)) const
    {
    	if ( this->magic == OSSwapBigToHostInt32(FAT_MAGIC) ) {
            const uint64_t maxArchs = ((4096 - sizeof(fat_header)) / sizeof(fat_arch));
            const uint32_t numArchs = OSSwapBigToHostInt32(nfat_arch);
            if ( numArchs > maxArchs ) {
                diag.error("fat header too large: %u entries", numArchs);
                return;
            }
            bool stop = false;
            const fat_arch* const archs = (fat_arch*)(((char*)this)+sizeof(fat_header));
            for (uint32_t i=0; i < numArchs; ++i) {
                uint32_t cpuType    = OSSwapBigToHostInt32(archs[i].cputype);
                uint32_t cpuSubType = OSSwapBigToHostInt32(archs[i].cpusubtype);
                uint32_t offset     = OSSwapBigToHostInt32(archs[i].offset);
                uint32_t len        = OSSwapBigToHostInt32(archs[i].size);
                Diagnostics sliceDiag;
                if ( !validate || isValidSlice(sliceDiag, fileLen, i, cpuType, cpuSubType, offset, len) )
                    callback(cpuType, cpuSubType, (uint8_t*)this+offset, len, stop);
                if ( stop )
                    break;
                if ( sliceDiag.hasError() )
                    diag.appendError("%s, ", sliceDiag.errorMessageCStr());
            }
     
            // Look for one more slice
            if ( numArchs != maxArchs ) {
                uint32_t cpuType    = OSSwapBigToHostInt32(archs[numArchs].cputype);
                uint32_t cpuSubType = OSSwapBigToHostInt32(archs[numArchs].cpusubtype);
                uint32_t offset     = OSSwapBigToHostInt32(archs[numArchs].offset);
                uint32_t len        = OSSwapBigToHostInt32(archs[numArchs].size);
                if ((cpuType == CPU_TYPE_ARM64) && ((cpuSubType == CPU_SUBTYPE_ARM64_ALL || cpuSubType == CPU_SUBTYPE_ARM64_V8))) {
                    if ( !validate || isValidSlice(diag, fileLen, numArchs, cpuType, cpuSubType, offset, len) )
                        callback(cpuType, cpuSubType, (uint8_t*)this+offset, len, stop);
                }
            }
        }
        else if ( this->magic == OSSwapBigToHostInt32(FAT_MAGIC_64) ) {
            if ( OSSwapBigToHostInt32(nfat_arch) > ((4096 - sizeof(fat_header)) / sizeof(fat_arch)) ) {
                diag.error("fat header too large: %u entries", OSSwapBigToHostInt32(nfat_arch));
                return;
            }
            bool stop = false;
            const fat_arch_64* const archs = (fat_arch_64*)(((char*)this)+sizeof(fat_header));
            for (uint32_t i=0; i < OSSwapBigToHostInt32(nfat_arch); ++i) {
                uint32_t cpuType    = OSSwapBigToHostInt32(archs[i].cputype);
                uint32_t cpuSubType = OSSwapBigToHostInt32(archs[i].cpusubtype);
                uint64_t offset     = OSSwapBigToHostInt64(archs[i].offset);
                uint64_t len        = OSSwapBigToHostInt64(archs[i].size);
                if ( !validate || isValidSlice(diag, fileLen, i, cpuType, cpuSubType, offset, len) )
                    callback(cpuType, cpuSubType, (uint8_t*)this+offset, len, stop);
                if ( stop )
                    break;
            }
        }
        else {
            diag.error("not a fat file");
        }
    }
     
    void FatFile::forEachSlice(Diagnostics& diag, uint64_t fileLen, void (^callback)(uint32_t sliceCpuType, uint32_t sliceCpuSubType, const void* sliceStart, uint64_t sliceSize, bool& stop)) const
    {
        forEachSlice(diag, fileLen, true, callback);
    }
     
    const char* FatFile::archNames(char strBuf[256]) const
    {
        strBuf[0] = '\0';
        Diagnostics   diag;
        __block bool  needComma = false;
        this->forEachSlice(diag, 0xFFFFFFFF, false, ^(uint32_t sliceCpuType, uint32_t sliceCpuSubType, const void* sliceStart, uint64_t sliceSize, bool& stop) {
            if ( needComma )
                strlcat(strBuf, ",", 256);
            strlcat(strBuf, MachOFile::archName(sliceCpuType, sliceCpuSubType), 256);
            needComma = true;
        });
        return strBuf;
    }
     
    bool FatFile::isFatFileWithSlice(Diagnostics& diag, uint64_t fileLen, const GradedArchs& archs, bool isOSBinary,
                                     uint64_t& sliceOffset, uint64_t& sliceLen, bool& missingSlice) const
    {
        missingSlice = false;
        if ( (this->magic != OSSwapBigToHostInt32(FAT_MAGIC)) && (this->magic != OSSwapBigToHostInt32(FAT_MAGIC_64)) )
            return false;
     
        __block int bestGrade = 0;
        forEachSlice(diag, fileLen, ^(uint32_t sliceCpuType, uint32_t sliceCpuSubType, const void* sliceStart, uint64_t sliceSize, bool& stop) {
            if (int sliceGrade = archs.grade(sliceCpuType, sliceCpuSubType, isOSBinary)) {
                if ( sliceGrade > bestGrade ) {
                    sliceOffset = (char*)sliceStart - (char*)this;
                    sliceLen    = sliceSize;
                    bestGrade   = sliceGrade;
                }
            }
        });
        if ( diag.hasError() )
            return false;
     
        if ( bestGrade == 0 )
            missingSlice = true;
     
        return (bestGrade != 0);
    }
     
     
    ////////////////////////////  GradedArchs ////////////////////////////////////////
     
     
    #define GRADE_i386        CPU_TYPE_I386,       CPU_SUBTYPE_I386_ALL,    false
    #define GRADE_x86_64      CPU_TYPE_X86_64,     CPU_SUBTYPE_X86_64_ALL,  false
    #define GRADE_x86_64h     CPU_TYPE_X86_64,     CPU_SUBTYPE_X86_64_H,    false
    #define GRADE_armv7       CPU_TYPE_ARM,        CPU_SUBTYPE_ARM_V7,      false
    #define GRADE_armv7s      CPU_TYPE_ARM,        CPU_SUBTYPE_ARM_V7S,     false
    #define GRADE_armv7k      CPU_TYPE_ARM,        CPU_SUBTYPE_ARM_V7K,     false
    #define GRADE_arm64       CPU_TYPE_ARM64,      CPU_SUBTYPE_ARM64_ALL,   false
    #define GRADE_arm64e      CPU_TYPE_ARM64,      CPU_SUBTYPE_ARM64E,      false
    #define GRADE_arm64e_pb   CPU_TYPE_ARM64,      CPU_SUBTYPE_ARM64E,      true
    #define GRADE_arm64_32    CPU_TYPE_ARM64_32,   CPU_SUBTYPE_ARM64_32_V8, false
     
    const GradedArchs GradedArchs::i386              = { {{GRADE_i386,    1}} };
    const GradedArchs GradedArchs::x86_64            = { {{GRADE_x86_64,  1}} };
    const GradedArchs GradedArchs::x86_64h           = { {{GRADE_x86_64h, 2}, {GRADE_x86_64, 1}} };
    const GradedArchs GradedArchs::arm64             = { {{GRADE_arm64,   1}} };
    #if SUPPORT_ARCH_arm64e
    const GradedArchs GradedArchs::arm64e_keysoff    = { {{GRADE_arm64e,    2}, {GRADE_arm64, 1}} };
    const GradedArchs GradedArchs::arm64e_keysoff_pb = { {{GRADE_arm64e_pb, 2}, {GRADE_arm64, 1}} };
    const GradedArchs GradedArchs::arm64e            = { {{GRADE_arm64e,    1}} };
    const GradedArchs GradedArchs::arm64e_pb         = { {{GRADE_arm64e_pb, 1}} };
    #endif
    const GradedArchs GradedArchs::armv7             = { {{GRADE_armv7,   1}} };
    const GradedArchs GradedArchs::armv7s            = { {{GRADE_armv7s,  2}, {GRADE_armv7, 1}} };
    const GradedArchs GradedArchs::armv7k            = { {{GRADE_armv7k,  1}} };
    #if SUPPORT_ARCH_arm64_32
    const GradedArchs GradedArchs::arm64_32          = { {{GRADE_arm64_32, 1}} };
    #endif
     
    int GradedArchs::grade(uint32_t cputype, uint32_t cpusubtype, bool isOSBinary) const
    {
        for (const CpuGrade* p = _orderedCpuTypes; p->type != 0; ++p) {
            if ( (p->type == cputype) && (p->subtype == (cpusubtype & ~CPU_SUBTYPE_MASK)) ) {
                if ( p->osBinary ) {
                    if ( isOSBinary )
                        return p->grade;
                }
                else {
                    return p->grade;
                }
            }
        }
        return 0;
    }
     
    const char* GradedArchs::name() const
    {
        return MachOFile::archName(_orderedCpuTypes[0].type, _orderedCpuTypes[0].subtype);
    }
     
    bool GradedArchs::checksOSBinary() const
    {
        for (const CpuGrade* p = _orderedCpuTypes; p->type != 0; ++p) {
            if ( p->osBinary )
                return true;
        }
        return false;
    }
     
    #if __x86_64__
    static bool isHaswell()
    {
        // FIXME: figure out a commpage way to check this
        struct host_basic_info info;
        mach_msg_type_number_t count = HOST_BASIC_INFO_COUNT;
        mach_port_t hostPort = mach_host_self();
        kern_return_t result = host_info(hostPort, HOST_BASIC_INFO, (host_info_t)&info, &count);
        mach_port_deallocate(mach_task_self(), hostPort);
        return (result == KERN_SUCCESS) && (info.cpu_subtype == CPU_SUBTYPE_X86_64_H);
    }
    #endif
     
    const GradedArchs& GradedArchs::forCurrentOS(bool keysOff, bool osBinariesOnly)
    {
    #if __arm64e__
        if ( osBinariesOnly )
            return (keysOff ? arm64e_keysoff_pb : arm64e_pb);
        else
            return (keysOff ? arm64e_keysoff : arm64e);
    #elif __ARM64_ARCH_8_32__
        return arm64_32;
    #elif __arm64__
        return arm64;
    #elif __ARM_ARCH_7K__
        return armv7k;
    #elif __ARM_ARCH_7S__
        return armv7s;
    #elif __ARM_ARCH_7A__
        return armv7;
    #elif __x86_64__
     #if TARGET_OS_SIMULATOR
        return x86_64;
      #else
        return isHaswell() ? x86_64h : x86_64;
      #endif
    #elif __i386__
        return i386;
    #else
        #error unknown platform
    #endif
    }
     
    const GradedArchs& GradedArchs::forName(const char* archName, bool keysOff)
    {
        if (strcmp(archName, "x86_64h") == 0 )
            return x86_64h;
        else if (strcmp(archName, "x86_64") == 0 )
            return x86_64;
    #if SUPPORT_ARCH_arm64e
        else if (strcmp(archName, "arm64e") == 0 )
            return keysOff ? arm64e_keysoff : arm64e;
    #endif
        else if (strcmp(archName, "arm64") == 0 )
            return arm64;
        else if (strcmp(archName, "armv7k") == 0 )
            return armv7k;
        else if (strcmp(archName, "armv7s") == 0 )
            return armv7s;
        else if (strcmp(archName, "armv7") == 0 )
            return armv7;
    #if SUPPORT_ARCH_arm64_32
        else if (strcmp(archName, "arm64_32") == 0 )
            return arm64_32;
    #endif
        else if (strcmp(archName, "i386") == 0 )
            return i386;
        assert(0 && "unknown arch name");
    }
     
     
     
    ////////////////////////////  MachOFile ////////////////////////////////////////
     
     
    const MachOFile::ArchInfo MachOFile::_s_archInfos[] = {
        { "x86_64",   CPU_TYPE_X86_64,   CPU_SUBTYPE_X86_64_ALL  },
        { "x86_64h",  CPU_TYPE_X86_64,   CPU_SUBTYPE_X86_64_H    },
        { "i386",     CPU_TYPE_I386,     CPU_SUBTYPE_I386_ALL    },
        { "arm64",    CPU_TYPE_ARM64,    CPU_SUBTYPE_ARM64_ALL   },
    #if SUPPORT_ARCH_arm64e
        { "arm64e",   CPU_TYPE_ARM64,    CPU_SUBTYPE_ARM64E     },
    #endif
    #if SUPPORT_ARCH_arm64_32
        { "arm64_32", CPU_TYPE_ARM64_32, CPU_SUBTYPE_ARM64_32_V8 },
    #endif
        { "armv7k",   CPU_TYPE_ARM,      CPU_SUBTYPE_ARM_V7K     },
        { "armv7s",   CPU_TYPE_ARM,      CPU_SUBTYPE_ARM_V7S     },
        { "armv7",    CPU_TYPE_ARM,      CPU_SUBTYPE_ARM_V7      }
    };
     
    const MachOFile::PlatformInfo MachOFile::_s_platformInfos[] = {
        { "macOS",       Platform::macOS,             LC_VERSION_MIN_MACOSX   },
        { "iOS",         Platform::iOS,               LC_VERSION_MIN_IPHONEOS },
        { "tvOS",        Platform::tvOS,              LC_VERSION_MIN_TVOS     },
        { "watchOS",     Platform::watchOS,           LC_VERSION_MIN_WATCHOS  },
        { "bridgeOS",    Platform::bridgeOS,          LC_BUILD_VERSION        },
        { "MacCatalyst", Platform::iOSMac,            LC_BUILD_VERSION        },
        { "iOS-sim",     Platform::iOS_simulator,     LC_BUILD_VERSION        },
        { "tvOS-sim",    Platform::tvOS_simulator,    LC_BUILD_VERSION        },
        { "watchOS-sim", Platform::watchOS_simulator, LC_BUILD_VERSION        },
        { "driverKit",   Platform::driverKit,         LC_BUILD_VERSION        },
    };
     
     
     
    bool MachOFile::is64() const
    {
        return (this->magic == MH_MAGIC_64);
    }
     
    size_t MachOFile::machHeaderSize() const
    {
        return is64() ? sizeof(mach_header_64) : sizeof(mach_header);
    }
     
    uint32_t MachOFile::maskedCpuSubtype() const
    {
        return (this->cpusubtype & ~CPU_SUBTYPE_MASK);
    }
     
    uint32_t MachOFile::pointerSize() const
    {
        if (this->magic == MH_MAGIC_64)
            return 8;
        else
            return 4;
    }
     
    bool MachOFile::uses16KPages() const
    {
        switch (this->cputype) {
            case CPU_TYPE_ARM64:
            case CPU_TYPE_ARM64_32:
                return true;
            case CPU_TYPE_ARM:
                // iOS is 16k aligned for armv7/armv7s and watchOS armv7k is 16k aligned
                return this->cpusubtype == CPU_SUBTYPE_ARM_V7K;
            default:
                return false;
        }
    }
     
    bool MachOFile::isArch(const char* aName) const
    {
        return (strcmp(aName, archName(this->cputype, this->cpusubtype)) == 0);
    }
     
    const char* MachOFile::archName(uint32_t cputype, uint32_t cpusubtype)
    {
        for (const ArchInfo& info : _s_archInfos) {
            if ( (cputype == info.cputype) && ((cpusubtype & ~CPU_SUBTYPE_MASK) == info.cpusubtype) ) {
                return info.name;
            }
        }
        return "unknown";
    }
     
    uint32_t MachOFile::cpuTypeFromArchName(const char* archName)
    {
        for (const ArchInfo& info : _s_archInfos) {
            if ( strcmp(archName, info.name) == 0 ) {
                return info.cputype;
            }
        }
        return 0;
    }
     
    uint32_t MachOFile::cpuSubtypeFromArchName(const char* archName)
    {
        for (const ArchInfo& info : _s_archInfos) {
            if ( strcmp(archName, info.name) == 0 ) {
                return info.cpusubtype;
            }
        }
        return 0;
    }
     
    const char* MachOFile::archName() const
    {
        return archName(this->cputype, this->cpusubtype);
    }
     
    static void appendDigit(char*& s, unsigned& num, unsigned place, bool& startedPrinting)
    {
        if ( num >= place ) {
            unsigned dig = (num/place);
            *s++ = '0' + dig;
            num -= (dig*place);
            startedPrinting = true;
        }
        else if ( startedPrinting ) {
            *s++ = '0';
        }
    }
     
    static void appendNumber(char*& s, unsigned num)
    {
        assert(num < 99999);
        bool startedPrinting = false;
        appendDigit(s, num, 10000, startedPrinting);
        appendDigit(s, num,  1000, startedPrinting);
        appendDigit(s, num,   100, startedPrinting);
        appendDigit(s, num,    10, startedPrinting);
        appendDigit(s, num,     1, startedPrinting);
        if ( !startedPrinting )
            *s++ = '0';
    }
     
    void MachOFile::packedVersionToString(uint32_t packedVersion, char versionString[32])
    {
        // sprintf(versionString, "%d.%d.%d", (packedVersion >> 16), ((packedVersion >> 8) & 0xFF), (packedVersion & 0xFF));
        char* s = versionString;
        appendNumber(s, (packedVersion >> 16));
        *s++ = '.';
        appendNumber(s, (packedVersion >> 8) & 0xFF);
        *s++ = '.';
        appendNumber(s, (packedVersion & 0xFF));
        *s++ = '\0';
    }
     
    bool MachOFile::builtForPlatform(Platform reqPlatform, bool onlyOnePlatform) const
    {
        __block bool foundRequestedPlatform = false;
        __block bool foundOtherPlatform     = false;
        forEachSupportedPlatform(^(Platform platform, uint32_t minOS, uint32_t sdk) {
            if ( platform == reqPlatform )
                foundRequestedPlatform = true;
            else
                foundOtherPlatform = true;
        });
        // if checking that this binary is built for exactly one platform, fail if more
        if ( foundOtherPlatform && onlyOnePlatform )
            return false;
        if ( foundRequestedPlatform )
            return true;
     
        // binary has no explict load command to mark platform
        // could be an old macOS binary, look at arch
        if  ( !foundOtherPlatform && (reqPlatform == Platform::macOS) ) {
            if ( this->cputype == CPU_TYPE_X86_64 )
                return true;
            if ( this->cputype == CPU_TYPE_I386 )
                return true;
        }
     
    #if BUILDING_DYLDINFO
        // Allow offline tools to analyze binaries dyld doesn't load, ie, those with platforms
        if ( !foundOtherPlatform && (reqPlatform == Platform::unknown) )
            return true;
    #endif
     
        return false;
    }
     
    bool MachOFile::loadableIntoProcess(Platform processPlatform, const char* path) const
    {
        if ( this->builtForPlatform(processPlatform) )
            return true;
     
        // Some host macOS dylibs can be loaded into simulator processes
        if ( MachOFile::isSimulatorPlatform(processPlatform) && this->builtForPlatform(Platform::macOS)) {
            static const char* const macOSHost[] = {
                "/usr/lib/system/libsystem_kernel.dylib",
                "/usr/lib/system/libsystem_platform.dylib",
                "/usr/lib/system/libsystem_pthread.dylib",
                "/usr/lib/system/libsystem_platform_debug.dylib",
                "/usr/lib/system/libsystem_pthread_debug.dylib",
                "/usr/lib/system/host/liblaunch_sim.dylib",
            };
            for (const char* libPath : macOSHost) {
                if (strcmp(libPath, path) == 0)
                    return true;
            }
        }
     
        // If this is being called on main executable where we expect a macOS program, Catalyst programs are also runnable
        if ( (this->filetype == MH_EXECUTE) && (processPlatform == Platform::macOS) && this->builtForPlatform(Platform::iOSMac, true) )
            return true;
    #if (TARGET_OS_OSX && TARGET_CPU_ARM64)
        if ( (this->filetype == MH_EXECUTE) && (processPlatform == Platform::macOS) && this->builtForPlatform(Platform::iOS, true) )
            return true;
    #endif
     
    #if TARGET_FEATURE_REALITYOS
        // allow iOS executables to use realityOS dylibs
        if ( (processPlatform == Platform::iOS) && this->builtForPlatform(Platform::realityOS, true) )
            return true;
     
        // allow iOS_Sim executables to use realityOS_Sim dylibs
        if ( (processPlatform == Platform::iOS_simulator) && this->builtForPlatform(Platform::realityOS_simulator, true) )
            return true;
    #endif
     
        bool iOSonMac = (processPlatform == Platform::iOSMac);
    #if (TARGET_OS_OSX && TARGET_CPU_ARM64)
        // allow iOS binaries in iOSApp
        if ( processPlatform == Platform::iOS ) {
            // can load Catalyst binaries into iOS process
            if ( this->builtForPlatform(Platform::iOSMac) )
                return true;
            iOSonMac = true;
        }
    #endif
        // macOS dylibs can be loaded into iOSMac processes
        if ( (iOSonMac) && this->builtForPlatform(Platform::macOS, true) )
            return true;
     
     
        return false;
    }
     
    bool MachOFile::isZippered() const
    {
        __block bool macOS = false;
        __block bool iOSMac = false;
        forEachSupportedPlatform(^(Platform platform, uint32_t minOS, uint32_t sdk) {
            if ( platform == Platform::macOS )
                macOS = true;
            else if ( platform == Platform::iOSMac )
                iOSMac = true;
        });
        return macOS && iOSMac;
    }
     
    bool MachOFile::inDyldCache() const {
        return (this->flags & MH_DYLIB_IN_CACHE);
    }
     
    Platform MachOFile::currentPlatform()
    {
    #if TARGET_OS_SIMULATOR
      #if TARGET_OS_WATCH
        return Platform::watchOS_simulator;
      #elif TARGET_OS_TV
        return Platform::tvOS_simulator;
      #elif TARGET_FEATURE_REALITYOS
        return Platform::realityOS_simulator;
      #else
        return Platform::iOS_simulator;
      #endif
    #elif TARGET_OS_BRIDGE
        return Platform::bridgeOS;
    #elif TARGET_OS_WATCH
        return Platform::watchOS;
    #elif TARGET_OS_TV
        return Platform::tvOS;
    #elif TARGET_OS_IOS
        return Platform::iOS;
    #elif TARGET_FEATURE_REALITYOS
        return Platform::realityOS;
    #elif TARGET_OS_OSX
        return Platform::macOS;
    #elif TARGET_OS_DRIVERKIT
        return Platform::driverKit;
    #else
        #error unknown platform
    #endif
    }
     
    Platform MachOFile::basePlatform(dyld3::Platform reqPlatform) {
        switch(reqPlatform) {
            case Platform::unknown:               return Platform::unknown;
            case Platform::macOS:                 return Platform::macOS;
            case Platform::iOS:                   return Platform::iOS;
            case Platform::tvOS:                  return Platform::tvOS;
            case Platform::watchOS:               return Platform::watchOS;
            case Platform::bridgeOS:              return Platform::bridgeOS;
            case Platform::iOSMac:                return Platform::iOS;
            case Platform::iOS_simulator:         return Platform::iOS;
            case Platform::tvOS_simulator:        return Platform::tvOS;
            case Platform::watchOS_simulator:     return Platform::watchOS;
            case Platform::driverKit:             return Platform::driverKit;
            default:                              return Platform::unknown;
        }
    }
     
     
    const char* MachOFile::currentArchName()
    {
    #if __ARM_ARCH_7K__
        return "armv7k";
    #elif __ARM_ARCH_7A__
        return "armv7";
    #elif __ARM_ARCH_7S__
        return "armv7s";
    #elif __arm64e__
        return "arm64e";
    #elif __arm64__
    #if __LP64__
        return "arm64";
    #else
        return "arm64_32";
    #endif
    #elif __x86_64__
        return isHaswell() ? "x86_64h" : "x86_64";
    #elif __i386__
        return "i386";
    #else
        #error unknown arch
    #endif
    }
     
    bool MachOFile::isSimulatorPlatform(Platform platform, Platform* basePlatform)
    {
        switch ( platform ) {
            case Platform::iOS_simulator:
                if ( basePlatform )
                    *basePlatform = Platform::iOS;
                return true;
            case Platform::watchOS_simulator:
                if ( basePlatform )
                    *basePlatform = Platform::watchOS;
                return true;
            case Platform::tvOS_simulator:
                if ( basePlatform )
                    *basePlatform = Platform::tvOS;
                return true;
           default:
                return false;
        }
    }
     
    bool MachOFile::isDyldManaged() const {
        switch ( this->filetype ) {
            case MH_BUNDLE:
            case MH_EXECUTE:
            case MH_DYLIB:
                return true;
            default:
                break;
        }
        return false;
    }
     
    bool MachOFile::isDylib() const
    {
        return (this->filetype == MH_DYLIB);
    }
     
    bool MachOFile::isBundle() const
    {
        return (this->filetype == MH_BUNDLE);
    }
     
    bool MachOFile::isMainExecutable() const
    {
        return (this->filetype == MH_EXECUTE);
    }
     
    bool MachOFile::isDynamicExecutable() const
    {
        if ( this->filetype != MH_EXECUTE )
            return false;
     
        // static executables do not have dyld load command
        return hasLoadCommand(LC_LOAD_DYLINKER);
    }
     
    bool MachOFile::isStaticExecutable() const
    {
        if ( this->filetype != MH_EXECUTE )
            return false;
     
        // static executables do not have dyld load command
        return !hasLoadCommand(LC_LOAD_DYLINKER);
    }
     
    bool MachOFile::isKextBundle() const
    {
        return (this->filetype == MH_KEXT_BUNDLE);
    }
     
    bool MachOFile::isFileSet() const
    {
        return (this->filetype == MH_FILESET);
    }
     
    bool MachOFile::isPIE() const
    {
        return (this->flags & MH_PIE);
    }
     
    bool MachOFile::isPreload() const
    {
        return (this->filetype == MH_PRELOAD);
    }
     
    const char* MachOFile::platformName(Platform reqPlatform)
    {
        for (const PlatformInfo& info : _s_platformInfos) {
            if ( info.platform == reqPlatform )
                return info.name;
        }
        return "unknown";
    }
     
    void MachOFile::forEachSupportedPlatform(void (^handler)(Platform platform, uint32_t minOS, uint32_t sdk)) const
    {
        Diagnostics diag;
        __block bool foundPlatform = false;
        forEachLoadCommand(diag, ^(const load_command* cmd, bool& stop) {
            const build_version_command* buildCmd = (build_version_command *)cmd;
            const version_min_command*   versCmd  = (version_min_command*)cmd;
            uint32_t                     sdk;
            switch ( cmd->cmd ) {
                case LC_BUILD_VERSION:
                    handler((Platform)(buildCmd->platform), buildCmd->minos, buildCmd->sdk);
                    foundPlatform = true;
                    break;
                case LC_VERSION_MIN_MACOSX:
                    sdk = versCmd->sdk;
                    // The original LC_VERSION_MIN_MACOSX did not have an sdk field, assume sdk is same as minOS for those old binaries
                    if ( sdk == 0 )
                        sdk = versCmd->version;
                    handler(Platform::macOS, versCmd->version, sdk);
                    foundPlatform = true;
                    break;
                case LC_VERSION_MIN_IPHONEOS:
                    if ( (this->cputype == CPU_TYPE_X86_64) || (this->cputype == CPU_TYPE_I386) )
                        handler(Platform::iOS_simulator, versCmd->version, versCmd->sdk); // old sim binary
                    else
                        handler(Platform::iOS, versCmd->version, versCmd->sdk);
                    foundPlatform = true;
                    break;
                case LC_VERSION_MIN_TVOS:
                    if ( this->cputype == CPU_TYPE_X86_64 )
                        handler(Platform::tvOS_simulator, versCmd->version, versCmd->sdk); // old sim binary
                    else
                        handler(Platform::tvOS, versCmd->version, versCmd->sdk);
                    foundPlatform = true;
                    break;
                case LC_VERSION_MIN_WATCHOS:
                    if ( (this->cputype == CPU_TYPE_X86_64) || (this->cputype == CPU_TYPE_I386) )
                        handler(Platform::watchOS_simulator, versCmd->version, versCmd->sdk); // old sim binary
                    else
                        handler(Platform::watchOS, versCmd->version, versCmd->sdk);
                    foundPlatform = true;
                    break;
            }
        });
        if ( !foundPlatform ) {
            // old binary with no explicit platform
    #if (BUILDING_DYLD || BUILDING_CLOSURE_UTIL) && TARGET_OS_OSX
            if ( this->cputype == CPU_TYPE_X86_64 )
                handler(Platform::macOS, 0x000A0500, 0x000A0500); // guess it is a macOS 10.5 binary
            // <rdar://problem/75343399>
            // The Go linker emits non-standard binaries without a platform and we have to live with it.
            if ( this->cputype == CPU_TYPE_ARM64 )
                handler(Platform::macOS, 0x000B0000, 0x000B0000); // guess it is a macOS 11.0 binary
    #endif
        }
        diag.assertNoError();   // any malformations in the file should have been caught by earlier validate() call
    }
     
     
    bool MachOFile::isMachO(Diagnostics& diag, uint64_t fileSize) const
    {
        if ( !hasMachOMagic() ) {
            // old PPC slices are not currently valid "mach-o" but should not cause an error
            if ( !hasMachOBigEndianMagic() )
                diag.error("file does not start with MH_MAGIC[_64]");
            return false;
        }
        if ( this->sizeofcmds + machHeaderSize() > fileSize ) {
            diag.error("load commands exceed length of first segment");
            return false;
        }
        forEachLoadCommand(diag, ^(const load_command* cmd, bool& stop) { });
        return diag.noError();
    }
     
    bool MachOFile::hasMachOMagic() const
    {
        return ( (this->magic == MH_MAGIC) || (this->magic == MH_MAGIC_64) );
    }
     
    bool MachOFile::hasMachOBigEndianMagic() const
    {
        return ( (this->magic == MH_CIGAM) || (this->magic == MH_CIGAM_64) );
    }
     
     
    void MachOFile::forEachLoadCommand(Diagnostics& diag, void (^callback)(const load_command* cmd, bool& stop)) const
    {
        bool stop = false;
        const load_command* startCmds = nullptr;
        if ( this->magic == MH_MAGIC_64 )
            startCmds = (load_command*)((char *)this + sizeof(mach_header_64));
        else if ( this->magic == MH_MAGIC )
            startCmds = (load_command*)((char *)this + sizeof(mach_header));
        else if ( hasMachOBigEndianMagic() )
            return;  // can't process big endian mach-o
        else {
            const uint32_t* h = (uint32_t*)this;
            diag.error("file does not start with MH_MAGIC[_64]: 0x%08X 0x%08X", h[0], h [1]);
            return;  // not a mach-o file
        }
        const load_command* const cmdsEnd = (load_command*)((char*)startCmds + this->sizeofcmds);
        const load_command* cmd = startCmds;
        for (uint32_t i = 0; i < this->ncmds; ++i) {
            const load_command* nextCmd = (load_command*)((char *)cmd + cmd->cmdsize);
            if ( cmd->cmdsize < 8 ) {
                diag.error("malformed load command #%d of %d at %p with mh=%p, size (0x%X) too small", i, this->ncmds, cmd, this, cmd->cmdsize);
                return;
            }
            // FIXME: add check the cmdsize is pointer aligned (might reveal bin compat issues)
            if ( (nextCmd > cmdsEnd) || (nextCmd < startCmds) ) {
                diag.error("malformed load command #%d of %d at %p with mh=%p, size (0x%X) is too large, load commands end at %p", i, this->ncmds, cmd, this, cmd->cmdsize, cmdsEnd);
                return;
            }
            callback(cmd, stop);
            if ( stop )
                return;
            cmd = nextCmd;
        }
    }
     
    void MachOFile::removeLoadCommand(Diagnostics& diag, void (^callback)(const load_command* cmd, bool& remove, bool& stop))
    {
        bool stop = false;
        const load_command* startCmds = nullptr;
        if ( this->magic == MH_MAGIC_64 )
            startCmds = (load_command*)((char *)this + sizeof(mach_header_64));
        else if ( this->magic == MH_MAGIC )
            startCmds = (load_command*)((char *)this + sizeof(mach_header));
        else if ( hasMachOBigEndianMagic() )
            return;  // can't process big endian mach-o
        else {
            const uint32_t* h = (uint32_t*)this;
            diag.error("file does not start with MH_MAGIC[_64]: 0x%08X 0x%08X", h[0], h [1]);
            return;  // not a mach-o file
        }
        const load_command* const cmdsEnd = (load_command*)((char*)startCmds + this->sizeofcmds);
        auto cmd = (load_command*)startCmds;
        const uint32_t origNcmds = this->ncmds;
        unsigned bytesRemaining = this->sizeofcmds;
        for (uint32_t i = 0; i < origNcmds; ++i) {
            bool remove = false;
            auto nextCmd = (load_command*)((char *)cmd + cmd->cmdsize);
            if ( cmd->cmdsize < 8 ) {
                diag.error("malformed load command #%d of %d at %p with mh=%p, size (0x%X) too small", i, this->ncmds, cmd, this, cmd->cmdsize);
                return;
            }
            if ( (nextCmd > cmdsEnd) || (nextCmd < startCmds) ) {
                diag.error("malformed load command #%d of %d at %p with mh=%p, size (0x%X) is too large, load commands end at %p", i, this->ncmds, cmd, this, cmd->cmdsize, cmdsEnd);
                return;
            }
            callback(cmd, remove, stop);
            if ( remove ) {
                this->sizeofcmds -= cmd->cmdsize;
                ::memmove((void*)cmd, (void*)nextCmd, bytesRemaining);
                this->ncmds--;
            } else {
                bytesRemaining -= cmd->cmdsize;
                cmd = nextCmd;
            }
            if ( stop )
                break;
        }
        if ( cmd )
         ::bzero(cmd, bytesRemaining);
    }
     
    const char* MachOFile::installName() const
    {
        const char*  name;
        uint32_t     compatVersion;
        uint32_t     currentVersion;
        if ( getDylibInstallName(&name, &compatVersion, &currentVersion) )
            return name;
        return nullptr;
    }
     
    bool MachOFile::getDylibInstallName(const char** installName, uint32_t* compatVersion, uint32_t* currentVersion) const
    {
        Diagnostics diag;
        __block bool found = false;
        forEachLoadCommand(diag, ^(const load_command* cmd, bool& stop) {
            if ( cmd->cmd == LC_ID_DYLIB ) {
                const dylib_command*  dylibCmd = (dylib_command*)cmd;
                *compatVersion  = dylibCmd->dylib.compatibility_version;
                *currentVersion = dylibCmd->dylib.current_version;
                *installName    = (char*)dylibCmd + dylibCmd->dylib.name.offset;
                found = true;
                stop = true;
            }
        });
        diag.assertNoError();   // any malformations in the file should have been caught by earlier validate() call
        return found;
    }
     
    bool MachOFile::getUuid(uuid_t uuid) const
    {
        Diagnostics diag;
        __block bool found = false;
        forEachLoadCommand(diag, ^(const load_command* cmd, bool& stop) {
            if ( cmd->cmd == LC_UUID ) {
                const uuid_command* uc = (const uuid_command*)cmd;
                memcpy(uuid, uc->uuid, sizeof(uuid_t));
                found = true;
                stop = true;
            }
        });
        diag.assertNoError();   // any malformations in the file should have been caught by earlier validate() call
        if ( !found )
            bzero(uuid, sizeof(uuid_t));
        return found;
    }
     
    void MachOFile::forEachDependentDylib(void (^callback)(const char* loadPath, bool isWeak, bool isReExport, bool isUpward, uint32_t compatVersion, uint32_t curVersion, bool& stop)) const
    {
        Diagnostics       diag;
        __block unsigned  count   = 0;
        __block bool      stopped = false;
        forEachLoadCommand(diag, ^(const load_command* cmd, bool& stop) {
             switch ( cmd->cmd ) {
                case LC_LOAD_DYLIB:
                case LC_LOAD_WEAK_DYLIB:
                case LC_REEXPORT_DYLIB:
                case LC_LOAD_UPWARD_DYLIB: {
                    const dylib_command* dylibCmd = (dylib_command*)cmd;
                    const char* loadPath = (char*)dylibCmd + dylibCmd->dylib.name.offset;
                    callback(loadPath, (cmd->cmd == LC_LOAD_WEAK_DYLIB), (cmd->cmd == LC_REEXPORT_DYLIB), (cmd->cmd == LC_LOAD_UPWARD_DYLIB),
                                        dylibCmd->dylib.compatibility_version, dylibCmd->dylib.current_version, stop);
                    ++count;
                    if ( stop )
                        stopped = true;
                }
                break;
            }
        });
        // everything must link with something
        if ( (count == 0) && !stopped ) {
            // The dylibs that make up libSystem can link with nothing
            // except for dylibs in libSystem.dylib which are ok to link with nothing (they are on bottom)
            if ( this->builtForPlatform(Platform::driverKit, true) ) {
                if ( !this->isDylib() || (strncmp(this->installName(), "/System/DriverKit/usr/lib/system/", 33) != 0) )
                    callback("/System/DriverKit/usr/lib/libSystem.B.dylib", false, false, false, 0x00010000, 0x00010000, stopped);
            }
            else {
                if ( !this->isDylib() || (strncmp(this->installName(), "/usr/lib/system/", 16) != 0) )
                    callback("/usr/lib/libSystem.B.dylib", false, false, false, 0x00010000, 0x00010000, stopped);
            }
        }
        diag.assertNoError();   // any malformations in the file should have been caught by earlier validate() call
    }
     
    void MachOFile::forDyldEnv(void (^callback)(const char* envVar, bool& stop)) const
    {
        Diagnostics diag;
        forEachLoadCommand(diag, ^(const load_command* cmd, bool& stop) {
             if ( cmd->cmd == LC_DYLD_ENVIRONMENT ) {
                const dylinker_command* envCmd = (dylinker_command*)cmd;
                const char* keyEqualsValue = (char*)envCmd + envCmd->name.offset;
                // only process variables that start with DYLD_ and end in _PATH
                if ( (strncmp(keyEqualsValue, "DYLD_", 5) == 0) ) {
                    const char* equals = strchr(keyEqualsValue, '=');
                    if ( equals != NULL ) {
                        if ( strncmp(&equals[-5], "_PATH", 5) == 0 ) {
                            callback(keyEqualsValue, stop);
                        }
                    }
                }
            }
        });
        diag.assertNoError();   // any malformations in the file should have been caught by earlier validate() call
    }
     
    bool MachOFile::enforceCompatVersion() const
    {
        __block bool result = true;
        forEachSupportedPlatform(^(Platform platform, uint32_t minOS, uint32_t sdk) {
            switch ( platform ) {
                case Platform::macOS:
                    if ( minOS >= 0x000A0E00 )  // macOS 10.14
                        result = false;
                    break;
                case Platform::iOS:
                case Platform::tvOS:
                case Platform::iOS_simulator:
                case Platform::tvOS_simulator:
                    if ( minOS >= 0x000C0000 )  // iOS 12.0
                        result = false;
                    break;
                case Platform::watchOS:
                case Platform::watchOS_simulator:
                    if ( minOS >= 0x00050000 )  // watchOS 5.0
                        result = false;
                    break;
                case Platform::bridgeOS:
                    if ( minOS >= 0x00030000 )  // bridgeOS 3.0
                        result = false;
                    break;
                case Platform::driverKit:
                case Platform::iOSMac:
                    result = false;
                    break;
                case Platform::unknown:
                    break;
            }
        });
        return result;
    }
     
    const thread_command* MachOFile::unixThreadLoadCommand() const {
        Diagnostics diag;
        __block const thread_command* command = nullptr;
        forEachLoadCommand(diag, ^(const load_command* cmd, bool& stop) {
            if ( cmd->cmd == LC_UNIXTHREAD ) {
                command = (const thread_command*)cmd;
                stop = true;
            }
        });
        return command;
    }
     
     
    uint32_t MachOFile::entryAddrRegisterIndexForThreadCmd() const
    {
        switch ( this->cputype ) {
            case CPU_TYPE_I386:
                return 10; // i386_thread_state_t.eip
            case CPU_TYPE_X86_64:
                return 16; // x86_thread_state64_t.rip
            case CPU_TYPE_ARM:
                return 15; // arm_thread_state_t.pc
            case CPU_TYPE_ARM64:
                return 32; // arm_thread_state64_t.__pc
        }
        return ~0U;
    }
     
     
    uint64_t MachOFile::entryAddrFromThreadCmd(const thread_command* cmd) const
    {
        assert(cmd->cmd == LC_UNIXTHREAD);
        const uint32_t* regs32 = (uint32_t*)(((char*)cmd) + 16);
        const uint64_t* regs64 = (uint64_t*)(((char*)cmd) + 16);
     
        uint32_t index = entryAddrRegisterIndexForThreadCmd();
        if (index == ~0U)
            return 0;
     
        return is64() ? regs64[index] : regs32[index];
    }
     
     
    void MachOFile::forEachSegment(void (^callback)(const SegmentInfo& info, bool& stop)) const
    {
        Diagnostics diag;
        const bool  intel32  = (this->cputype == CPU_TYPE_I386);
        __block uint32_t segIndex = 0;
        forEachLoadCommand(diag, ^(const load_command* cmd, bool& stop) {
            if ( cmd->cmd == LC_SEGMENT_64 ) {
                const segment_command_64* segCmd = (segment_command_64*)cmd;
                uint64_t sizeOfSections = segCmd->vmsize;
                uint8_t p2align = 0;
                const section_64* const sectionsStart = (section_64*)((char*)segCmd + sizeof(struct segment_command_64));
                const section_64* const sectionsEnd   = &sectionsStart[segCmd->nsects];
                for (const section_64* sect=sectionsStart; sect < sectionsEnd; ++sect) {
                    sizeOfSections = sect->addr + sect->size - segCmd->vmaddr;
                    if ( sect->align > p2align )
                        p2align = sect->align;
                }
                SegmentInfo info;
                info.fileOffset        = segCmd->fileoff;
                info.fileSize          = segCmd->filesize;
                info.vmAddr            = segCmd->vmaddr;
                info.vmSize            = segCmd->vmsize;
                info.sizeOfSections    = sizeOfSections;
                info.segName           = segCmd->segname;
                info.loadCommandOffset = (uint32_t)((uint8_t*)segCmd - (uint8_t*)this);
                info.protections       = segCmd->initprot;
                info.textRelocs        = false;
                info.readOnlyData      = ((segCmd->flags & SG_READ_ONLY) != 0);
                info.isProtected       = (segCmd->flags & SG_PROTECTED_VERSION_1) ? 1 : 0;
                info.hasZeroFill       = (segCmd->initprot == 3) && (segCmd->filesize < segCmd->vmsize);
                info.p2align           = p2align;
                info.segIndex          = segIndex;
                callback(info, stop);
                ++segIndex;
            }
            else if ( cmd->cmd == LC_SEGMENT ) {
                const segment_command* segCmd = (segment_command*)cmd;
                uint64_t sizeOfSections = segCmd->vmsize;
                uint8_t p2align = 0;
                bool  hasTextRelocs = false;
                const section* const sectionsStart = (section*)((char*)segCmd + sizeof(struct segment_command));
                const section* const sectionsEnd   = &sectionsStart[segCmd->nsects];
                for (const section* sect=sectionsStart; sect < sectionsEnd; ++sect) {
                    sizeOfSections = sect->addr + sect->size - segCmd->vmaddr;
                    if ( sect->align > p2align )
                        p2align = sect->align;
                    if ( sect->flags & (S_ATTR_EXT_RELOC|S_ATTR_LOC_RELOC) )
                        hasTextRelocs = true;
               }
                SegmentInfo info;
                info.fileOffset        = segCmd->fileoff;
                info.fileSize          = segCmd->filesize;
                info.vmAddr            = segCmd->vmaddr;
                info.vmSize            = segCmd->vmsize;
                info.sizeOfSections    = sizeOfSections;
                info.segName           = segCmd->segname;
                info.loadCommandOffset = (uint32_t)((uint8_t*)segCmd - (uint8_t*)this);
                info.protections       = segCmd->initprot;
                info.textRelocs        = intel32 && !info.writable() && hasTextRelocs;
                info.readOnlyData      = ((segCmd->flags & SG_READ_ONLY) != 0);
                info.isProtected       = (segCmd->flags & SG_PROTECTED_VERSION_1) ? 1 : 0;
                info.hasZeroFill       = (segCmd->initprot == 3) && (segCmd->filesize < segCmd->vmsize);
                info.p2align           = p2align;
                info.segIndex          = segIndex;
                callback(info, stop);
                ++segIndex;
            }
        });
        diag.assertNoError();   // any malformations in the file should have been caught by earlier validate() call
    }
     
    uint64_t MachOFile::preferredLoadAddress() const
    {
        __block uint64_t textVmAddr = 0;
        forEachSegment(^(const SegmentInfo& info, bool& stop) {
            if ( strcmp(info.segName, "__TEXT") == 0 ) {
                textVmAddr = info.vmAddr;
                stop = true;
            }
        });
        return textVmAddr;
    }
     
    void MachOFile::forEachSection(void (^callback)(const SectionInfo& sectInfo, bool malformedSectionRange, bool& stop)) const
    {
        Diagnostics diag;
        BLOCK_ACCCESSIBLE_ARRAY(char, sectNameCopy, 20);  // read as:  char sectNameCopy[20];
        const bool intel32 = (this->cputype == CPU_TYPE_I386);
        __block uint32_t segIndex = 0;
        forEachLoadCommand(diag, ^(const load_command* cmd, bool& stop) {
            SectionInfo sectInfo;
            if ( cmd->cmd == LC_SEGMENT_64 ) {
                const segment_command_64* segCmd = (segment_command_64*)cmd;
                uint64_t sizeOfSections = segCmd->vmsize;
                uint8_t p2align = 0;
                const section_64* const sectionsStart = (section_64*)((char*)segCmd + sizeof(struct segment_command_64));
                const section_64* const sectionsEnd   = &sectionsStart[segCmd->nsects];
                for (const section_64* sect=sectionsStart; sect < sectionsEnd; ++sect) {
                    sizeOfSections = sect->addr + sect->size - segCmd->vmaddr;
                    if ( sect->align > p2align )
                        p2align = sect->align;
                }
                sectInfo.segInfo.fileOffset        = segCmd->fileoff;
                sectInfo.segInfo.fileSize          = segCmd->filesize;
                sectInfo.segInfo.vmAddr            = segCmd->vmaddr;
                sectInfo.segInfo.vmSize            = segCmd->vmsize;
                sectInfo.segInfo.sizeOfSections    = sizeOfSections;
                sectInfo.segInfo.segName           = segCmd->segname;
                sectInfo.segInfo.loadCommandOffset = (uint32_t)((uint8_t*)segCmd - (uint8_t*)this);
                sectInfo.segInfo.protections       = segCmd->initprot;
                sectInfo.segInfo.textRelocs        = false;
                sectInfo.segInfo.readOnlyData      = ((segCmd->flags & SG_READ_ONLY) != 0);
                sectInfo.segInfo.isProtected       = (segCmd->flags & SG_PROTECTED_VERSION_1) ? 1 : 0;
                sectInfo.segInfo.p2align           = p2align;
                sectInfo.segInfo.segIndex          = segIndex;
                for (const section_64* sect=sectionsStart; !stop && (sect < sectionsEnd); ++sect) {
                    const char* sectName = sect->sectname;
                    if ( sectName[15] != '\0' ) {
                        strlcpy(sectNameCopy, sectName, 17);
                        sectName = sectNameCopy;
                    }
                    bool malformedSectionRange = (sect->addr < segCmd->vmaddr) || greaterThanAddOrOverflow(sect->addr, sect->size, segCmd->vmaddr + segCmd->filesize);
                    sectInfo.sectName       = sectName;
                    sectInfo.sectFileOffset = sect->offset;
                    sectInfo.sectFlags      = sect->flags;
                    sectInfo.sectAddr       = sect->addr;
                    sectInfo.sectSize       = sect->size;
                    sectInfo.sectAlignP2    = sect->align;
                    sectInfo.reserved1      = sect->reserved1;
                    sectInfo.reserved2      = sect->reserved2;
                    callback(sectInfo, malformedSectionRange, stop);
                }
                ++segIndex;
            }
            else if ( cmd->cmd == LC_SEGMENT ) {
                const segment_command* segCmd = (segment_command*)cmd;
                uint64_t sizeOfSections = segCmd->vmsize;
                uint8_t p2align = 0;
                bool  hasTextRelocs = false;
                const section* const sectionsStart = (section*)((char*)segCmd + sizeof(struct segment_command));
                const section* const sectionsEnd   = &sectionsStart[segCmd->nsects];
                for (const section* sect=sectionsStart; sect < sectionsEnd; ++sect) {
                    sizeOfSections = sect->addr + sect->size - segCmd->vmaddr;
                    if ( sect->align > p2align )
                        p2align = sect->align;
                    if ( sect->flags & (S_ATTR_EXT_RELOC|S_ATTR_LOC_RELOC) )
                        hasTextRelocs = true;
                }
                sectInfo.segInfo.fileOffset        = segCmd->fileoff;
                sectInfo.segInfo.fileSize          = segCmd->filesize;
                sectInfo.segInfo.vmAddr            = segCmd->vmaddr;
                sectInfo.segInfo.vmSize            = segCmd->vmsize;
                sectInfo.segInfo.sizeOfSections    = sizeOfSections;
                sectInfo.segInfo.segName           = segCmd->segname;
                sectInfo.segInfo.loadCommandOffset = (uint32_t)((uint8_t*)segCmd - (uint8_t*)this);
                sectInfo.segInfo.protections       = segCmd->initprot;
                sectInfo.segInfo.textRelocs        = intel32 && !sectInfo.segInfo.writable() && hasTextRelocs;
                sectInfo.segInfo.readOnlyData      = ((segCmd->flags & SG_READ_ONLY) != 0);
                sectInfo.segInfo.isProtected       = (segCmd->flags & SG_PROTECTED_VERSION_1) ? 1 : 0;
                sectInfo.segInfo.p2align           = p2align;
                sectInfo.segInfo.segIndex          = segIndex;
                for (const section* sect=sectionsStart; !stop && (sect < sectionsEnd); ++sect) {
                    const char* sectName = sect->sectname;
                    if ( sectName[15] != '\0' ) {
                        strlcpy(sectNameCopy, sectName, 17);
                        sectName = sectNameCopy;
                    }
                    bool malformedSectionRange = (sect->addr < segCmd->vmaddr) || greaterThanAddOrOverflow(sect->addr, sect->size, segCmd->vmaddr + segCmd->filesize);
                    sectInfo.sectName       = sectName;
                    sectInfo.sectFileOffset = sect->offset;
                    sectInfo.sectFlags      = sect->flags;
                    sectInfo.sectAddr       = sect->addr;
                    sectInfo.sectSize       = sect->size;
                    sectInfo.sectAlignP2    = sect->align;
                    sectInfo.reserved1      = sect->reserved1;
                    sectInfo.reserved2      = sect->reserved2;
                    callback(sectInfo, malformedSectionRange, stop);
                }
                ++segIndex;
            }
        });
        diag.assertNoError();   // any malformations in the file should have been caught by earlier validate() call
    }
     
    void MachOFile::forEachInterposingSection(Diagnostics& diag, void (^handler)(uint64_t vmOffset, uint64_t vmSize, bool& stop)) const
    {
        const unsigned ptrSize   = pointerSize();
        const unsigned entrySize = 2 * ptrSize;
        forEachSection(^(const MachOFile::SectionInfo& info, bool malformedSectionRange, bool &stop) {
            if ( ((info.sectFlags & SECTION_TYPE) == S_INTERPOSING) || ((strcmp(info.sectName, "__interpose") == 0) && ((strncmp(info.segInfo.segName, "__DATA", 6) == 0) || strncmp(info.segInfo.segName, "__AUTH", 6) == 0)) ) {
                if ( info.sectSize % entrySize != 0 ) {
                    diag.error("interposing section %s/%s has bad size", info.segInfo.segName, info.sectName);
                    stop = true;
                    return;
                }
                if ( malformedSectionRange ) {
                    diag.error("interposing section %s/%s extends beyond the end of the segment", info.segInfo.segName, info.sectName);
                    stop = true;
                    return;
                }
                if ( (info.sectAddr % ptrSize) != 0 ) {
                    diag.error("interposing section %s/%s is not pointer aligned", info.segInfo.segName, info.sectName);
                    stop = true;
                    return;
                }
                handler(info.sectAddr - preferredLoadAddress(), info.sectSize, stop);
            }
        });
    }
     
    bool MachOFile::isRestricted() const
    {
        __block bool result = false;
        forEachSection(^(const MachOFile::SectionInfo& info, bool malformedSectionRange, bool &stop) {
            if ( (strcmp(info.segInfo.segName, "__RESTRICT") == 0) && (strcmp(info.sectName, "__restrict") == 0) ) {
                result = true;
                stop = true;
            }
        });
        return result;
    }
     
    bool MachOFile::hasWeakDefs() const
    {
        return (this->flags & MH_WEAK_DEFINES);
    }
     
    bool MachOFile::usesWeakDefs() const
    {
        return (this->flags & MH_BINDS_TO_WEAK);
    }
     
    bool MachOFile::hasThreadLocalVariables() const
    {
        return (this->flags & MH_HAS_TLV_DESCRIPTORS);
    }
     
    static bool endsWith(const char* str, const char* suffix)
    {
        size_t strLen    = strlen(str);
        size_t suffixLen = strlen(suffix);
        if ( strLen < suffixLen )
            return false;
        return (strcmp(&str[strLen-suffixLen], suffix) == 0);
    }
     
    bool MachOFile::isSharedCacheEligiblePath(const char* dylibName) {
        return (   (strncmp(dylibName, "/usr/lib/", 9) == 0)
                || (strncmp(dylibName, "/System/Library/", 16) == 0)
                || (strncmp(dylibName, "/System/iOSSupport/usr/lib/", 27) == 0)
                || (strncmp(dylibName, "/System/iOSSupport/System/Library/", 34) == 0)
                || (strncmp(dylibName, "/Library/Apple/usr/lib/", 23) == 0)
                || (strncmp(dylibName, "/Library/Apple/System/Library/", 30) == 0)
                || (strncmp(dylibName, "/System/DriverKit/", 18) == 0));
    }
     
    static bool startsWith(const char* buffer, const char* valueToFind) {
        return strncmp(buffer, valueToFind, strlen(valueToFind)) == 0;
    }
     
    static bool platformExcludesSharedCache_macOS(const char* installName) {
        // Note: This function basically matches dontCache() from update dyld shared cache
     
        if ( startsWith(installName, "/usr/lib/system/introspection/") )
            return true;
        if ( startsWith(installName, "/System/Library/QuickTime/") )
            return true;
        if ( startsWith(installName, "/System/Library/Tcl/") )
            return true;
        if ( startsWith(installName, "/System/Library/Perl/") )
            return true;
        if ( startsWith(installName, "/System/Library/MonitorPanels/") )
            return true;
        if ( startsWith(installName, "/System/Library/Accessibility/") )
            return true;
        if ( startsWith(installName, "/usr/local/") )
            return true;
        if ( startsWith(installName, "/usr/lib/pam/") )
            return true;
        // We no longer support ROSP, so skip all paths which start with the special prefix
        if ( startsWith(installName, "/System/Library/Templates/Data/") )
            return true;
     
        // anything inside a .app bundle is specific to app, so should not be in shared cache
        if ( strstr(installName, ".app/") != NULL )
            return true;
     
        return false;
    }
     
    static bool platformExcludesSharedCache_iOS(const char* installName) {
        if ( strcmp(installName, "/System/Library/Caches/com.apple.xpc/sdk.dylib") == 0 )
            return true;
        if ( strcmp(installName, "/System/Library/Caches/com.apple.xpcd/xpcd_cache.dylib") == 0 )
            return true;
        return false;
    }
     
    // Returns true if the current platform requires that this install name be excluded from the shared cache
    // Note that this overrides any exclusion from anywhere else.
    static bool platformExcludesSharedCache(Platform platform, const char* installName) {
        if ( MachOFile::isSimulatorPlatform(platform) )
            return false;
        if ( (platform == dyld3::Platform::macOS) || (platform == dyld3::Platform::iOSMac) )
            return platformExcludesSharedCache_macOS(installName);
        // Everything else is based on iOS so just use that value
        return platformExcludesSharedCache_iOS(installName);
    }
     
     
    bool MachOFile::canBePlacedInDyldCache(const char* path, void (^failureReason)(const char*)) const
    {
     
        if ( !isSharedCacheEligiblePath(path) ) {
            // Dont spam the user with an error about paths when we know these are never eligible.
            return false;
        }
     
        // only dylibs can go in cache
        if ( this->filetype != MH_DYLIB ) {
            failureReason("Not MH_DYLIB");
            return false; // cannot continue, installName() will assert() if not a dylib
        }
     
     
        const char* dylibName = installName();
        if ( dylibName[0] != '/' ) {
            failureReason("install name not an absolute path");
            // Don't continue as we don't want to spam the log with errors we don't need.
            return false;
        }
        else if ( strcmp(dylibName, path) != 0 ) {
            failureReason("install path does not match install name");
            return false;
        }
        else if ( strstr(dylibName, "//") != 0 ) {
            failureReason("install name should not include //");
            return false;
        }
        else if ( strstr(dylibName, "./") != 0 ) {
            failureReason("install name should not include ./");
            return false;
        }
     
        __block bool platformExcludedFile = false;
        forEachSupportedPlatform(^(Platform platform, uint32_t minOS, uint32_t sdk) {
            if ( platformExcludedFile )
                return;
            if ( platformExcludesSharedCache(platform, dylibName) ) {
                platformExcludedFile = true;
                return;
            }
        });
        if ( platformExcludedFile ) {
            failureReason("install name is not shared cache eligible on platform");
            return false;
        }
     
        bool retval = true;
     
        // flat namespace files cannot go in cache
        if ( (this->flags & MH_TWOLEVEL) == 0 ) {
            retval = false;
            failureReason("Not built with two level namespaces");
        }
     
        // don't put debug variants into dyld cache
        if ( endsWith(path, "_profile.dylib") || endsWith(path, "_debug.dylib") || endsWith(path, "_profile") || endsWith(path, "_debug") || endsWith(path, "/CoreADI") ) {
            retval = false;
            failureReason("Variant image");
        }
     
        // dylib must have extra info for moving DATA and TEXT segments apart
        __block bool hasExtraInfo = false;
        __block bool hasDyldInfo = false;
        __block bool hasExportTrie = false;
        Diagnostics diag;
        forEachLoadCommand(diag, ^(const load_command* cmd, bool& stop) {
            if ( cmd->cmd == LC_SEGMENT_SPLIT_INFO )
                hasExtraInfo = true;
            if ( cmd->cmd == LC_DYLD_INFO_ONLY )
                hasDyldInfo = true;
            if ( cmd->cmd == LC_DYLD_EXPORTS_TRIE )
                hasExportTrie = true;
        });
        if ( !hasExtraInfo ) {
            retval = false;
            failureReason("Missing split seg info");
        }
        if ( !hasDyldInfo && !hasExportTrie ) {
            retval = false;
            failureReason("Old binary, missing dyld info or export trie");
        }
     
        // dylib can only depend on other dylibs in the shared cache
        __block bool allDepPathsAreGood = true;
        forEachDependentDylib(^(const char* loadPath, bool isWeak, bool isReExport, bool isUpward, uint32_t compatVersion, uint32_t curVersion, bool& stop) {
            // Skip weak links.  They are allowed to be missing
            if ( isWeak )
                return;
            if ( !isSharedCacheEligiblePath(loadPath) ) {
                allDepPathsAreGood = false;
                stop = true;
            }
        });
        if ( !allDepPathsAreGood ) {
            retval = false;
            failureReason("Depends on dylibs ineligable for dyld cache");
        }
     
        // dylibs with interposing info cannot be in cache
        if ( hasInterposingTuples() ) {
            retval = false;
            failureReason("Has interposing tuples");
        }
     
        // Temporarily kick out swift binaries out of dyld cache on watchOS simulators as they have missing split seg
        if ( (this->cputype == CPU_TYPE_I386) && builtForPlatform(Platform::watchOS_simulator) ) {
            if ( strncmp(dylibName, "/usr/lib/swift/", 15) == 0 ) {
                retval = false;
                failureReason("i386 swift binary");
            }
        }
     
        return retval;
    }
     
    #if BUILDING_APP_CACHE_UTIL
    bool MachOFile::canBePlacedInKernelCollection(const char* path, void (^failureReason)(const char*)) const
    {
        // only dylibs and the kernel itself can go in cache
        if ( this->filetype == MH_EXECUTE ) {
            // xnu
        } else if ( this->isKextBundle() ) {
            // kext's
        } else {
            failureReason("Not MH_KEXT_BUNDLE");
            return false;
        }
     
        if ( this->filetype == MH_EXECUTE ) {
            // xnu
     
            // two-level namespace binaries cannot go in cache
            if ( (this->flags & MH_TWOLEVEL) != 0 ) {
                failureReason("Built with two level namespaces");
                return false;
            }
     
            // xnu kernel cannot have a page zero
            __block bool foundPageZero = false;
            forEachSegment(^(const SegmentInfo &segmentInfo, bool &stop) {
                if ( strcmp(segmentInfo.segName, "__PAGEZERO") == 0 ) {
                    foundPageZero = true;
                    stop = true;
                }
            });
            if (foundPageZero) {
                failureReason("Has __PAGEZERO");
                return false;
            }
     
            // xnu must have an LC_UNIXTHREAD to point to the entry point
            __block bool foundMainLC = false;
            __block bool foundUnixThreadLC = false;
            Diagnostics diag;
            forEachLoadCommand(diag, ^(const load_command* cmd, bool& stop) {
                if ( cmd->cmd == LC_MAIN ) {
                    foundMainLC = true;
                    stop = true;
                }
                else if ( cmd->cmd == LC_UNIXTHREAD ) {
                    foundUnixThreadLC = true;
                }
            });
            if (foundMainLC) {
                failureReason("Found LC_MAIN");
                return false;
            }
            if (!foundUnixThreadLC) {
                failureReason("Expected LC_UNIXTHREAD");
                return false;
            }
     
            if (diag.hasError()) {
                failureReason("Error parsing load commands");
                return false;
            }
     
            // The kernel should be a static executable, not a dynamic one
            if ( !isStaticExecutable() ) {
                failureReason("Expected static executable");
                return false;
            }
     
            // The kernel must be built with -pie
            if ( !isPIE() ) {
                failureReason("Expected pie");
                return false;
            }
        }
     
        if ( isArch("arm64e") && isKextBundle() && !hasChainedFixups() ) {
            failureReason("Missing fixup information");
            return false;
        }
     
        // dylibs with interposing info cannot be in cache
        if ( hasInterposingTuples() ) {
            failureReason("Has interposing tuples");
            return false;
        }
     
        // Only x86_64 is allowed to have RWX segments
        if ( !isArch("x86_64") && !isArch("x86_64h") ) {
            __block bool foundBadSegment = false;
            forEachSegment(^(const SegmentInfo &info, bool &stop) {
                if ( (info.protections & (VM_PROT_WRITE | VM_PROT_EXECUTE)) == (VM_PROT_WRITE | VM_PROT_EXECUTE) ) {
                    failureReason("Segments are not allowed to be both writable and executable");
                    foundBadSegment = true;
                    stop = true;
                }
            });
            if ( foundBadSegment )
                return false;
        }
     
        return true;
    }
    #endif
     
    static bool platformExcludesPrebuiltClosure_macOS(const char* path) {
        // We no longer support ROSP, so skip all paths which start with the special prefix
        if ( startsWith(path, "/System/Library/Templates/Data/") )
            return true;
     
        // anything inside a .app bundle is specific to app, so should not get a prebuilt closure
        if ( strstr(path, ".app/") != NULL )
            return true;
     
        return false;
    }
     
    static bool platformExcludesPrebuiltClosure_iOS(const char* path) {
        if ( strcmp(path, "/System/Library/Caches/com.apple.xpc/sdk.dylib") == 0 )
            return true;
        if ( strcmp(path, "/System/Library/Caches/com.apple.xpcd/xpcd_cache.dylib") == 0 )
            return true;
        return false;
    }
     
    // Returns true if the current platform requires that this install name be excluded from the shared cache
    // Note that this overrides any exclusion from anywhere else.
    static bool platformExcludesPrebuiltClosure(Platform platform, const char* path) {
        if ( MachOFile::isSimulatorPlatform(platform) )
            return false;
        if ( (platform == dyld3::Platform::macOS) || (platform == dyld3::Platform::iOSMac) )
            return platformExcludesPrebuiltClosure_macOS(path);
        // Everything else is based on iOS so just use that value
        return platformExcludesPrebuiltClosure_iOS(path);
    }
     
    bool MachOFile::canHavePrecomputedDlopenClosure(const char* path, void (^failureReason)(const char*)) const
    {
        __block bool retval = true;
     
        // only dylibs can go in cache
        if ( (this->filetype != MH_DYLIB) && (this->filetype != MH_BUNDLE) ) {
            retval = false;
            failureReason("not MH_DYLIB or MH_BUNDLE");
        }
     
        // flat namespace files cannot go in cache
        if ( (this->flags & MH_TWOLEVEL) == 0 ) {
            retval = false;
            failureReason("not built with two level namespaces");
        }
     
        // can only depend on other dylibs with absolute paths
        __block bool allDepPathsAreGood = true;
        forEachDependentDylib(^(const char* loadPath, bool isWeak, bool isReExport, bool isUpward, uint32_t compatVersion, uint32_t curVersion, bool& stop) {
            if ( loadPath[0] != '/' ) {
                allDepPathsAreGood = false;
                stop = true;
            }
        });
        if ( !allDepPathsAreGood ) {
            retval = false;
            failureReason("depends on dylibs that are not absolute paths");
        }
     
        __block bool platformExcludedFile = false;
        forEachSupportedPlatform(^(Platform platform, uint32_t minOS, uint32_t sdk) {
            if ( platformExcludedFile )
                return;
            if ( platformExcludesPrebuiltClosure(platform, path) ) {
                platformExcludedFile = true;
                return;
            }
        });
        if ( platformExcludedFile ) {
            failureReason("file cannot get a prebuilt closure on this platform");
            return false;
        }
     
        // dylibs with interposing info cannot have dlopen closure pre-computed
        if ( hasInterposingTuples() ) {
            retval = false;
            failureReason("has interposing tuples");
        }
     
        // special system dylib overrides cannot have closure pre-computed
        if ( strncmp(path, "/usr/lib/system/introspection/", 30) == 0 ) {
            retval = false;
            failureReason("override of OS dylib");
        }
     
        return retval;
    }
     
    bool MachOFile::hasInterposingTuples() const
    {
        __block bool hasInterposing = false;
        Diagnostics diag;
        forEachInterposingSection(diag, ^(uint64_t vmOffset, uint64_t vmSize, bool &stop) {
            hasInterposing = true;
            stop = true;
        });
        return hasInterposing;
    }
     
    bool MachOFile::isFairPlayEncrypted(uint32_t& textOffset, uint32_t& size) const
    {
        if ( const encryption_info_command* encCmd = findFairPlayEncryptionLoadCommand() ) {
           if ( encCmd->cryptid == 1 ) {
                // Note: cryptid is 0 in just-built apps.  The AppStore sets cryptid to 1
                textOffset = encCmd->cryptoff;
                size       = encCmd->cryptsize;
                return true;
            }
        }
        textOffset = 0;
        size = 0;
        return false;
    }
     
    bool MachOFile::canBeFairPlayEncrypted() const
    {
        return (findFairPlayEncryptionLoadCommand() != nullptr);
    }
     
    const encryption_info_command* MachOFile::findFairPlayEncryptionLoadCommand() const
    {
        __block const encryption_info_command* result = nullptr;
        Diagnostics diag;
        forEachLoadCommand(diag, ^(const load_command* cmd, bool& stop) {
             if ( (cmd->cmd == LC_ENCRYPTION_INFO) || (cmd->cmd == LC_ENCRYPTION_INFO_64) ) {
                result = (encryption_info_command*)cmd;
                stop = true;
            }
        });
        if ( diag.noError() )
            return result;
        else
            return nullptr;
    }
     
     
    bool MachOFile::hasLoadCommand(uint32_t cmdNum) const
    {
        __block bool hasLC = false;
        Diagnostics diag;
        forEachLoadCommand(diag, ^(const load_command* cmd, bool& stop) {
            if ( cmd->cmd == cmdNum ) {
                hasLC = true;
                stop = true;
            }
        });
        return hasLC;
    }
     
    bool MachOFile::allowsAlternatePlatform() const
    {
        __block bool result = false;
        forEachSection(^(const SectionInfo& info, bool malformedSectionRange, bool& stop) {
            if ( (strcmp(info.sectName, "__allow_alt_plat") == 0) && (strncmp(info.segInfo.segName, "__DATA", 6) == 0) ) {
                result = true;
                stop = true;
            }
        });
        return result;
    }
     
    bool MachOFile::hasChainedFixups() const
    {
    #if SUPPORT_ARCH_arm64e
        // arm64e always uses chained fixups
        if ( (this->cputype == CPU_TYPE_ARM64) && (this->maskedCpuSubtype() == CPU_SUBTYPE_ARM64E) ) {
            // Not all binaries have fixups at all so check for the load commands
            return hasLoadCommand(LC_DYLD_INFO_ONLY) || hasLoadCommand(LC_DYLD_CHAINED_FIXUPS);
        }
    #endif
        return hasLoadCommand(LC_DYLD_CHAINED_FIXUPS);
    }
     
    bool MachOFile::hasChainedFixupsLoadCommand() const
    {
        return hasLoadCommand(LC_DYLD_CHAINED_FIXUPS);
    }
     
    bool MachOFile::hasOpcodeFixups() const
    {
        return hasLoadCommand(LC_DYLD_INFO_ONLY) || hasLoadCommand(LC_DYLD_INFO) ;
    }
     
    uint64_t MachOFile::read_uleb128(Diagnostics& diag, const uint8_t*& p, const uint8_t* end)
    {
        uint64_t result = 0;
        int         bit = 0;
        do {
            if ( p == end ) {
                diag.error("malformed uleb128");
                break;
            }
            uint64_t slice = *p & 0x7f;
     
            if ( bit > 63 ) {
                diag.error("uleb128 too big for uint64");
                break;
            }
            else {
                result |= (slice << bit);
                bit += 7;
            }
        }
        while (*p++ & 0x80);
        return result;
    }
     
     
    int64_t MachOFile::read_sleb128(Diagnostics& diag, const uint8_t*& p, const uint8_t* end)
    {
        int64_t  result = 0;
        int      bit = 0;
        uint8_t  byte = 0;
        do {
            if ( p == end ) {
                diag.error("malformed sleb128");
                break;
            }
            byte = *p++;
            result |= (((int64_t)(byte & 0x7f)) << bit);
            bit += 7;
        } while (byte & 0x80);
        // sign extend negative numbers
        if ( ((byte & 0x40) != 0) && (bit < 64) )
            result |= (~0ULL) << bit;
        return result;
    }
     
     
    const MachOFile* MachOFile::compatibleSlice(Diagnostics& diag, const void* fileContent, size_t contentSize, const char* path, Platform platform, bool isOSBinary, const GradedArchs& archs)
    {
        const MachOFile* mf = nullptr;
        if ( const dyld3::FatFile* ff = dyld3::FatFile::isFatFile(fileContent) ) {
            uint64_t  sliceOffset;
            uint64_t  sliceLen;
            bool      missingSlice;
            if ( ff->isFatFileWithSlice(diag, contentSize, archs, isOSBinary, sliceOffset, sliceLen, missingSlice) ) {
                mf = (MachOFile*)((long)fileContent + sliceOffset);
            }
            else {
                char strBuf[256];
                diag.error("fat file, but missing compatible architecture (have '%s', need '%s')", ff->archNames(strBuf), archs.name());
                return nullptr;
            }
        }
        else {
            mf = (MachOFile*)fileContent;
        }
     
        if ( !mf->hasMachOMagic() || !mf->isMachO(diag, contentSize) ) {
            diag.error("not a mach-o file");
            return nullptr;
        }
     
        if ( archs.grade(mf->cputype, mf->cpusubtype, isOSBinary) == 0 ) {
            diag.error("mach-o file, but is an incompatible architecture (have '%s', need '%s')", mf->archName(), archs.name());
            return nullptr;
        }
     
        if ( !mf->loadableIntoProcess(platform, path) ) {
            __block Platform havePlatform = Platform::unknown;
            mf->forEachSupportedPlatform(^(Platform aPlat, uint32_t minOS, uint32_t sdk) {
                havePlatform = aPlat;
            });
            diag.error("mach-o file (%s), but incompatible platform (have '%s', need '%s')", path, MachOFile::platformName(havePlatform), MachOFile::platformName(platform));
            return nullptr;
        }
     
        return mf;
    }
     
     
    } // namespace dyld3
    }

    Cette fois-ci, le même nom a été retrouvé dans un dépôt de marque.

    La demande de marque n'a pas été officiellement déposée par Apple, mais il est courant pour les grandes entreprises de demander des marques sous des noms de société uniques - comme Realityo Systems LLC, dans ce cas - dans l'État du Delaware dans le seul but de maintenir anonymat.

    La demande de marque est la dernière preuve qu'Apple est sur le point d'annoncer son casque après de longues rumeurs. Cela fait suite à la nouvelle du début du mois selon laquelle le conseil d'administration de la société aurait essayé l'appareil portable, ce qui est une pratique courante avant un lancement public. En janvier, les médias américains ont rapporté que le casque devait initialement sortir fin 2022 après une annonce lors de la conférence des développeurs de la société, mais cela pourrait être retardé en raison de problèmes de développement. La sortie du casque pourrait désormais avoir lieu en 2023, selon le journaliste américain Parker Ortolani.

    Nom : parker.png
Affichages : 839
Taille : 31,9 Ko

    La documentation de la marque fait référence au « matériel informatique portable » et concernerait « la conception et le développement de matériel informatique, de logiciels, de périphériques et de jeux informatiques et vidéo ». La conception et la fonctionnalité du casque d'Apple ont été la source de nombreuses spéculations au fil des ans, mais la plupart des rapports suggèrent qu'il sera en mesure d'offrir une combinaison d'expériences de réalité virtuelle et de réalité augmentée, vous immergeant dans du contenu virtuel ainsi qu'en apportant des couches d'éléments virtuels sur des environnements du monde réel.

    Il est important de noter que la marque RealityOS n'a pas été demandée par Apple elle-même, mais a plutôt été enregistrée par une société appelée "Realityo Systems LLC". Mais Ortolani rapporte que Realityo ne semble pas avoir de présence publique, suggérant qu'il s'agit d'une société-écran utilisée par la société technologique basée à Cupertino pour cacher son implication. Apple aurait adopté la même approche dans le passé, ont rapporté certains médias, en utilisant une société-écran appelée "Yosemite Research LLC" pour enregistrer des noms de mise à jour macOS comme Yosemite, Big Sur et Monterey.

    Realityo Systems LLC et Yosemite Research LLC sont enregistrés à la même adresse, ce qui implique fortement qu'Apple est derrière eux. Les dépôts RealityOS pour une marque commerciale et une marque de service ne répertorient aucun exemple d'utilisation du nom en public (ce qui signifie que le produit auquel ils sont associés n'a pas encore été publié), et ce sont également les deux seules applications associées à Realityo Systems. LLC.

    Ces éléments ont été découverts quelques jours seulement avant qu'Apple ne lance sa conférence annuelle des développeurs qui aura lieu le 6 juin, et sont répertoriés avec des dates limites du 8 juin, ce qui laisse supposer que nous pourrions voir le casque annoncé lors du discours d'ouverture d'Apple. Mais Mark Gurman de Bloomberg note que le moment de la date du 8 juin est probablement une coïncidence et coïncide avec un délai légal clef qui intervient six mois après le dépôt initial d'une marque. « Peut-être que nous le verrons [au WWDC] », a tweeté Gurman, « mais la demande de marque n'en est pas la preuve ».

    Sources : Parker Ortolani, RealityOS, Mark Gurnman

    Et vous ?

    Quelle lecture en faites-vous ?

    Voir aussi :

    Réalité virtuelle : le casque VR d'Apple pourrait coûter 3000 dollars, comporter des écrans 8K et plus d'une douzaine de caméras
    Apple : bientôt des casques utilisant le port Lightening sur les iDevices ? Cupertino a ajouté des spécificités à son programme MFI
    Contribuez au club : Corrections, suggestions, critiques, ... : Contactez le service news et Rédigez des actualités

Discussions similaires

  1. Réponses: 8
    Dernier message: 28/10/2016, 07h21
  2. [AC-2007] appel de fonction illegal dans un formulaire qui fait des call successifs.
    Par benji971 dans le forum VBA Access
    Réponses: 3
    Dernier message: 04/08/2016, 14h17
  3. Réponses: 2
    Dernier message: 18/01/2008, 11h59
  4. "Trigger" sur une insertion : référence au nouveau tuple
    Par samworld dans le forum MS SQL Server
    Réponses: 1
    Dernier message: 26/06/2007, 22h27

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo