Loading...
   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
/*
 * Copyright (c) 2021 Apple Inc. All rights reserved.
 *
 * @APPLE_LICENSE_HEADER_START@
 *
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 *
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 *
 * @APPLE_LICENSE_HEADER_END@
 */

#include <utility>

#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include <assert.h>

#include <TargetConditionals.h>
#if !TARGET_OS_EXCLAVEKIT
  #include <unistd.h>
#endif

#include "Array.h"
#include "Header.h"
#include "Architecture.h"
#include "Misc.h"
#include "Policy.h"
#include "LoggingStub.h"

using mach_o::Architecture;
using mach_o::Platform;
using mach_o::PlatformAndVersions;
using mach_o::Policy;

namespace mach_o {

//
// MARK: --- methods that read mach_header ---
//

bool Header::hasMachOMagic() const
{
    return ((mh.magic == MH_MAGIC) || (mh.magic == MH_MAGIC_64));
}

bool Header::hasMachOBigEndianMagic() const
{
    return ((mh.magic == MH_CIGAM) || (mh.magic == MH_CIGAM_64));
}

bool Header::is64() const
{
    return (mh.magic == MH_MAGIC_64);
}

uint32_t Header::machHeaderSize() const
{
    return is64() ? sizeof(mach_header_64) : sizeof(mach_header);
}

uint32_t Header::pointerSize() const
{
    if ( mh.magic == MH_MAGIC_64 )
        return 8;
    else
        return 4;
}

bool Header::uses16KPages() const
{
    switch ( mh.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 mh.cpusubtype == CPU_SUBTYPE_ARM_V7K;
        default:
            return false;
    }
}

bool Header::isArch(const char* aName) const
{
    return (strcmp(aName, this->archName()) == 0);
}

const char* Header::archName() const
{
    return Architecture(&mh).name();
}

Architecture Header::arch() const
{
    return Architecture(&mh);
}

bool Header::inDyldCache() const
{
    return (mh.flags & MH_DYLIB_IN_CACHE);
}

bool Header::isDyldManaged() const
{
    switch ( mh.filetype ) {
        case MH_BUNDLE:
        case MH_EXECUTE:
        case MH_DYLIB:
            return ((mh.flags & MH_DYLDLINK) != 0);
        default:
            break;
    }
    return false;
}

bool Header::isDylib() const
{
    return (mh.filetype == MH_DYLIB);
}

bool Header::isBundle() const
{
    return (mh.filetype == MH_BUNDLE);
}

bool Header::isMainExecutable() const
{
    return (mh.filetype == MH_EXECUTE);
}

bool Header::isDynamicExecutable() const
{
    if ( mh.filetype != MH_EXECUTE )
        return false;

    // static executables do not have dyld load command
    return hasLoadCommand(LC_LOAD_DYLINKER);
}

bool Header::isKextBundle() const
{
    return (mh.filetype == MH_KEXT_BUNDLE);
}

bool Header::isObjectFile() const
{
    return (mh.filetype == MH_OBJECT);
}

bool Header::isFileSet() const
{
    return (mh.filetype == MH_FILESET);
}

bool Header::isPIE() const
{
    return (mh.flags & MH_PIE);
}

bool Header::isPreload() const
{
    return (mh.filetype == MH_PRELOAD);
}

bool Header::hasWeakDefs() const
{
    return (mh.flags & MH_WEAK_DEFINES);
}

bool Header::usesWeakDefs() const
{
    return (mh.flags & MH_BINDS_TO_WEAK);
}

bool Header::hasThreadLocalVariables() const
{
    return (mh.flags & MH_HAS_TLV_DESCRIPTORS);
}

const Header* Header::isMachO(std::span<const uint8_t> content)
{
    if ( content.size() < sizeof(mach_header) )
        return nullptr;

    const Header* mh = (const Header*)content.data();
    if ( mh->hasMachOMagic() )
        return mh;
    return nullptr;
}

bool Header::mayHaveTextFixups() const
{
    // only i386 binaries support text fixups
    if ( mh.cputype == CPU_TYPE_I386 )
        return true;
    // and x86_64 kext bundles
    if ( isKextBundle() && (mh.cputype == CPU_TYPE_X86_64) )
        return true;
    return false;
}

bool Header::hasSubsectionsViaSymbols() const
{
    return (this->mh.flags & MH_SUBSECTIONS_VIA_SYMBOLS) != 0;
}

bool Header::noReexportedDylibs() const
{
    return (this->mh.flags & MH_NO_REEXPORTED_DYLIBS) != 0;
}

bool Header::isAppExtensionSafe() const
{
    return (this->mh.flags & MH_APP_EXTENSION_SAFE) != 0;
}

bool Header::isSimSupport() const
{
    return (this->mh.flags & MH_SIM_SUPPORT) != 0;
}


//
// MARK: --- methods for validating mach-o content ---
//

PlatformAndVersions Header::platformAndVersions() const
{
    // should be one platform load command (exception is zippered dylibs)
    __block PlatformAndVersions pvs;
    forEachPlatformLoadCommand(^(Platform platform, Version32 minOS, Version32 sdk) {
        Error err = pvs.zip({ platform, minOS, sdk });
        assert(err.noError());
    });
    return pvs;
}

Error Header::validSemanticsPlatform() const
{
    // should be one platform load command (exception is zippered dylibs)
    __block PlatformAndVersions pvs;
    __block Error           badPlatform;
    forEachPlatformLoadCommand(^(Platform platform, Version32 minOS, Version32 sdk) {
        if ( badPlatform.hasError() ) return;

        if ( Error err = platform.valid() ) {
            badPlatform = std::move(err);
            return;
        }
        badPlatform = pvs.zip({ platform, minOS, sdk });
    });
    if ( badPlatform )
        return std::move(badPlatform);

#if BUILDING_MACHO_WRITER
    if ( pvs.platform.empty() )
        return Error::none(); // allow empty platform in static linker
#endif

    return pvs.platform.valid();
}

Error Header::valid(uint64_t fileSize) const
{
    if ( fileSize < sizeof(mach_header) )
        return Error("file is too short");

    if ( !hasMachOMagic() )
        return Error("not a mach-o file (start is no MH_MAGIC[_64])");

    if ( Error err = validStructureLoadCommands(fileSize) )
        return err;

    if ( Error err = validSemanticsPlatform() )
        return err;

    // create policy object
    Policy policy(arch(), platformAndVersions(), mh.filetype, false);

    if ( Error err = validSemanticsUUID(policy) )
        return err;

    if ( Error err = validSemanticsInstallName(policy) )
        return err;

    if ( Error err = validSemanticsDependents(policy) )
        return err;

    if ( Error err = validSemanticsRPath(policy) )
        return err;

    if ( Error err = validSemanticsSegments(policy, fileSize) )
        return err;

    if ( Error err = validSemanticsLinkerOptions(policy) )
        return err;

    if ( isMainExecutable() ) {
        if ( Error err = validSemanticsMain(policy) )
            return err;
    }

    return Error::none();
}

static Error stringOverflow(const load_command* cmd, uint32_t index, uint32_t strOffset)
{
    if ( strOffset >= cmd->cmdsize )
        return Error("load command #%d string offset (%u) outside its size (%u)", index, strOffset, cmd->cmdsize);

    const char* str = (char*)cmd + strOffset;
    const char* end = (char*)cmd + cmd->cmdsize;
    for ( const char* s = str; s < end; ++s ) {
        if ( *s == '\0' ) {
            return Error::none();
        }
    }
    return Error("load command #%d string extends beyond end of load command", index);
}

Error Header::validStructureLoadCommands(uint64_t fileSize) const
{
    // check load command don't exceed file length
    const uint64_t headerAndLCSize = mh.sizeofcmds + machHeaderSize();
    if ( headerAndLCSize > fileSize ) {
        return Error("load commands length (%llu) exceeds length of file (%llu)", headerAndLCSize, fileSize);
    }

    // check for reconized filetype
    switch ( mh.filetype ) {
        case MH_EXECUTE:
        case MH_DYLIB:
        case MH_DYLINKER:
        case MH_BUNDLE:
        case MH_KEXT_BUNDLE:
        case MH_FILESET:
        case MH_PRELOAD:
        case MH_OBJECT:
            break;
        default:
            return Error("unknown filetype %d", mh.filetype);
    }

    // walk all load commands and sanity check them
    __block int   index = 1;
    __block Error lcError;
    auto          lcChecker = ^(const load_command* cmd, bool& stop) {
        const dylib_command*         dylibCmd;
        const rpath_command*         rpathCmd;
        const sub_umbrella_command*  umbrellaCmd;
        const sub_client_command*    clientCmd;
        const sub_library_command*   libraryCmd;
        const build_version_command* buildVersCmd;
        const segment_command*       segCmd;
        const segment_command_64*    seg64Cmd;
        const fileset_entry_command* fileSetCmd;
        switch ( cmd->cmd ) {
            case LC_ID_DYLIB:
            case LC_LOAD_DYLIB:
            case LC_LOAD_WEAK_DYLIB:
            case LC_REEXPORT_DYLIB:
            case LC_LOAD_UPWARD_DYLIB:
                dylibCmd = (dylib_command*)cmd;
                lcError  = stringOverflow(cmd, index, dylibCmd->dylib.name.offset);
                break;
            case LC_RPATH:
                rpathCmd = (rpath_command*)cmd;
                lcError  = stringOverflow(cmd, index, rpathCmd->path.offset);
                break;
            case LC_SUB_UMBRELLA:
                umbrellaCmd = (sub_umbrella_command*)cmd;
                lcError     = stringOverflow(cmd, index, umbrellaCmd->sub_umbrella.offset);
                break;
            case LC_SUB_CLIENT:
                clientCmd = (sub_client_command*)cmd;
                lcError   = stringOverflow(cmd, index, clientCmd->client.offset);
                break;
            case LC_SUB_LIBRARY:
                libraryCmd = (sub_library_command*)cmd;
                lcError    = stringOverflow(cmd, index, libraryCmd->sub_library.offset);
                break;
            case LC_SYMTAB:
                if ( cmd->cmdsize != sizeof(symtab_command) )
                    lcError = Error("load command #%d LC_SYMTAB size wrong", index);
                break;
            case LC_DYSYMTAB:
                if ( cmd->cmdsize != sizeof(dysymtab_command) )
                    lcError = Error("load command #%d LC_DYSYMTAB size wrong", index);
                break;
            case LC_SEGMENT_SPLIT_INFO:
                if ( cmd->cmdsize != sizeof(linkedit_data_command) )
                    lcError = Error("load command #%d LC_SEGMENT_SPLIT_INFO size wrong", index);
                break;
            case LC_ATOM_INFO:
                if ( cmd->cmdsize != sizeof(linkedit_data_command) )
                    lcError = Error("load command #%d LC_ATOM_INFO size wrong", index);
                break;
            case LC_FUNCTION_STARTS:
                if ( cmd->cmdsize != sizeof(linkedit_data_command) )
                    lcError = Error("load command #%d LC_FUNCTION_STARTS size wrong", index);
                break;
            case LC_DYLD_EXPORTS_TRIE:
                if ( cmd->cmdsize != sizeof(linkedit_data_command) )
                    lcError = Error("load command #%d LC_DYLD_EXPORTS_TRIE size wrong", index);
                break;
            case LC_DYLD_CHAINED_FIXUPS:
                if ( cmd->cmdsize != sizeof(linkedit_data_command) )
                    lcError = Error("load command #%d LC_DYLD_CHAINED_FIXUPS size wrong", index);
                break;
            case LC_ENCRYPTION_INFO:
                if ( cmd->cmdsize != sizeof(encryption_info_command) )
                    lcError = Error("load command #%d LC_ENCRYPTION_INFO size wrong", index);
                break;
            case LC_ENCRYPTION_INFO_64:
                if ( cmd->cmdsize != sizeof(encryption_info_command_64) )
                    lcError = Error("load command #%d LC_ENCRYPTION_INFO_64 size wrong", index);
                break;
            case LC_DYLD_INFO:
            case LC_DYLD_INFO_ONLY:
                if ( cmd->cmdsize != sizeof(dyld_info_command) )
                    lcError = Error("load command #%d LC_DYLD_INFO_ONLY size wrong", index);
                break;
            case LC_VERSION_MIN_MACOSX:
            case LC_VERSION_MIN_IPHONEOS:
            case LC_VERSION_MIN_TVOS:
            case LC_VERSION_MIN_WATCHOS:
                if ( cmd->cmdsize != sizeof(version_min_command) )
                    lcError = Error("load command #%d LC_VERSION_MIN_* size wrong", index);
                break;
            case LC_UUID:
                if ( cmd->cmdsize != sizeof(uuid_command) )
                    lcError = Error("load command #%d LC_UUID size wrong", index);
                break;
            case LC_BUILD_VERSION:
                buildVersCmd = (build_version_command*)cmd;
                if ( cmd->cmdsize != (sizeof(build_version_command) + buildVersCmd->ntools * sizeof(build_tool_version)) )
                    lcError = Error("load command #%d LC_BUILD_VERSION size wrong", index);
                break;
            case LC_MAIN:
                if ( cmd->cmdsize != sizeof(entry_point_command) )
                    lcError = Error("load command #%d LC_MAIN size wrong", index);
                break;
            case LC_SEGMENT:
                segCmd = (segment_command*)cmd;
                if ( cmd->cmdsize != (sizeof(segment_command) + segCmd->nsects * sizeof(section)) )
                    lcError = Error("load command #%d LC_SEGMENT size does not match number of sections", index);
                break;
            case LC_SEGMENT_64:
                seg64Cmd = (segment_command_64*)cmd;
                if ( cmd->cmdsize != (sizeof(segment_command_64) + seg64Cmd->nsects * sizeof(section_64)) )
                    lcError = Error("load command #%d LC_SEGMENT_64 size does not match number of sections", index);
                break;
            case LC_FILESET_ENTRY:
                fileSetCmd = (fileset_entry_command*)cmd;
                lcError    = stringOverflow(cmd, index, fileSetCmd->entry_id.offset);
                break;
            default:
                if ( cmd->cmd & LC_REQ_DYLD )
                    lcError = Error("load command #%d unknown required load command 0x%08X", index, cmd->cmd);
                break;
        }
        ++index;
        if ( lcError )
            stop = true;
    };
    if ( Error err = this->forEachLoadCommand(lcChecker) )
        return err;
    if ( lcError )
        return std::move(lcError);
    /*
    // check load commands fit in TEXT segment
    if ( this->isDyldManaged() ) {
        __block bool foundTEXT = false;
        __block Error segError;
        forEachSegment(^(const SegmentInfo& segInfo, bool& stop) {
            if ( strcmp(segInfo.segName, "__TEXT") == 0 ) {
                foundTEXT = true;
                if ( headerAndLCSize > segInfo.fileSize ) {
                    segError = Error("load commands (%llu) exceed length of __TEXT segment (%llu)", headerAndLCSize, segInfo.fileSize);
                }
                if ( segInfo.fileOffset != 0 ) {
                    segError = Error("__TEXT segment not start of mach-o (%llu)", segInfo.fileOffset);
                }
                stop = true;
            }
        });
        if ( segError )
            return std::move(segError);
        if ( !foundTEXT ) {
            return Error("missing __TEXT segment");
        }
    }
*/
    return Error::none();
}


Error Header::validSemanticsUUID(const Policy& policy) const
{
    // should have at most one LC_UUID
    __block unsigned uuidCount = 0;
    forEachLoadCommandSafe(^(const load_command* cmd, bool& stop) {
        if ( cmd->cmd == LC_UUID )
            ++uuidCount;
    });
    if ( uuidCount > 1 )
        return Error("too many LC_UUID load commands");
    if ( (uuidCount == 0) && policy.enforceHasUUID() )
        return Error("missing LC_UUID load command");

    return Error::none();
}

Error Header::validSemanticsInstallName(const Policy& policy) const
{
    __block const char* installName = nullptr;
    __block int         foundCount  = 0;
    forEachLoadCommandSafe(^(const load_command* cmd, bool& stop) {
        if ( cmd->cmd == LC_ID_DYLIB ) {
            const dylib_command* dylibCmd = (dylib_command*)cmd;
            installName                   = (char*)dylibCmd + dylibCmd->dylib.name.offset;
            ++foundCount;
        }
    });
    if ( foundCount > 1 )
        return Error("multiple LC_ID_DYLIB found");

    if ( this->isDylib() ) {
        if ( installName == nullptr )
            return Error("MH_DYLIB is missing LC_ID_DYLIB");
#if 0 // FIXME: need path plumbed down
        if ( policy.enforceInstallNamesAreRealPaths() ) {
            // new binary, so check that part after @xpath/ is real (not symlinks)
            if ( (strncmp(installName, "@loader_path/", 13) == 0) || (strncmp(installName, "@executable_path/", 17) == 0) ) {
                if ( const char* s = strchr(installName, '/') ) {
                    while (strncmp(s, "/..", 3) == 0)
                        s += 3;
                    const char* trailingInstallPath = s;
                    const char* trailingRealPath = &path[strlen(path)-strlen(trailingInstallPath)];
                    if ( strcmp(trailingRealPath, trailingInstallPath) != 0 ) {
                        Error("install name '%s' contains symlinks", installName);
                    }
                }
            }
        }
#endif
    }
    else {
        if ( installName != nullptr )
            return Error("found LC_ID_DYLIB found in non-MH_DYLIB");
    }

    return Error::none();
}

Error Header::validSemanticsDependents(const Policy& policy) const
{
    // gather info
    __block Error dupDepError;
    __block int   depCount = 0;
    const char*   depPathsBuffer[256];
    const char**  depPaths = depPathsBuffer;
    const bool    enforceNoDupDylibs = policy.enforceNoDuplicateDylibs();
    const bool    hasWarningHandler = mach_o::hasWarningHandler();
    // don't use forEachDependentDylib, because it synthesizes libSystem.dylib
    forEachLoadCommandSafe(^(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;
                if ( (depCount < 256) && ( enforceNoDupDylibs || hasWarningHandler ) ) {
                    for ( int i = 0; i < depCount; ++i ) {
                        if ( strcmp(loadPath, depPaths[i]) == 0 ) {
                            if ( enforceNoDupDylibs ) {
                                dupDepError = Error("duplicate dependent dylib '%s'", loadPath);
                                stop        = true;
                            } else
                                warning(this, "duplicate dependent dylib are deprecated ('%s')", loadPath);
                        }
                    }
                    depPaths[depCount] = loadPath;
                }
                ++depCount;
            } break;
        }
    });
    if ( dupDepError )
        return std::move(dupDepError);

    // all new binaries must link with something
    if ( this->isDyldManaged() && policy.enforceHasLinkedDylibs() && (depCount == 0) ) {
        // except for dylibs in libSystem.dylib which are ok to link with nothing (they are on bottom)
        const char* libSystemDir   = this->builtForPlatform(Platform::driverKit, true) ? "/System/DriverKit/usr/lib/system/" : "/usr/lib/system/";
        const char* installName    = this->installName();
        bool        isNotLibSystem = (installName == nullptr) || (strncmp(installName, libSystemDir, strlen(libSystemDir)) != 0);
        if ( isNotLibSystem )
            return Error("missing LC_LOAD_DYLIB (must link with at least libSystem.dylib)");
    }
    return Error::none();
}

Error Header::validSemanticsRPath(const Policy& policy) const
{
    const bool enforceNoDupRPath = policy.enforceNoDuplicateRPaths();
    if ( !enforceNoDupRPath && !hasWarningHandler() )
        return Error::none();

    __block Error dupRPathError;
    __block int   rpathCount = 0;
    const char*   rpathsBuffer[64];
    const char**  rpaths = rpathsBuffer;
    forEachRPath(^(const char* rPath, bool& stop) {
        if ( rpathCount < 64 ) {
            for ( int i = 0; i < rpathCount; ++i ) {
                if ( strcmp(rPath, rpaths[i]) == 0 ) {
                    if ( enforceNoDupRPath ) {
                        dupRPathError = Error("duplicate LC_RPATH '%s'", rPath);
                        stop          = true;
                    } else
                        warning(this, "duplicate LC_RPATH are deprecated ('%s')", rPath);
                }
            }
            rpaths[rpathCount] = rPath;
        }
        ++rpathCount;
    });
    return std::move(dupRPathError);
}

#if !TARGET_OS_EXCLAVEKIT
template <typename SG, typename SC>
Error Header::validSegment(const Policy& policy, uint64_t wholeFileSize, const SG* seg) const
{
    if ( greaterThanAddOrOverflow(seg->fileoff, seg->filesize, wholeFileSize) )
        return Error("segment '%s' load command content extends beyond end of file", seg->segname);

    // <rdar://problem/19986776> dyld should support non-allocatable __LLVM segment
    if ( !isObjectFile() ) {
        if ( (seg->filesize > seg->vmsize) && ((seg->vmsize != 0) || ((seg->flags & SG_NORELOC) == 0)) )
            return Error("segment '%s' filesize exceeds vmsize", seg->segname);
    }

    // check permission bits
    if ( (seg->initprot & 0xFFFFFFF8) != 0 ) {
        return Error("%s segment permissions has invalid bits set (0x%08X)", seg->segname, seg->initprot);
    }
    if ( policy.enforceTextSegmentPermissions() ) {
        if ( (strcmp(seg->segname, "__TEXT") == 0) && (seg->initprot != (VM_PROT_READ | VM_PROT_EXECUTE)) )
            return Error("__TEXT segment permissions is not 'r-x'");
    }
    if ( policy.enforceReadOnlyLinkedit() ) {
        if ( (strcmp(seg->segname, "__LINKEDIT") == 0) && (seg->initprot != VM_PROT_READ) )
            return Error("__LINKEDIT segment permissions is not 'r--'");
    }
    if ( policy.enforceDataSegmentPermissions() ) {
        if ( (strcmp(seg->segname, "__DATA") == 0) && (seg->initprot != (VM_PROT_READ | VM_PROT_WRITE)) )
            return Error("__DATA segment permissions is not 'rw-'");
        if ( strcmp(seg->segname, "__DATA_CONST") == 0 ) {
            if ( seg->initprot != (VM_PROT_READ | VM_PROT_WRITE) )
                return Error("__DATA_CONST segment permissions is not 'rw-'");
            if ( (seg->flags & SG_READ_ONLY) == 0 ) {
                if ( this->isDylib() && this->hasSplitSegInfo() ) {
                    // dylibs in dyld cache are allowed to not have SG_READ_ONLY set
                }
                else {
                    return Error("__DATA_CONST segment missing SG_READ_ONLY flag");
                }
            }
        }
    }

    // check for vmaddr wrapping
    if ( (seg->vmaddr + seg->vmsize) < seg->vmaddr )
        return Error("'%s' segment vm range wraps", seg->segname);

    // check sections are within its segment
    const SC* const sectionsStart = (SC*)((char*)seg + sizeof(SG));
    const SC* const sectionsEnd   = &sectionsStart[seg->nsects];
    for ( const SC* sect = sectionsStart; (sect < sectionsEnd); ++sect ) {
        if ( (int64_t)(sect->size) < 0 ) {
            return Error("section '%s' size too large 0x%lX", sect->sectname, (size_t)sect->size);
        }
        else if ( sect->addr < seg->vmaddr ) {
            return Error("section '%s' start address 0x%lX is before containing segment's address 0x%0lX", sect->sectname, (size_t)sect->addr, (size_t)seg->vmaddr);
        }
        else if ( policy.enforceSectionsInSegment() && (sect->addr + sect->size > seg->vmaddr + seg->vmsize) ) {
            return Error("section '%s' end address 0x%lX is beyond containing segment's end address 0x%0lX", sect->sectname, (size_t)(sect->addr + sect->size), (size_t)(seg->vmaddr + seg->vmsize));
        }
    }

    return Error::none();
}

#endif // !TARGET_OS_EXCLAVEKIT
struct Interval
{
    bool     overlaps(const Interval& other) const;
    uint64_t start;
    uint64_t end;
};

bool Interval::overlaps(const Interval& other) const
{
    return ((other.start < this->end) && (other.end > this->start));
}

Error Header::validSemanticsSegments(const Policy& policy, uint64_t fileSize) const
{
    // check each segment load command in isolation
    struct SegRange
    {
        Interval    vm;
        Interval    file;
        const char* name;
    };
    STACK_ALLOC_OVERFLOW_SAFE_ARRAY(SegRange, ranges, 12);
    __block Error     lcError;
    __block bool      hasTEXT              = false;
    __block bool      hasLINKEDIT          = false;
    __block uintptr_t segmentIndexText     = 0;
    __block uintptr_t segmentIndexLinkedit = 0;
    forEachLoadCommandSafe(^(const load_command* cmd, bool& stop) {
        if ( cmd->cmd == LC_SEGMENT_64 ) {
            const segment_command_64* seg64 = (segment_command_64*)cmd;
            if ( strcmp(seg64->segname, "__TEXT") == 0 ) {
                hasTEXT          = true;
                segmentIndexText = ranges.count();
            }
            else if ( strcmp(seg64->segname, "__LINKEDIT") == 0 ) {
                hasLINKEDIT          = true;
                segmentIndexLinkedit = ranges.count();
            }
            lcError = validSegment<segment_command_64, section_64>(policy, fileSize, seg64);
            ranges.push_back({ { seg64->vmaddr, seg64->vmaddr + seg64->vmsize }, { seg64->fileoff, seg64->fileoff + seg64->filesize }, seg64->segname });
        }
        else if ( cmd->cmd == LC_SEGMENT ) {
            const segment_command* seg32 = (segment_command*)cmd;
            if ( strcmp(seg32->segname, "__TEXT") == 0 ) {
                hasTEXT          = true;
                segmentIndexText = ranges.count();
            }
            else if ( strcmp(seg32->segname, "__LINKEDIT") == 0 ) {
                hasLINKEDIT          = true;
                segmentIndexLinkedit = ranges.count();
            }
            lcError = validSegment<segment_command, section>(policy, fileSize, seg32);
            ranges.push_back({ { seg32->vmaddr, seg32->vmaddr + seg32->vmsize }, { seg32->fileoff, seg32->fileoff + seg32->filesize }, seg32->segname });
        }
        if ( lcError )
            stop = true;
    });
    if ( lcError )
        return std::move(lcError);

    // dynamic binaries have further restrictions
    if ( isDyldManaged() ) {
        if ( hasTEXT ) {
            if ( ranges[segmentIndexText].file.start != 0 )
                return Error("__TEXT segment fileoffset is not zero");
            const uint32_t headerAndLCSize = machHeaderSize() + mh.sizeofcmds;
            if ( ranges[segmentIndexText].file.end < headerAndLCSize )
                return Error("load commands do not fit in __TEXT segment");
        }
        else {
            return Error("missing __TEXT segment");
        }
        // FIXME: LINKEDIT checks need to move to Analyzer
        //if ( !hasLINKEDIT )
        //    return Error("missing __LINKEDIT segment");
    }

    // check for overlapping segments, by looking at every possible pair of segments
    for ( const SegRange& r1 : ranges ) {
        for ( const SegRange& r2 : ranges ) {
            if ( &r1 == &r2 )
                continue;
            if ( r1.vm.overlaps(r2.vm) )
                return Error("vm range of segment '%s' overlaps segment '%s'", r1.name, r2.name);
            if ( r1.file.overlaps(r2.file) )
                return Error("file range of segment '%s' overlaps segment '%s'", r1.name, r2.name);
        }
    }

    // check segment load command order matches file content order which matches vm order
    // skip dyld cache because segments are moved around too much
    if ( policy.enforceSegmentOrderMatchesLoadCmds() && !inDyldCache() ) {
        const SegRange* last = nullptr;
        for ( const SegRange& r : ranges ) {
            if ( last != nullptr ) {
                if ( (r.file.start < last->file.start) && (r.file.start != r.file.end) )
                    return Error("segment '%s' file offset out of order", r.name);
                if ( r.vm.start < last->vm.start ) {
                    if ( isFileSet() && (strcmp(r.name, "__PRELINK_INFO") == 0) ) {
                        // __PRELINK_INFO may have no vmaddr set
                    }
                    else {
                        return Error("segment '%s' vm address out of order", r.name);
                    }
                }
            }
            last = &r;
        }
    }

    return Error::none();
}

Error Header::validSemanticsMain(const Policy& policy) const
{
    if ( this->inDyldCache() && policy.enforceMainFlagsCorrect() )
        return Error("MH_EXECUTE has MH_DYLIB_IN_CACHE bit set");

    // validate the correct number of LC_MAIN or LC_UNIXTHREAD
    __block Error    lcError;
    __block uint64_t startAddress              = 0;
    __block const entry_point_command* mainCmd = nullptr;
    __block const thread_command* threadCmd    = nullptr;
    forEachLoadCommandSafe(^(const load_command* cmd, bool& stop) {
        switch ( cmd->cmd ) {
            case LC_MAIN:
                if ( mainCmd != nullptr )
                    lcError = Error("multiple LC_MAIN load commands");
                mainCmd = (entry_point_command*)cmd;
                break;
            case LC_UNIXTHREAD:
                if ( threadCmd != nullptr )
                    lcError = Error("multiple LC_UNIXTHREAD load commands");
                threadCmd = (thread_command*)cmd;
                if ( !entryAddrFromThreadCmd(threadCmd, startAddress) )
                    lcError = Error("invalid LC_UNIXTHREAD");
                break;
        }
    });
    if ( lcError )
        return std::move(lcError);
    if ( (mainCmd != nullptr) && (threadCmd != nullptr) )
        return Error("can't have LC_MAIN and LC_UNIXTHREAD load commands");
    if ( this->builtForPlatform(Platform::driverKit) ) {
        if ( (mainCmd != nullptr) || (threadCmd != nullptr) )
            return Error("LC_MAIN not allowed for driverkit");
    }
    else {
        if ( (mainCmd == nullptr) && (threadCmd == nullptr) )
            return Error("missing LC_MAIN or LC_UNIXTHREAD in main executable");
    }

    // FIXME: validate LC_MAIN or LC_UNIXTHREAD points into executable segment
    return Error::none();
}

Error Header::validSemanticsLinkerOptions(const Policy& policy) const
{
    __block Error     lcError;

    forEachLoadCommandSafe(^(const load_command *cmd, bool &stop) {
        if ( cmd->cmd == LC_LINKER_OPTION ) {
            const char*     begin = (char*)cmd + sizeof(linker_option_command);
            const char*     end = (char*)cmd + cmd->cmdsize;
            const uint32_t  count = ((linker_option_command*)cmd)->count;
            for ( uint32_t i = 0; i < count; ++i ) {
                const char* next = begin + strlen(begin) + 1;
                if ( next > end ) {
                    lcError = Error("malformed LC_LINKER_OPTION command");
                    stop = true;
                    return;
                }
                begin = next;
            }
        }
    });

    return std::move(lcError);
}

Error Header::forEachLoadCommand(void (^callback)(const load_command* cmd, bool& stop)) const
{
    bool                stop      = false;
    const load_command* startCmds = nullptr;
    if ( mh.magic == MH_MAGIC_64 )
        startCmds = (load_command*)((char*)this + sizeof(mach_header_64));
    else if ( mh.magic == MH_MAGIC )
        startCmds = (load_command*)((char*)this + sizeof(mach_header));
    else if ( hasMachOBigEndianMagic() )
        return Error("big endian mach-o file");
    else {
        const uint32_t* h = (uint32_t*)this;
        return Error("file does not start with MH_MAGIC[_64]: 0x%08X 0x%08X", h[0], h[1]);
    }
    if ( mh.filetype > 12 )
        return Error("unknown mach-o filetype (%u)", mh.filetype);
    //    const uint32_t ptrSize = this->pointerSize();
    const load_command* const cmdsEnd = (load_command*)((char*)startCmds + mh.sizeofcmds);
    const load_command*       cmd     = startCmds;
    for ( uint32_t i = 1; (i <= mh.ncmds) && !stop; ++i ) {
        const load_command* nextCmd = (load_command*)((char*)cmd + cmd->cmdsize);
        if ( cmd >= cmdsEnd ) {
            return Error("malformed load command (%d of %d) at %p with mh=%p, off end of load commands", i, mh.ncmds, cmd, this);
        }
        if ( cmd->cmdsize < 8 ) {
            return Error("malformed load command (%d of %d) at %p with mh=%p, size (0x%X) too small", i, mh.ncmds, cmd, this, cmd->cmdsize);
        }
#if 0
        // check the cmdsize is pointer aligned
        if ( checks.pointerAlignedLoadCommands ) {
            if ( (cmd->cmdsize % ptrSize) != 0 ) {
                return Error("malformed load command (%d of %d) at %p with mh=%p, size (0x%X) is not pointer sized", i, mh.ncmds, cmd, this, cmd->cmdsize);
            }
        }
#endif
        if ( (nextCmd > cmdsEnd) || (nextCmd < startCmds) ) {
            return Error("malformed load command (%d of %d) at %p with mh=%p, size (0x%X) is too large, load commands end at %p", i, mh.ncmds, cmd, this, cmd->cmdsize, cmdsEnd);
        }
        callback(cmd, stop);
        cmd = nextCmd;
    }
    return Error::none();
}

// This forEach is only used after the load commands have been validated, so no need to return Error and handle it
void Header::forEachLoadCommandSafe(void (^callback)(const load_command* cmd, bool& stop)) const
{
    if ( Error err = forEachLoadCommand(callback) )
        assert("Header::forEachLoadCommand()");
}

bool Header::hasLoadCommand(uint32_t cmdNum) const
{
    __block bool hasLC = false;
    forEachLoadCommandSafe(^(const load_command* cmd, bool& stop) {
        if ( cmd->cmd == cmdNum ) {
            hasLC = true;
            stop  = true;
        }
    });
    return hasLC;
}

bool Header::isStaticExecutable() const
{
    if ( mh.filetype != MH_EXECUTE )
        return false;

    // static executables do not have dyld load command
    return !hasLoadCommand(LC_LOAD_DYLINKER);
}

//
// MARK: --- methods that read Platform load commands ---
//

void Header::forEachPlatformLoadCommand(void (^handler)(Platform platform, Version32 minOS, Version32 sdk)) const
{
    __block bool foundPlatform = false;
    forEachLoadCommandSafe(^(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), Version32(buildCmd->minos), Version32(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, Version32(versCmd->version), Version32(sdk));
                foundPlatform = true;
                break;
            case LC_VERSION_MIN_IPHONEOS:
                if ( (mh.cputype == CPU_TYPE_X86_64) || (mh.cputype == CPU_TYPE_I386) )
                    handler(Platform::iOS_simulator, Version32(versCmd->version), Version32(versCmd->sdk)); // old sim binary
                else
                    handler(Platform::iOS, Version32(versCmd->version), Version32(versCmd->sdk));
                foundPlatform = true;
                break;
            case LC_VERSION_MIN_TVOS:
                if ( mh.cputype == CPU_TYPE_X86_64 )
                    handler(Platform::tvOS_simulator, Version32(versCmd->version), Version32(versCmd->sdk)); // old sim binary
                else
                    handler(Platform::tvOS, Version32(versCmd->version), Version32(versCmd->sdk));
                foundPlatform = true;
                break;
            case LC_VERSION_MIN_WATCHOS:
                if ( (mh.cputype == CPU_TYPE_X86_64) || (mh.cputype == CPU_TYPE_I386) )
                    handler(Platform::watchOS_simulator, Version32(versCmd->version), Version32(versCmd->sdk)); // old sim binary
                else
                    handler(Platform::watchOS, Version32(versCmd->version), Version32(versCmd->sdk));
                foundPlatform = true;
                break;
        }
    });
#ifndef BUILDING_MACHO_WRITER // no implicit platforms in static linker
    if ( !foundPlatform ) {
        // old binary with no explicit platform
#if TARGET_OS_OSX
        if ( (mh.cputype == CPU_TYPE_X86_64) | (mh.cputype == CPU_TYPE_I386) )
            handler(Platform::macOS, Version32(10, 5), Version32(10, 5)); // 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 ( mh.cputype == CPU_TYPE_ARM64 )
            handler(Platform::macOS, Version32(11, 0), Version32(11, 0)); // guess it is a macOS 11.0 binary
#endif
    }
#endif
}

bool Header::builtForPlatform(Platform reqPlatform, bool onlyOnePlatform) const
{
    PlatformAndVersions pvs = platformAndVersions();

    if ( pvs.platform == reqPlatform )
        return true;

    if ( onlyOnePlatform )
        return false;

    __block bool match = false;
    pvs.unzip(^(PlatformAndVersions pvers) {
        match |= pvers.platform == reqPlatform;
    });

    return match;
}

bool Header::isZippered() const
{
    return platformAndVersions().platform == Platform::zippered;
}

bool Header::allowsAlternatePlatform() const
{
    __block bool result = false;
    this->forEachSection(^(const SectionInfo& info, bool& stop) {
        if ( (info.sectionName == "__allow_alt_plat") && info.segmentName.starts_with("__DATA") ) {
            result = true;
            stop   = true;
        }
    });
    return result;
}

const char* Header::installName() const
{
    const char* name;
    Version32   compatVersion;
    Version32   currentVersion;
    if ( getDylibInstallName(&name, &compatVersion, &currentVersion) )
        return name;
    return nullptr;
}

bool Header::getDylibInstallName(const char** installName, Version32* compatVersion, Version32* currentVersion) const
{
    __block bool found = false;
    forEachLoadCommandSafe(^(const load_command* cmd, bool& stop) {
        if ( cmd->cmd == LC_ID_DYLIB ) {
            const dylib_command* dylibCmd = (dylib_command*)cmd;
            *compatVersion                = Version32(dylibCmd->dylib.compatibility_version);
            *currentVersion               = Version32(dylibCmd->dylib.current_version);
            *installName                  = (char*)dylibCmd + dylibCmd->dylib.name.offset;
            found                         = true;
            stop                          = true;
        }
    });
    return found;
}

bool Header::getUuid(uuid_t uuid) const
{
    __block bool found = false;
    forEachLoadCommandSafe(^(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;
        }
    });
    if ( !found )
        bzero(uuid, sizeof(uuid_t));
    return found;
}


const char* Header::dependentDylibLoadPath(uint32_t depIndex) const
{
    __block uint32_t     curIndex  = 0;
    __block const char*  result    = nullptr;
    forEachLoadCommandSafe(^(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;
                if ( curIndex == depIndex )
                    result = (char*)dylibCmd + dylibCmd->dylib.name.offset;
                ++curIndex;
            } break;
        }
    });
    return result;
}

uint32_t Header::dependentDylibCount(bool* allDepsAreNormal) const
{
    if ( allDepsAreNormal != nullptr )
        *allDepsAreNormal = true;
    __block unsigned count   = 0;
    forEachLoadCommandSafe(^(const load_command* cmd, bool& stop) {
        switch ( cmd->cmd ) {
            case LC_LOAD_WEAK_DYLIB:
            case LC_REEXPORT_DYLIB:
            case LC_LOAD_UPWARD_DYLIB:
                if ( allDepsAreNormal != nullptr )
                    *allDepsAreNormal = false;  // record if any linkages were weak, re-export, or upward
                ++count;
                break;
            case LC_LOAD_DYLIB:
                ++count;
                break;
        }
    });
    return count;
}

void Header::forEachDependentDylib(void (^callback)(const char* loadPath, bool isWeak, bool isReExport, bool isUpward,
                                                    Version32 compatVersion, Version32 curVersion, bool& stop)) const
{
    __block unsigned count   = 0;
    __block bool     stopped = false;
    forEachLoadCommandSafe(^(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),
                         Version32(dylibCmd->dylib.compatibility_version), Version32(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, Version32(1, 0), Version32(1, 0), stopped);
        }
        else {
            if ( !this->isDylib() || (strncmp(this->installName(), "/usr/lib/system/", 16) != 0) )
                callback("/usr/lib/libSystem.B.dylib", false, false, false, Version32(1, 0), Version32(1, 0), stopped);
        }
    }
}

void Header::forDyldEnv(void (^callback)(const char* envVar, bool& stop)) const
{
    forEachLoadCommandSafe(^(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);
                    }
                }
            }
        }
    });
}

bool Header::entryAddrFromThreadCmd(const thread_command* cmd, uint64_t& addr) const
{
    const uint32_t* regs32 = (uint32_t*)(((char*)cmd) + 16);
    const uint64_t* regs64 = (uint64_t*)(((char*)cmd) + 16);
    uint32_t        flavor = *((uint32_t*)(((char*)cmd) + 8));
    switch ( mh.cputype ) {
        case CPU_TYPE_I386:
            if ( flavor == 1 ) {   // i386_THREAD_STATE
                addr = regs32[10]; // i386_thread_state_t.eip
                return true;
            }
            break;
        case CPU_TYPE_X86_64:
            if ( flavor == 4 ) {   // x86_THREAD_STATE64
                addr = regs64[16]; // x86_thread_state64_t.rip
                return true;
            }
            break;
        case CPU_TYPE_ARM:
            if ( flavor == 1 ) {   // ARM_THREAD_STATE
                addr = regs32[15]; // arm_thread_state_t.pc
                return true;
            }
            break;
        case CPU_TYPE_ARM64:
            if ( flavor == 6 ) {   // ARM_THREAD_STATE64
                addr = regs64[32]; // arm_thread_state64_t.__pc
                return true;
            }
            break;
    }
    return false;
}

// returns false if entry point not found
bool Header::getEntry(uint64_t& offset, bool& usesCRT) const
{
    __block bool result = false;
    forEachLoadCommandSafe(^(const load_command* cmd, bool& stop) {
        if ( cmd->cmd == LC_MAIN ) {
            entry_point_command* mainCmd = (entry_point_command*)cmd;
            offset                       = mainCmd->entryoff;
            usesCRT                      = false;
            result                       = true;
            stop                         = true;
        }
        else if ( cmd->cmd == LC_UNIXTHREAD ) {
            uint64_t startAddress;
            if ( entryAddrFromThreadCmd((thread_command*)cmd, startAddress) ) {
                offset  = startAddress - preferredLoadAddress();
                usesCRT = true;
                result  = true;
            }
            stop = true;
        }
    });
    return result;
}

bool Header::hasCodeSignature(uint32_t& fileOffset, uint32_t& size) const
{
    __block bool result = false;
    forEachLoadCommandSafe(^(const load_command* cmd, bool& stop) {
        if ( cmd->cmd == LC_CODE_SIGNATURE ) {
            linkedit_data_command* sigCmd = (linkedit_data_command*)cmd;
            fileOffset                    = sigCmd->dataoff;
            size                          = sigCmd->datasize;
            result                        = true;
            stop                          = true;
        }
    });
    // FIXME: may need to ignore codesigs from pre 10.9 macOS binaries
    return result;
}

bool Header::hasIndirectSymbolTable(uint32_t& fileOffset, uint32_t& count) const
{
    __block bool result = false;
    forEachLoadCommandSafe(^(const load_command* cmd, bool& stop) {
        if ( cmd->cmd == LC_DYSYMTAB) {
            dysymtab_command* dySymCmd = (dysymtab_command*)cmd;
            fileOffset  = dySymCmd->indirectsymoff;
            count       = dySymCmd->nindirectsyms;
            result      = true;
            stop        = true;
        }
    });
    return result;
}

bool Header::hasSplitSegInfo() const
{
    __block bool result = false;
    forEachLoadCommandSafe(^(const load_command* cmd, bool& stop) {
        if ( cmd->cmd == LC_SEGMENT_SPLIT_INFO) {
            result      = true;
            stop        = true;
        }
    });
    return result;
}

bool Header::hasAtomInfo(uint32_t& fileOffset, uint32_t& size) const
{
    __block bool result = false;
    forEachLoadCommandSafe(^(const load_command* cmd, bool& stop) {
        if ( cmd->cmd == LC_ATOM_INFO) {
            linkedit_data_command* sigCmd = (linkedit_data_command*)cmd;
            fileOffset                    = sigCmd->dataoff;
            size                          = sigCmd->datasize;
            result      = true;
            stop        = true;
        }
    });
    return result;
}


uint32_t Header::segmentCount() const
{
    __block uint32_t count = 0;
    forEachLoadCommandSafe(^(const load_command* cmd, bool& stop) {
        switch ( cmd->cmd ) {
            case LC_SEGMENT:
            case LC_SEGMENT_64:
                ++count;
                break;
        }
    });
    return count;
}

uint64_t Header::preferredLoadAddress() const
{
    __block uint64_t textVmAddr = 0;
    forEachLoadCommandSafe(^(const load_command* cmd, bool& stop) {
        if ( cmd->cmd == LC_SEGMENT_64 ) {
            const segment_command_64* segCmd = (segment_command_64*)cmd;
            if ( strcmp(segCmd->segname, "__TEXT") == 0 ) {
                textVmAddr = segCmd->vmaddr;
                stop = true;
            }
        }
        else if ( cmd->cmd == LC_SEGMENT ) {
            const segment_command* segCmd = (segment_command*)cmd;
            if ( strcmp(segCmd->segname, "__TEXT") == 0 ) {
                textVmAddr = segCmd->vmaddr;
                stop = true;
            }
        }
    });
    return textVmAddr;
}

int64_t Header::getSlide() const
{
    return (long)this - (long)(this->preferredLoadAddress());
}

bool Header::hasDataConst() const
{
    __block bool result = false;
    forEachLoadCommandSafe(^(const load_command* cmd, bool& stop) {
        if ( cmd->cmd == LC_SEGMENT_64 ) {
            const segment_command_64* segCmd = (segment_command_64*)cmd;
            if ( (segCmd->flags & SG_READ_ONLY) != 0 )
                result = true;
        }
        else if ( cmd->cmd == LC_SEGMENT ) {
            const segment_command* segCmd = (segment_command*)cmd;
            if ( (segCmd->flags & SG_READ_ONLY) != 0 )
                result = true;
        }
    });
    return result;
}

std::string_view Header::segmentName(uint32_t segIndex) const
{
    __block std::string_view result;
    __block uint32_t    segCount = 0;
    this->forEachSegment(^(const SegmentInfo& info, bool& stop) {
        if ( segIndex == segCount ) {
            result = info.segmentName;
            stop   = true;
        }
        ++segCount;
    });
    return result;
}

// LC_SEGMENT stores names as char[16] potentially without a null terminator.  This returns a string_view for the given name
static std::string_view name16(const char name[16])
{
    size_t length = strnlen(name, 16);
    return std::string_view(name, length);
}

void Header::forEachSegment(void (^callback)(const SegmentInfo& infos, bool& stop)) const
{
    forEachLoadCommandSafe(^(const load_command* cmd, bool& stop) {
        if ( cmd->cmd == LC_SEGMENT_64 ) {
            const segment_command_64* segCmd = (segment_command_64*)cmd;
            SegmentInfo segInfo { .segmentName=name16(segCmd->segname), .vmaddr=segCmd->vmaddr, .vmsize=segCmd->vmsize,
                .fileOffset=(uint32_t)segCmd->fileoff, .fileSize=(uint32_t)segCmd->filesize, .flags=segCmd->flags, .perms=(uint8_t)segCmd->initprot };
            callback(segInfo, stop);
        }
        else if ( cmd->cmd == LC_SEGMENT ) {
            const segment_command* segCmd = (segment_command*)cmd;
            SegmentInfo segInfo { .segmentName=name16(segCmd->segname), .vmaddr=segCmd->vmaddr, .vmsize=segCmd->vmsize,
                .fileOffset=segCmd->fileoff, .fileSize=segCmd->filesize, .flags=segCmd->flags, .perms=(uint8_t)segCmd->initprot };
            callback(segInfo, stop);
        }
    });
}

void Header::forEachSection(void (^callback)(const SectionInfo&, bool& stop)) const
{
    __block uint64_t prefLoadAddr = 0;
    forEachLoadCommandSafe(^(const load_command* cmd, bool& stop) {
        if ( cmd->cmd == LC_SEGMENT_64 ) {
            const segment_command_64* segCmd        = (segment_command_64*)cmd;
            if ( strcmp(segCmd->segname, "__TEXT") == 0 )
                prefLoadAddr = segCmd->vmaddr;
            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; !stop && (sect < sectionsEnd); ++sect ) {
                std::string_view sectName = name16(sect->sectname);
                std::string_view segName = name16(sect->segname);
                SectionInfo info = { segName, sectName, (uint32_t)segCmd->initprot, sect->flags, sect->align, sect->addr - prefLoadAddr, sect->size, sect->offset,
                                     sect->reloff, sect->nreloc, sect->reserved1, sect->reserved2};
                callback(info, stop);
            }
        }
        else if ( cmd->cmd == LC_SEGMENT ) {
            const segment_command* segCmd        = (segment_command*)cmd;
            if ( strcmp(segCmd->segname, "__TEXT") == 0 )
                prefLoadAddr = segCmd->vmaddr;
            const section* const   sectionsStart = (section*)((char*)segCmd + sizeof(struct segment_command));
            const section* const   sectionsEnd   = &sectionsStart[segCmd->nsects];
            for ( const section* sect = sectionsStart; !stop && (sect < sectionsEnd); ++sect ) {
                std::string_view sectName = name16(sect->sectname);
                std::string_view segName = name16(sect->segname);
                SectionInfo info = { segName, sectName, (uint32_t)segCmd->initprot, sect->flags, sect->align, sect->addr - prefLoadAddr, sect->size, sect->offset,
                                     sect->reloff, sect->nreloc, sect->reserved1, sect->reserved2};
                callback(info, stop);
            }
        }
    });
}

// add any LINKEDIT content file-offset in load commands to this to get content
const uint8_t* Header::computeLinkEditBias(bool zeroFillExpanded) const
{
    // When there is no zerofill expansion, just add fileoffset of LINKEDIT content to mach_header to get content
    // If there is zerofill expansion, then zerofillExpansionAmount() needs to be added in too
    if ( zeroFillExpanded )
        return (uint8_t*)this + zerofillExpansionAmount();
    else
        return (uint8_t*)this;
}

// When loaded by dyld, LINKEDIT is farther from mach_header than in file
bool Header::hasZerofillExpansion() const
{
    return (zerofillExpansionAmount() != 0);
}

uint64_t Header::zerofillExpansionAmount() const
{
    // need to find LINKEDIT and TEXT to compute difference of file offsets vs vm offsets
    __block uint64_t result         = 0;
    __block uint64_t textVmAddr     = 0;
    __block uint64_t textFileOffset = 0;
    forEachLoadCommandSafe(^(const load_command* cmd, bool& stop) {
        if ( cmd->cmd == LC_SEGMENT_64 ) {
            const segment_command_64* segCmd = (segment_command_64*)cmd;
            if ( strcmp(segCmd->segname, "__TEXT") == 0 ) {
                textVmAddr     = segCmd->vmaddr;
                textFileOffset = segCmd->fileoff;
            }
            else if ( strcmp(segCmd->segname, "__LINKEDIT") == 0 ) {
                uint64_t vmOffsetToLinkedit   = segCmd->vmaddr - textVmAddr;
                uint64_t fileOffsetToLinkedit = segCmd->fileoff;
                result                        = vmOffsetToLinkedit - fileOffsetToLinkedit;
                stop                          = true;
            }
        }
        else if ( cmd->cmd == LC_SEGMENT ) {
            const segment_command* segCmd = (segment_command*)cmd;
            if ( strcmp(segCmd->segname, "__TEXT") == 0 ) {
                textVmAddr     = segCmd->vmaddr;
                textFileOffset = segCmd->fileoff;
            }
            else if ( strcmp(segCmd->segname, "__LINKEDIT") == 0 ) {
                uint64_t vmOffsetToLinkedit   = segCmd->vmaddr - textVmAddr;
                uint64_t fileOffsetToLinkedit = segCmd->fileoff - textFileOffset;
                result                        = vmOffsetToLinkedit - fileOffsetToLinkedit;
                stop                          = true;
            }
        }
    });
    return result;
}

bool Header::hasCustomStackSize(uint64_t& size) const {
    __block bool result = false;
    forEachLoadCommandSafe(^(const load_command* cmd, bool& stop) {
        if ( cmd->cmd == LC_MAIN ) {
            const entry_point_command* entryPointCmd = (entry_point_command*)cmd;
            size    = entryPointCmd->stacksize;
            result  = true;
            stop    = true;
        }
    });
    return result;
}

bool Header::isRestricted() const
{
    __block bool result = false;
    this->forEachSection(^(const SectionInfo& info, bool& stop) {
        if ( (info.segmentName == "__RESTRICT") && (info.sectionName == "__restrict") ) {
            result = true;
            stop   = true;
        }
    });
    return result;
}

bool Header::hasInterposingTuples() const
{
    __block bool hasInterposing = false;
    this->forEachSection(^(const SectionInfo& info, bool& stop) {
        if ( ((info.flags & SECTION_TYPE) == S_INTERPOSING) || ((info.sectionName == "__interpose") && (info.segmentName.starts_with("__DATA") || info.segmentName.starts_with("__AUTH"))) ) {
            hasInterposing = true;
            stop           = true;
        }
    });
    return hasInterposing;
}

bool Header::hasObjC() const
{
    __block bool hasObjCInfo = false;
    this->forEachSection(^(const SectionInfo& info, bool& stop) {
        if ( (info.sectionName == "__objc_imageinfo") && info.segmentName.starts_with("__DATA") ) {
            hasObjCInfo = true;
            stop        = true;
        }
    });
    return hasObjCInfo;
}

bool Header::hasEncryptionInfo(uint32_t& cryptId, uint32_t& textOffset, uint32_t& size) const
{
    if ( const encryption_info_command* encCmd = findFairPlayEncryptionLoadCommand() ) {
        cryptId = encCmd->cryptid;
        textOffset = encCmd->cryptoff;
        size       = encCmd->cryptsize;
        return true;
    }
    textOffset = 0;
    size       = 0;
    return false;
}

bool Header::isFairPlayEncrypted(uint32_t& textOffset, uint32_t& size) const
{
    // Note: cryptid is 0 in just-built apps.  The AppStore sets cryptid to 1
    uint32_t cryptId = 0;
    return hasEncryptionInfo(cryptId, textOffset, size) && cryptId == 1;
}

bool Header::canBeFairPlayEncrypted() const
{
    return (findFairPlayEncryptionLoadCommand() != nullptr);
}

const encryption_info_command* Header::findFairPlayEncryptionLoadCommand() const
{
    __block const encryption_info_command* result = nullptr;
    forEachLoadCommandSafe(^(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;
        }
    });
    return result;
}

bool Header::hasChainedFixups() const
{
    // arm64e always uses chained fixups
    if ( Architecture(&mh) == Architecture::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);
    }
    return hasLoadCommand(LC_DYLD_CHAINED_FIXUPS);
}

bool Header::hasChainedFixupsLoadCommand() const
{
    return hasLoadCommand(LC_DYLD_CHAINED_FIXUPS);
}

bool Header::hasOpcodeFixups() const
{
    return hasLoadCommand(LC_DYLD_INFO_ONLY) || hasLoadCommand(LC_DYLD_INFO);
}

void Header::forEachRPath(void (^callback)(const char* rPath, bool& stop)) const
{
    forEachLoadCommandSafe(^(const load_command* cmd, bool& stop) {
        if ( cmd->cmd == LC_RPATH ) {
            const char* rpath = (char*)cmd + ((struct rpath_command*)cmd)->path.offset;
            callback(rpath, stop);
        }
    });
}

void Header::forEachLinkerOption(void (^callback)(const char* opt, bool& stop)) const
{
    forEachLoadCommandSafe(^(const load_command *cmd, bool &stop) {
        if ( cmd->cmd == LC_LINKER_OPTION ) {
            const char*     begin = (char*)cmd + sizeof(linker_option_command);
            const uint32_t  count = ((linker_option_command*)cmd)->count;
            for ( uint32_t i = 0; i < count; ++i ) {
                const char* next = begin + strlen(begin) + 1;
                callback(begin, stop);
                begin = next;
            }
        }
    });
}

void Header::forAllowableClient(void (^callback)(const char* clientName, bool& stop)) const
{
    forEachLoadCommandSafe(^(const load_command* cmd, bool& stop) {
        if ( cmd->cmd == LC_SUB_CLIENT ) {
            const char* clientName = (char*)cmd + ((struct sub_client_command*)cmd)->client.offset;
            callback(clientName, stop);
        }
    });
}

const char* Header::umbrellaName() const
{
    __block const char* result = nullptr;
    forEachLoadCommandSafe(^(const load_command* cmd, bool& stop) {
        if ( cmd->cmd == LC_SUB_FRAMEWORK ) {
            result = (char*)cmd + ((struct sub_framework_command*)cmd)->umbrella.offset;
        }
    });
    return result;
}


uint32_t Header::headerAndLoadCommandsSize() const
{
    return machHeaderSize() + mh.sizeofcmds;
}

uint32_t Header::fileSize() const
{
    if ( isObjectFile() ) {
        // .o files do not have LINKEDIT segment, so use end of symbol table as file size
        __block uint32_t size = 0;
        forEachLoadCommandSafe(^(const load_command* cmd, bool& stop) {
            if ( cmd->cmd == LC_SYMTAB ) {
                const symtab_command* symTab = (symtab_command*)cmd;
                size = symTab->stroff + symTab->strsize;
                stop = true;
            }
        });
        return size;
    }

    // compute file size from LINKEDIT fileoffset + filesize
    __block uint32_t lastSegmentOffset = 0;
    __block uint32_t lastSegmentSize = 0;
    forEachSegment(^(const SegmentInfo &infos, bool &stop) {
        if ( infos.fileOffset >= lastSegmentOffset ) {
            lastSegmentOffset = infos.fileOffset;
            lastSegmentSize = std::max(infos.fileSize, lastSegmentSize);
        }
    });
    if ( lastSegmentSize == 0 )
        return headerAndLoadCommandsSize();

    uint32_t size;
    if ( __builtin_add_overflow(lastSegmentOffset, lastSegmentSize, &size)
        || size < headerAndLoadCommandsSize() )
        assert("malformed mach-o, size smaller than header and load commands");

    return size;
}

//
// MARK: --- methods that create and modify ---
//

#if BUILDING_MACHO_WRITER

Header* Header::make(std::span<uint8_t> buffer, uint32_t filetype, uint32_t flags, Architecture arch, bool addImplicitTextSegment)
{
    const size_t minHeaderAlignment = filetype == MH_OBJECT ? 8 : getpagesize();
    assert(((uint64_t)buffer.data() & (minHeaderAlignment - 1)) == 0);
    assert(buffer.size() >= sizeof(mach_header_64));
    bzero(buffer.data(), buffer.size());
    Header& header = *(Header*)buffer.data();
    mach_header& mh = header.mh;
    if ( arch.isBigEndian() ) {
        mh.magic      = arch.is64() ? MH_CIGAM_64 : MH_CIGAM;
        mh.filetype   = OSSwapBigToHostInt32(filetype);
        mh.ncmds      = 0;
        mh.sizeofcmds = OSSwapBigToHostInt32(MH_NOUNDEFS | MH_DYLDLINK | MH_TWOLEVEL);
        mh.flags      = OSSwapBigToHostInt32(flags);
        arch.set(mh);
        return &header; // can only construct mach_header for big-endian
    }
    else {
        mh.magic      = arch.is64() ? MH_MAGIC_64 : MH_MAGIC;
        mh.filetype   = filetype;
        mh.ncmds      = 0;
        mh.sizeofcmds = 0;
        mh.flags      = flags;
        arch.set(mh);
    }
    if ( addImplicitTextSegment && (filetype != MH_OBJECT) ) {
        SegmentInfo segInfo { .segmentName="__TEXT", .vmaddr=0, .vmsize=0x1000, .fileOffset=0, .fileSize=0x1000, .perms=(VM_PROT_READ | VM_PROT_EXECUTE) };
        header.addSegment(segInfo, std::array { "__text" });
    }

    return &header;
}

void Header::save(char savedPath[PATH_MAX]) const
{
    ::strcpy(savedPath, "/tmp/mocko-XXXXXX");
    int fd = ::mkstemp(savedPath);
    if ( fd != -1 ) {
        ::pwrite(fd, this, sizeof(Header), 0);
        ::close(fd);
    }
}

uint32_t Header::pointerAligned(uint32_t value) const
{
    // mach-o requires all load command sizes to be a multiple the pointer size
    if ( is64() )
        return ((value + 7) & (-8));
    else
        return ((value + 3) & (-4));
}

load_command* Header::firstLoadCommand()
{
    if ( mh.magic == MH_MAGIC )
        return (load_command*)((uint8_t*)this + sizeof(mach_header));
    else
        return (load_command*)((uint8_t*)this + sizeof(mach_header_64));
}

// creates space for a new load command, but does not fill in its payload
load_command* Header::appendLoadCommand(uint32_t cmd, uint32_t cmdSize)
{
    load_command* thisCmd = (load_command*)((uint8_t*)firstLoadCommand() + mh.sizeofcmds);
    thisCmd->cmd          = cmd;
    thisCmd->cmdsize      = cmdSize;
    mh.ncmds += 1;
    mh.sizeofcmds += cmdSize;

    return thisCmd;
}

// copies a new load command from another
void Header::appendLoadCommand(const load_command* lc)
{
    load_command* thisCmd = (load_command*)((uint8_t*)firstLoadCommand() + mh.sizeofcmds);
    ::memcpy(thisCmd, lc, lc->cmdsize);
    mh.ncmds += 1;
    mh.sizeofcmds += lc->cmdsize;
}

void Header::addBuildVersion(Platform platform, Version32 minOS, Version32 sdk, std::span<const build_tool_version> tools)
{
    assert(platform != Platform::zippered && "can't add a build command for Platform::zippered, it must be split");
    uint32_t               lcSize = (uint32_t)(sizeof(build_version_command) + tools.size() * sizeof(build_tool_version));
    build_version_command* bv     = (build_version_command*)appendLoadCommand(LC_BUILD_VERSION, lcSize);
    bv->platform = platform.value();
    bv->minos    = minOS.value();
    bv->sdk      = sdk.value();
    bv->ntools   = (uint32_t)tools.size();
    if ( bv->ntools != 0 )
        memcpy((uint8_t*)bv + sizeof(build_version_command), &tools[0], tools.size() * sizeof(build_tool_version));
}

void Header::addMinVersion(Platform platform, Version32 minOS, Version32 sdk)
{
    version_min_command vc;
    vc.cmdsize = sizeof(version_min_command);
    vc.version = minOS.value();
    vc.sdk     = sdk.value();
    if ( platform == Platform::macOS )
        vc.cmd = LC_VERSION_MIN_MACOSX;
    else if ( platform == Platform::iOS )
        vc.cmd = LC_VERSION_MIN_IPHONEOS;
    else if ( platform == Platform::watchOS )
        vc.cmd = LC_VERSION_MIN_WATCHOS;
    else if ( platform == Platform::tvOS )
        vc.cmd = LC_VERSION_MIN_TVOS;
    else
        assert(0 && "unknown platform");
    appendLoadCommand((load_command*)&vc);
}

void Header::setHasThreadLocalVariables()
{
    assert(mh.filetype != MH_OBJECT);
    mh.flags |= MH_HAS_TLV_DESCRIPTORS;
}

void Header::setHasWeakDefs()
{
    assert(mh.filetype != MH_OBJECT);
    mh.flags |= MH_WEAK_DEFINES;
}

void Header::setUsesWeakDefs()
{
    assert(mh.filetype != MH_OBJECT);
    mh.flags |= MH_BINDS_TO_WEAK;
}

void Header::setAppExtensionSafe()
{
    assert(mh.filetype == MH_DYLIB);
    mh.flags |= MH_APP_EXTENSION_SAFE;
}

void Header::setSimSupport()
{
    assert(mh.filetype == MH_DYLIB);
    mh.flags |= MH_SIM_SUPPORT;
}

void Header::setNoReExportedDylibs()
{
    assert(mh.filetype == MH_DYLIB);
    mh.flags |= MH_NO_REEXPORTED_DYLIBS;
}

void Header::addPlatformInfo(Platform platform, Version32 minOS, Version32 sdk, std::span<const build_tool_version> tools)
{
    Architecture arch(&mh);
    Policy policy(arch, { platform, minOS, sdk }, mh.filetype);
    switch ( policy.useBuildVersionLoadCommand() ) {
        case Policy::preferUse:
        case Policy::mustUse:
            // three macOS dylibs under libSystem need to be built with old load commands to support old simulator runtimes
            if ( isSimSupport() && (platform == Platform::macOS) && ((arch == Architecture::x86_64) || (arch == Architecture::i386)) )
                addMinVersion(platform, minOS, sdk);
            else
                addBuildVersion(platform, minOS, sdk, tools);
            break;
        case Policy::preferDontUse:
        case Policy::mustNotUse:
            addMinVersion(platform, minOS, sdk);
            break;
    }
}

void Header::addNullUUID()
{
    uuid_command uc;
    uc.cmd     = LC_UUID;
    uc.cmdsize = sizeof(uuid_command);
    bzero(uc.uuid, 16);
    appendLoadCommand((load_command*)&uc);
}

void Header::addUniqueUUID(uuid_t copyOfUUID)
{
    uuid_command uc;
    uc.cmd     = LC_UUID;
    uc.cmdsize = sizeof(uuid_command);
    uuid_generate_random(uc.uuid);
    appendLoadCommand((load_command*)&uc);
    if ( copyOfUUID )
        memcpy(copyOfUUID, uc.uuid, sizeof(uuid_t));
}

void Header::updateUUID(uuid_t uuid)
{
    __block bool found = false;
    forEachLoadCommandSafe(^(const load_command *cmd, bool &stop) {
        if ( cmd->cmd == LC_UUID ) {
            memcpy(((uuid_command*)cmd)->uuid, uuid, 16);
            found = true;
            stop = true;
        }
    });
    assert(found && "updateUUID called without a LC_UUID command");
}

void Header::addSegment(const SegmentInfo& info, std::span<const char* const> sectionNames)
{
    if ( is64() ) {
        uint32_t            lcSize = (uint32_t)(sizeof(segment_command_64) + sectionNames.size() * sizeof(section_64));
        segment_command_64* sc     = (segment_command_64*)appendLoadCommand(LC_SEGMENT_64, lcSize);
        strncpy(sc->segname, info.segmentName.data(), 16);
        sc->vmaddr             = info.vmaddr;
        sc->vmsize             = info.vmsize;
        sc->fileoff            = info.fileOffset;
        sc->filesize           = info.fileSize;
        sc->initprot           = info.perms;
        sc->maxprot            = info.perms;
        sc->nsects             = (uint32_t)sectionNames.size();
        sc->flags              = info.flags;
        section_64* const sect = (section_64*)((uint8_t*)sc + sizeof(struct segment_command_64));
        uint32_t sectionIndex  = 0;
        for ( const char* sectName : sectionNames ) {
            strncpy(sect[sectionIndex].segname, info.segmentName.data(), 16);
            strncpy(sect[sectionIndex].sectname, sectName, 16);
            ++sectionIndex;
        }
    }
    else {
        uint32_t         lcSize = (uint32_t)(sizeof(segment_command) + sectionNames.size() * sizeof(section));
        segment_command* sc     = (segment_command*)appendLoadCommand(LC_SEGMENT, lcSize);
        strncpy(sc->segname, info.segmentName.data(), 16);
        sc->vmaddr             = (uint32_t)info.vmaddr;
        sc->vmsize             = (uint32_t)info.vmsize;
        sc->fileoff            = info.fileOffset;
        sc->filesize           = info.fileSize;
        sc->initprot           = info.perms;
        sc->maxprot            = info.perms;
        sc->nsects             = (uint32_t)sectionNames.size();
        sc->flags              = info.flags;
        section* const sect = (section*)((uint8_t*)sc + sizeof(struct segment_command));
        uint32_t sectionIndex  = 0;
        for ( const char* sectName : sectionNames ) {
            strncpy(sect[sectionIndex].segname, info.segmentName.data(), 16);
            strncpy(sect[sectionIndex].sectname, sectName, 16);
            ++sectionIndex;
        }
    }
}

void Header::updateSection(const SectionInfo& info)
{
    forEachLoadCommandSafe(^(const load_command* cmd, bool& stop) {
        if ( cmd->cmd == LC_SEGMENT_64 ) {
            segment_command_64* segCmd = (segment_command_64*)cmd;
            if (info.segmentName == segCmd->segname) {
                section_64* const  sectionsStart = (section_64*)((char*)segCmd + sizeof(struct segment_command_64));
                section_64* const  sectionsEnd   = &sectionsStart[segCmd->nsects];
                for ( section_64* sect=sectionsStart; sect < sectionsEnd; ++sect ) {
                    if ( strncmp(info.sectionName.data(), sect->sectname, 16) == 0 ) {
                        sect->addr      = info.address;
                        sect->size      = info.size;
                        sect->offset    = info.fileOffset;
                        sect->align     = info.alignment;
                        sect->reloff    = info.relocsOffset;
                        sect->nreloc    = info.relocsCount;
                        sect->flags     = info.flags;
                        sect->reserved1 = info.reserved1;
                        sect->reserved2 = info.reserved2;
                        sect->reserved3 = 0;
                        stop = true;
                        return;
                    }
                }
            }
        }
        else if ( cmd->cmd == LC_SEGMENT ) {
            segment_command* segCmd = (segment_command*)cmd;
            if (info.segmentName == segCmd->segname) {
                section* const  sectionsStart = (section*)((char*)segCmd + sizeof(struct segment_command));
                section* const  sectionsEnd   = &sectionsStart[segCmd->nsects];
                for ( section* sect=sectionsStart; sect < sectionsEnd; ++sect ) {
                    if ( strncmp(info.sectionName.data(), sect->sectname, 16) == 0 ) {
                        sect->addr      = (uint32_t)info.address;
                        sect->size      = (uint32_t)info.size;
                        sect->offset    = info.fileOffset;
                        sect->align     = info.alignment;
                        sect->reloff    = info.relocsOffset;
                        sect->nreloc    = info.relocsCount;
                        sect->flags     = info.flags;
                        sect->reserved1 = info.reserved1;
                        sect->reserved2 = info.reserved2;
                        stop = true;
                        return;
                    }
                }
            }
        }
    });
}

void Header::updateSegment(const SegmentInfo& info)
{
    forEachLoadCommandSafe(^(const load_command* cmd, bool& stop) {
        if ( cmd->cmd == LC_SEGMENT_64 ) {
            segment_command_64* segCmd = (segment_command_64*)cmd;
            if (info.segmentName == segCmd->segname) {
                segCmd->vmaddr             = info.vmaddr;
                segCmd->vmsize             = info.vmsize;
                segCmd->fileoff            = info.fileOffset;
                segCmd->filesize           = info.fileSize;
                segCmd->initprot           = info.perms;
                segCmd->maxprot            = info.perms;
                stop = true;
                return;
            }
        }
        else if ( cmd->cmd == LC_SEGMENT ) {
            segment_command* segCmd = (segment_command*)cmd;
            if (info.segmentName == segCmd->segname) {
                segCmd->vmaddr             = (uint32_t)info.vmaddr;
                segCmd->vmsize             = (uint32_t)info.vmsize;
                segCmd->fileoff            = info.fileOffset;
                segCmd->filesize           = info.fileSize;
                segCmd->initprot           = info.perms;
                segCmd->maxprot            = info.perms;
                stop = true;
                return;
            }
        }
    });
}


void Header::addInstallName(const char* name, Version32 compatVers, Version32 currentVersion)
{
    uint32_t       alignedSize      = pointerAligned((uint32_t)(sizeof(dylib_command) + strlen(name) + 1));
    dylib_command* ic               = (dylib_command*)appendLoadCommand(LC_ID_DYLIB, alignedSize);
    ic->dylib.name.offset           = sizeof(dylib_command);
    ic->dylib.current_version       = currentVersion.value();
    ic->dylib.compatibility_version = compatVers.value();
    strcpy((char*)ic + ic->dylib.name.offset, name);
}

void Header::addDependentDylib(const char* path, bool isWeak, bool isUpward, bool isReexport, Version32 compatVers, Version32 currentVersion)
{
    uint32_t       alignedSize = pointerAligned((uint32_t)(sizeof(dylib_command) + strlen(path) + 1));
    dylib_command* dc          = (dylib_command*)appendLoadCommand(LC_LOAD_DYLIB, alignedSize);
    if ( isReexport )
        dc->cmd = LC_REEXPORT_DYLIB;
    else if ( isUpward )
        dc->cmd = LC_LOAD_UPWARD_DYLIB;
    else if ( isWeak )
        dc->cmd = LC_LOAD_WEAK_DYLIB;
    dc->dylib.name.offset           = sizeof(dylib_command);
    dc->dylib.current_version       = currentVersion.value();
    dc->dylib.compatibility_version = compatVers.value();
    dc->dylib.timestamp             = 2; // needs to be some constant value that is different than dylib id load command
    strcpy((char*)dc + dc->dylib.name.offset, path);
}

void Header::addLibSystem()
{
    addDependentDylib("/usr/lib/libSystem.B.dylib");
}

void Header::addDylibId(CString name, Version32 compatVers, Version32 currentVersion)
{
    uint32_t       alignedSize          = pointerAligned((uint32_t)(sizeof(dylib_command) + name.size() + 1));
    dylib_command* dc                   = (dylib_command*)appendLoadCommand(LC_ID_DYLIB, alignedSize);
    dc->dylib.name.offset               = sizeof(dylib_command);
    dc->dylib.timestamp                 = 1; // needs to be some constant value that is different than dependent dylib
    dc->dylib.current_version           = currentVersion.value();
    dc->dylib.compatibility_version     = compatVers.value();
    strcpy((char*)dc + dc->dylib.name.offset, name.c_str());
}

void Header::addDyldID()
{
    const char* path = "/usr/lib/dyld";
    uint32_t       alignedSize = pointerAligned((uint32_t)(sizeof(dylinker_command) + strlen(path) + 1));
    dylinker_command* dc       = (dylinker_command*)appendLoadCommand(LC_ID_DYLINKER, alignedSize);
    dc->name.offset = sizeof(dylinker_command);
    strcpy((char*)dc + dc->name.offset, path);
}

void Header::addDynamicLinker()
{
    const char* path = "/usr/lib/dyld";
    uint32_t       alignedSize = pointerAligned((uint32_t)(sizeof(dylinker_command) + strlen(path) + 1));
    dylinker_command* dc       = (dylinker_command*)appendLoadCommand(LC_LOAD_DYLINKER, alignedSize);
    dc->name.offset = sizeof(dylinker_command);
    strcpy((char*)dc + dc->name.offset, path);
}

void Header::addFairPlayEncrypted(uint32_t offset, uint32_t size)
{
    if ( is64() ) {
        encryption_info_command_64 en64;
        en64.cmd       = LC_ENCRYPTION_INFO_64;
        en64.cmdsize   = sizeof(encryption_info_command_64);
        en64.cryptoff  = offset;
        en64.cryptsize = size;
        en64.cryptid   = 0;
        en64.pad       = 0;
        appendLoadCommand((load_command*)&en64);
    }
    else {
        encryption_info_command en32;
        en32.cmd       = LC_ENCRYPTION_INFO;
        en32.cmdsize   = sizeof(encryption_info_command);
        en32.cryptoff  = offset;
        en32.cryptsize = size;
        en32.cryptid   = 0;
        appendLoadCommand((load_command*)&en32);
    }
}

void Header::addRPath(const char* path)
{
    uint32_t       alignedSize = pointerAligned((uint32_t)(sizeof(rpath_command) + strlen(path) + 1));
    rpath_command* rc          = (rpath_command*)appendLoadCommand(LC_RPATH, alignedSize);
    rc->path.offset            = sizeof(rpath_command);
    strcpy((char*)rc + rc->path.offset, path);
}

void Header::addDyldEnvVar(const char* path)
{
    uint32_t          alignedSize = pointerAligned((uint32_t)(sizeof(dylinker_command) + strlen(path) + 1));
    dylinker_command* dc          = (dylinker_command*)appendLoadCommand(LC_DYLD_ENVIRONMENT, alignedSize);
    dc->name.offset               = sizeof(dylinker_command);
    strcpy((char*)dc + dc->name.offset, path);
}

void Header::addAllowableClient(const char* clientName)
{
    uint32_t            alignedSize = pointerAligned((uint32_t)(sizeof(sub_client_command) + strlen(clientName) + 1));
    sub_client_command* ac          = (sub_client_command*)appendLoadCommand(LC_SUB_CLIENT, alignedSize);
    ac->client.offset               = sizeof(sub_client_command);
    strcpy((char*)ac + ac->client.offset, clientName);
}

void Header::addUmbrellaName(const char* umbrellaName)
{
    uint32_t            alignedSize = pointerAligned((uint32_t)(sizeof(sub_framework_command) + strlen(umbrellaName) + 1));
    sub_framework_command* ac       = (sub_framework_command*)appendLoadCommand(LC_SUB_FRAMEWORK, alignedSize);
    ac->umbrella.offset             = sizeof(sub_framework_command);
    strcpy((char*)ac + ac->umbrella.offset, umbrellaName);
}

void Header::addSourceVersion(Version64 vers)
{
    source_version_command svc;
    svc.cmd       = LC_SOURCE_VERSION;
    svc.cmdsize   = sizeof(source_version_command);
    svc.version   = vers.value();
    appendLoadCommand((load_command*)&svc);
}

void Header::setMain(uint32_t offset)
{
    entry_point_command ec;
    ec.cmd       = LC_MAIN;
    ec.cmdsize   = sizeof(entry_point_command);
    ec.entryoff  = offset;
    ec.stacksize = 0;
    appendLoadCommand((load_command*)&ec);
}

void Header::setCustomStackSize(uint64_t stackSize) {
    __block bool found = false;
    forEachLoadCommandSafe(^(const load_command* cmd, bool& stop) {
        if (cmd->cmd == LC_MAIN) {
            entry_point_command* ec = (entry_point_command*)cmd;
            ec->stacksize           = stackSize;
            found                   = true;
            stop                    = true;
        }
    });
    assert(found);
}

void Header::setUnixEntry(uint64_t startAddr)
{
    // FIXME: support other archs
    if ( (mh.cputype == CPU_TYPE_ARM64) || (mh.cputype == CPU_TYPE_ARM64_32) ) {
        uint32_t   lcSize = 288;
        uint32_t*  words     = (uint32_t*)appendLoadCommand(LC_UNIXTHREAD, lcSize);
        words[2] = 6;   // flavor = ARM_THREAD_STATE64
        words[3] = 68;  // count  = ARM_EXCEPTION_STATE64_COUNT
        bzero(&words[4], lcSize-16);
        *(uint64_t*)(&words[68]) = startAddr;  // register pc = startAddr
    }
    else if ( mh.cputype == CPU_TYPE_X86_64 ) {
        uint32_t   lcSize = 184;
        uint32_t*  words     = (uint32_t*)appendLoadCommand(LC_UNIXTHREAD, lcSize);
        words[2] = 4;   // flavor = x86_THREAD_STATE64
        words[3] = 42;  // count  = x86_THREAD_STATE64_COUNT
        bzero(&words[4], lcSize-16);
        *(uint64_t*)(&words[36]) = startAddr;  // register pc = startAddr
    }
    else {
        assert(0 && "arch not supported");
    }
}

void Header::addCodeSignature(uint32_t fileOffset, uint32_t fileSize)
{
    linkedit_data_command lc;
    lc.cmd       = LC_CODE_SIGNATURE;
    lc.cmdsize   = sizeof(linkedit_data_command);
    lc.dataoff   = fileOffset;
    lc.datasize  = fileSize;
    appendLoadCommand((load_command*)&lc);
}

void Header::setBindOpcodesInfo(uint32_t rebaseOffset, uint32_t rebaseSize,
                                uint32_t bindsOffset, uint32_t bindsSize,
                                uint32_t weakBindsOffset, uint32_t weakBindsSize,
                                uint32_t lazyBindsOffset, uint32_t lazyBindsSize,
                                uint32_t exportTrieOffset, uint32_t exportTrieSize)
{
    dyld_info_command lc;
    lc.cmd              = LC_DYLD_INFO_ONLY;
    lc.cmdsize          = sizeof(dyld_info_command);
    lc.rebase_off       = rebaseOffset;
    lc.rebase_size      = rebaseSize;
    lc.bind_off         = bindsOffset;
    lc.bind_size        = bindsSize;
    lc.weak_bind_off    = weakBindsOffset;
    lc.weak_bind_size   = weakBindsSize;
    lc.lazy_bind_off    = lazyBindsOffset;
    lc.lazy_bind_size   = lazyBindsSize;
    lc.export_off       = exportTrieOffset;
    lc.export_size      = exportTrieSize;
    appendLoadCommand((load_command*)&lc);
}

void Header::setChainedFixupsInfo(uint32_t cfOffset, uint32_t cfSize)
{
    linkedit_data_command lc;
    lc.cmd       = LC_DYLD_CHAINED_FIXUPS;
    lc.cmdsize   = sizeof(linkedit_data_command);
    lc.dataoff   = cfOffset;
    lc.datasize  = cfSize;
    appendLoadCommand((load_command*)&lc);
}

void Header::setExportTrieInfo(uint32_t offset, uint32_t size)
{
    linkedit_data_command lc;
    lc.cmd       = LC_DYLD_EXPORTS_TRIE;
    lc.cmdsize   = sizeof(linkedit_data_command);
    lc.dataoff   = offset;
    lc.datasize  = size;
    appendLoadCommand((load_command*)&lc);
}

void Header::setSplitSegInfo(uint32_t offset, uint32_t size)
{
    linkedit_data_command lc;
    lc.cmd       = LC_SEGMENT_SPLIT_INFO;
    lc.cmdsize   = sizeof(linkedit_data_command);
    lc.dataoff   = offset;
    lc.datasize  = size;
    appendLoadCommand((load_command*)&lc);
}

void Header::setDataInCode(uint32_t offset, uint32_t size)
{
    linkedit_data_command lc;
    lc.cmd       = LC_DATA_IN_CODE;
    lc.cmdsize   = sizeof(linkedit_data_command);
    lc.dataoff   = offset;
    lc.datasize  = size;
    appendLoadCommand((load_command*)&lc);
}

void Header::setFunctionStarts(uint32_t offset, uint32_t size)
{
    linkedit_data_command lc;
    lc.cmd       = LC_FUNCTION_STARTS;
    lc.cmdsize   = sizeof(linkedit_data_command);
    lc.dataoff   = offset;
    lc.datasize  = size;
    appendLoadCommand((load_command*)&lc);
}

void Header::setAtomInfo(uint32_t offset, uint32_t size)
{
    linkedit_data_command lc;
    lc.cmd       = LC_ATOM_INFO;
    lc.cmdsize   = sizeof(linkedit_data_command);
    lc.dataoff   = offset;
    lc.datasize  = size;
    appendLoadCommand((load_command*)&lc);
}

void Header::setSymbolTable(uint32_t nlistOffset, uint32_t nlistCount, uint32_t stringPoolOffset, uint32_t stringPoolSize,
                            uint32_t localsCount, uint32_t globalsCount, uint32_t undefCount, uint32_t indOffset, uint32_t indCount)
{
    symtab_command stc;
    stc.cmd       = LC_SYMTAB;
    stc.cmdsize   = sizeof(symtab_command);
    stc.symoff    = nlistOffset;
    stc.nsyms     = nlistCount;
    stc.stroff    = stringPoolOffset;
    stc.strsize   = stringPoolSize;
    appendLoadCommand((load_command*)&stc);

    dysymtab_command dstc;
    bzero(&dstc, sizeof(dstc));
    dstc.cmd            = LC_DYSYMTAB;
    dstc.cmdsize        = sizeof(dysymtab_command);
    dstc.ilocalsym      = 0;
    dstc.nlocalsym      = localsCount;
    dstc.iextdefsym     = localsCount;
    dstc.nextdefsym     = globalsCount;
    dstc.iundefsym      = localsCount+globalsCount;
    dstc.nundefsym      = undefCount;
    dstc.indirectsymoff = indOffset;
    dstc.nindirectsyms  = indCount;
    appendLoadCommand((load_command*)&dstc);
}

void Header::addLinkerOption(std::span<uint8_t> buffer, uint32_t count)
{
    uint32_t cmdSize = pointerAligned(sizeof(linker_option_command) + (uint32_t)buffer.size());

    linker_option_command* lc = (linker_option_command*)appendLoadCommand(LC_LINKER_OPTION, cmdSize);
    lc->cmd     = LC_LINKER_OPTION;
    lc->cmdsize = cmdSize;
    lc->count   = count;
    memcpy((uint8_t*)(lc + 1), buffer.data(), buffer.size());
}

Header::LinkerOption Header::LinkerOption::make(std::span<CString> opts)
{
    LinkerOption out;
    out.count = (uint32_t)opts.size();
    assert(out.count == opts.size());
    for ( CString option : opts ) {
        if ( option.empty() )
            continue;
        size_t previousSize = out.buffer.size();
        out.buffer.resize(previousSize + option.size() + 1);
        option.strcpy((char*)out.buffer.data() + previousSize);
    }
    return out;
}

load_command* Header::findLoadCommand(uint32_t cmdNum)
{
    __block load_command* result = nullptr;
    forEachLoadCommandSafe(^(const load_command* cmd, bool& stop) {
        if ( cmd->cmd == cmdNum ) {
            result = (load_command*)cmd;
            stop   = true;
        }
    });
    return result;
}

void Header::removeLoadCommand(void (^callback)(const load_command* cmd, bool& remove, bool& stop))
{
    bool                stop      = false;
    const load_command* startCmds = nullptr;
    if ( mh.magic == MH_MAGIC_64 )
        startCmds = (load_command*)((char*)this + sizeof(mach_header_64));
    else if ( mh.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 + mh.sizeofcmds);
    auto                      cmd            = (load_command*)startCmds;
    const uint32_t            origNcmds      = mh.ncmds;
    unsigned                  bytesRemaining = mh.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, mh.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, mh.ncmds, cmd, this, cmd->cmdsize, cmdsEnd);
            return;
        }
        callback(cmd, remove, stop);
        if ( remove ) {
            mh.sizeofcmds -= cmd->cmdsize;
            ::memmove((void*)cmd, (void*)nextCmd, bytesRemaining);
            mh.ncmds--;
        }
        else {
            bytesRemaining -= cmd->cmdsize;
            cmd = nextCmd;
        }
        if ( stop )
            break;
    }
    if ( cmd )
        ::bzero(cmd, bytesRemaining);
}

uint32_t Header::relocatableHeaderAndLoadCommandsSize(bool is64, uint32_t sectionCount, uint32_t platformsCount, std::span<const Header::LinkerOption> linkerOptions)
{
    uint32_t size =  0;
    if ( is64 ) {
        size += sizeof(mach_header_64);
        size += sizeof(segment_command_64);
        size += sizeof(section_64) * sectionCount;
    }
    else {
        size += sizeof(mach_header);
        size += sizeof(segment_command);
        size += sizeof(section) * sectionCount;
    }
    size += sizeof(symtab_command);
    size += sizeof(dysymtab_command);
    size += sizeof(build_version_command) * platformsCount;
    size += sizeof(linkedit_data_command);

    for ( Header::LinkerOption opt : linkerOptions ) {
        size += opt.lcSize();
    }
    return size;
}

void Header::setRelocatableSectionCount(uint32_t sectionCount)
{
    assert(mh.filetype == MH_OBJECT);
    if ( is64() ) {
        uint32_t            lcSize = (uint32_t)(sizeof(segment_command_64) + sectionCount * sizeof(section_64));
        segment_command_64* sc = (segment_command_64*)appendLoadCommand(LC_SEGMENT_64, lcSize);
        sc->segname[0]         = '\0';   // MH_OBJECT has one segment with no name
        sc->vmaddr             = 0;
        sc->vmsize             = 0;   // adjusted in updateRelocatableSegmentSize()
        sc->fileoff            = 0;
        sc->filesize           = 0;   // adjusted in updateRelocatableSegmentSize()
        sc->initprot           = 7;
        sc->maxprot            = 7;
        sc->nsects             = sectionCount;
        // section info to be filled in later by setRelocatableSectionInfo()
        bzero((uint8_t*)sc + sizeof(segment_command_64), sectionCount * sizeof(section_64));
    }
    else {
        uint32_t            lcSize = (uint32_t)(sizeof(segment_command) + sectionCount * sizeof(section));
        segment_command* sc = (segment_command*)appendLoadCommand(LC_SEGMENT, lcSize);
        sc->segname[0]         = '\0';   // MH_OBJECT has one segment with no name
        sc->vmaddr             = 0;
        sc->vmsize             = 0x1000; // FIXME: need dynamic segment layout
        sc->fileoff            = 0;
        sc->filesize           = 0x1000;
        sc->initprot           = 7;
        sc->maxprot            = 7;
        sc->nsects             = sectionCount;
        // section info to be filled in later by setRelocatableSectionInfo()
        bzero((uint8_t*)sc + sizeof(segment_command), sectionCount * sizeof(struct section));
    }
}

void Header::updateRelocatableSegmentSize(uint64_t vmSize, uint32_t fileSize)
{
    forEachLoadCommandSafe(^(const load_command* cmd, bool& stop) {
        if ( cmd->cmd == LC_SEGMENT ) {
            segment_command* sc = (segment_command*)cmd;
            sc->vmsize   = (uint32_t)vmSize;
            sc->filesize = fileSize;
            stop = true;
        }
        else if ( cmd->cmd == LC_SEGMENT_64 ) {
            segment_command_64* sc = (segment_command_64*)cmd;
            sc->vmsize   = vmSize;
            sc->filesize = fileSize;
            stop = true;
        }
    });
}


void Header::setRelocatableSectionInfo(uint32_t sectionIndex, const char* segName, const char* sectName,
                                       uint32_t flags, uint64_t address, uint64_t size, uint32_t fileOffset,
                                       uint16_t alignment, uint32_t relocsOffset, uint32_t relocsCount)
{
    __block struct section*    section32 = nullptr;
    __block struct section_64* section64 = nullptr;
    forEachLoadCommandSafe(^(const load_command* cmd, bool& stop) {
        if ( cmd->cmd == LC_SEGMENT ) {
            struct section* sections = (struct section*)((uint8_t*)cmd + sizeof(segment_command));
            section32 = &sections[sectionIndex];
            stop = true;
        }
        else if ( cmd->cmd == LC_SEGMENT_64 ) {
            struct section_64* sections = (struct section_64*)((uint8_t*)cmd + sizeof(segment_command_64));
            section64 = &sections[sectionIndex];
            stop = true;
        }
    });
    if ( section64 != nullptr ) {
        strncpy(section64->segname,  segName, 16);
        strncpy(section64->sectname, sectName, 16);
        section64->addr      = address;
        section64->size      = size;
        section64->offset    = fileOffset;
        section64->align     = alignment;
        section64->reloff    = relocsOffset;
        section64->nreloc    = relocsCount;
        section64->flags     = flags;
        section64->reserved1 = 0;
        section64->reserved2 = 0;
        section64->reserved3 = 0;
    }
    else if ( section32 != nullptr ) {
        strncpy(section32->segname,  segName, 16);
        strncpy(section32->sectname, sectName, 16);
        section32->addr      = (uint32_t)address;
        section32->size      = (uint32_t)size;
        section32->offset    = fileOffset;
        section32->align     = alignment;
        section32->reloff    = relocsOffset;
        section32->nreloc    = relocsCount;
        section32->flags     = flags;
        section32->reserved1 = 0;
        section32->reserved2 = 0;
    }
}

#endif // BUILDING_MACHO_WRITER


} // namespace dyld3