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
/* -*- mode: C++; c-basic-offset: 4; tab-width: 4 -*-
 *
 * Copyright (c) 2004-2009 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@
 */

//
// This file implements that API's in <mach-o/dyld.h>
//
//

#define __STDC_LIMIT_MACROS
#include <stddef.h>
#include <stdint.h>
#include <string.h>
#include <sys/param.h>
#include <sys/mount.h>
#include <Availability.h>


#include <vector>
#include <map>
#include <algorithm>

#include <mach/mach.h>
#include <sys/time.h>
#include <sys/sysctl.h>
#include <mach/mach_traps.h> // for task_self_trap()

#include <mach-o/dyld_images.h>
#include <mach-o/dyld.h>
#include <mach-o/dyld_priv.h>

#include "ImageLoader.h"
#include "ImageLoaderMachO.h"
#include "dyld2.h"
#include "dyldLibSystemInterface.h"
#include "DyldSharedCache.h"
#include "MachOFile.h"

#undef _POSIX_C_SOURCE
#include <dlfcn.h>

#if __has_feature(ptrauth_calls)
  #include <ptrauth.h>
#endif


// relocation_info.r_length field has value 3 for 64-bit executables and value 2 for 32-bit executables
#if __LP64__
#define RELOC_SIZE 3
#define LC_SEGMENT_COMMAND		LC_SEGMENT_64
#define LC_ROUTINES_COMMAND		LC_ROUTINES_64
struct macho_segment_command	: public segment_command_64  {};
struct macho_section			: public section_64  {};
struct macho_routines_command	: public routines_command_64  {};
#else
#define RELOC_SIZE 2
#define LC_SEGMENT_COMMAND		LC_SEGMENT
#define LC_ROUTINES_COMMAND		LC_ROUTINES
struct macho_segment_command	: public segment_command {};
struct macho_section			: public section  {};
struct macho_routines_command	: public routines_command  {};
#endif


// this was in dyld_priv.h but it is no longer exported
extern "C" {
    const struct dyld_all_image_infos* _dyld_get_all_image_infos();
}

// from dyldExceptions.c
extern "C" void __Unwind_SjLj_SetThreadKey(pthread_key_t key);

// from dyld_gdb.cpp 
extern void addImagesToAllImages(uint32_t infoCount, const dyld_image_info info[]);
extern uint32_t allImagesCount();
extern const mach_header* allImagesIndexedMachHeader(uint32_t index);
extern const char* allImagesIndexedPath(uint32_t index);

extern "C" int _dyld_func_lookup(const char* name, void** address);

extern "C" void* dlopen_internal(const char* path, int mode, void* callerAddress);
extern "C" bool  dlopen_preflight_internal(const char* path, void* callerAddress);
extern "C" void* dlsym_internal(void* handle, const char* symbolName, void* callerAddress);

extern "C" void* dlopen_compat(const char* path, int mode);
extern "C" bool  dlopen_preflight_compat(const char* path);
extern "C" void* dlsym_compat(void* handle, const char* symbolName);



// deprecated APIs are still availble on Mac OS X, but not on iPhone OS
#if TARGET_OS_OSX
	#define DEPRECATED_APIS_SUPPORTED 1
#else
	#define DEPRECATED_APIS_SUPPORTED 0
#endif

static bool sDynamicInterposing = false;

#if DEPRECATED_APIS_SUPPORTED
static char sLastErrorFilePath[1024];
static NSLinkEditErrors sLastErrorFileCode;
static int sLastErrorNo;
#endif

// In 10.3.x and earlier all the NSObjectFileImage API's were implemeneted in libSystem.dylib
// Beginning in 10.4 the NSObjectFileImage API's are implemented in dyld and libSystem just forwards
// This conditional keeps support for old libSystem's which needed some help implementing the API's
#define OLD_LIBSYSTEM_SUPPORT (__i386__)

// The following functions have no prototype in any header.  They are special cases
// where _dyld_func_lookup() is used directly.
static void _dyld_make_delayed_module_initializer_calls();
static void registerThreadHelpers(const dyld::LibSystemHelpers*);
#if DEPRECATED_APIS_SUPPORTED
static void _dyld_install_handlers(void* undefined, void* multiple, void* linkEdit);
#if OLD_LIBSYSTEM_SUPPORT
static NSModule _dyld_link_module(NSObjectFileImage object_addr, size_t object_size, const char* moduleName, uint32_t options);
#endif
static void _dyld_register_binding_handler(void * (*)(const char *, const char *, void *), ImageLoader::BindingOptions);
static bool NSMakePrivateModulePublic(NSModule module);
static void _dyld_call_module_initializers_for_dylib(const struct mach_header* mh_dylib_header);

// The following functions are dyld API's, but since dyld links with a static copy of libc.a
// the public name cannot be used.
static void		client_dyld_lookup_and_bind(const char* symbolName, void** address, NSModule* module);
static bool		client_NSIsSymbolNameDefined(const char* symbolName);
#endif // DEPRECATED_APIS_SUPPORTED
#if SUPPORT_ZERO_COST_EXCEPTIONS
static bool client_dyld_find_unwind_sections(void* addr, dyld_unwind_sections* info);
#endif
#if DEPRECATED_APIS_SUPPORTED
#endif

static void unimplemented()
{
	dyld::halt("unimplemented dyld function\n");
}

struct dyld_func {
    const char* name;
    void*		implementation;
};

static const struct dyld_func dyld_funcs[] = {
    {"__dyld_register_func_for_add_image",				(void*)_dyld_register_func_for_add_image },
    {"__dyld_register_func_for_remove_image",			(void*)_dyld_register_func_for_remove_image },
    {"__dyld_dladdr",									(void*)dladdr },
    {"__dyld_dlclose",									(void*)dlclose },
    {"__dyld_dlerror",									(void*)dlerror },
    {"__dyld_dlopen_internal",							(void*)dlopen_internal },
    {"__dyld_dlsym_internal",							(void*)dlsym_internal },
    {"__dyld_dlopen_preflight_internal",				(void*)dlopen_preflight_internal },
    {"__dyld_dlopen",									(void*)dlopen_compat },
    {"__dyld_dlsym",									(void*)dlsym_compat },
    {"__dyld_dlopen_preflight",							(void*)dlopen_preflight_compat },
	{"__dyld_image_count",								(void*)_dyld_image_count },
    {"__dyld_get_image_header",							(void*)_dyld_get_image_header },
    {"__dyld_get_image_vmaddr_slide",					(void*)_dyld_get_image_vmaddr_slide },
    {"__dyld_get_image_name",							(void*)_dyld_get_image_name },
    {"__dyld_get_image_slide",							(void*)_dyld_get_image_slide },
    {"__dyld_get_prog_image_header",					(void*)_dyld_get_prog_image_header },
    {"__dyld__NSGetExecutablePath",						(void*)_NSGetExecutablePath },

	// SPIs
  	{"__dyld_register_thread_helpers",					(void*)registerThreadHelpers },
	{"__dyld_fork_child",								(void*)_dyld_fork_child },
    {"__dyld_make_delayed_module_initializer_calls",	(void*)_dyld_make_delayed_module_initializer_calls },
	{"__dyld_get_all_image_infos",						(void*)_dyld_get_all_image_infos },
#if SUPPORT_ZERO_COST_EXCEPTIONS
	{"__dyld_find_unwind_sections",						(void*)client_dyld_find_unwind_sections },
#endif
#if __i386__ || __x86_64__ || __arm__ || __arm64__
	{"__dyld_fast_stub_entry",							(void*)dyld::fastBindLazySymbol },
#endif
	{"__dyld_image_path_containing_address",			(void*)dyld_image_path_containing_address },
	{"__dyld_shared_cache_some_image_overridden",		(void*)dyld_shared_cache_some_image_overridden },
	{"__dyld_process_is_restricted",					(void*)dyld::processIsRestricted },
	{"__dyld_dynamic_interpose",						(void*)dyld_dynamic_interpose },
	{"__dyld_shared_cache_file_path",					(void*)dyld::getStandardSharedCacheFilePath },
	{"__dyld_has_inserted_or_interposing_libraries",	(void*)dyld::hasInsertedOrInterposingLibraries },
    {"__dyld_get_image_header_containing_address",		(void*)dyld_image_header_containing_address },
    {"__dyld_is_memory_immutable",						(void*)_dyld_is_memory_immutable },
    {"__dyld_objc_notify_register",						(void*)_dyld_objc_notify_register },
    {"__dyld_get_shared_cache_uuid",					(void*)_dyld_get_shared_cache_uuid },
    {"__dyld_get_shared_cache_range",					(void*)_dyld_get_shared_cache_range },
    {"__dyld_images_for_addresses",						(void*)_dyld_images_for_addresses },
    {"__dyld_register_for_image_loads",					(void*)_dyld_register_for_image_loads },
    {"__dyld_register_for_bulk_image_loads",			(void*)_dyld_register_for_bulk_image_loads },
    {"__dyld_register_driverkit_main",					(void*)_dyld_register_driverkit_main },
    {"__dyld_halt",										(void*)dyld::halt },

#if DEPRECATED_APIS_SUPPORTED
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
    {"__dyld_lookup_and_bind",						(void*)client_dyld_lookup_and_bind },
    {"__dyld_lookup_and_bind_with_hint",			(void*)_dyld_lookup_and_bind_with_hint },
    {"__dyld_lookup_and_bind_fully",				(void*)_dyld_lookup_and_bind_fully },
    {"__dyld_install_handlers",						(void*)_dyld_install_handlers },
    {"__dyld_link_edit_error",						(void*)NSLinkEditError },
    {"__dyld_unlink_module",						(void*)NSUnLinkModule },
    {"__dyld_bind_fully_image_containing_address",  (void*)_dyld_bind_fully_image_containing_address },
    {"__dyld_image_containing_address",				(void*)_dyld_image_containing_address },
    {"__dyld_register_binding_handler",				(void*)_dyld_register_binding_handler },
    {"__dyld_NSNameOfSymbol",						(void*)NSNameOfSymbol },
    {"__dyld_NSAddressOfSymbol",					(void*)NSAddressOfSymbol },
    {"__dyld_NSModuleForSymbol",					(void*)NSModuleForSymbol },
    {"__dyld_NSLookupAndBindSymbol",				(void*)NSLookupAndBindSymbol },
    {"__dyld_NSLookupAndBindSymbolWithHint",		(void*)NSLookupAndBindSymbolWithHint },
    {"__dyld_NSLookupSymbolInModule",				(void*)NSLookupSymbolInModule},
    {"__dyld_NSLookupSymbolInImage",				(void*)NSLookupSymbolInImage},
    {"__dyld_NSMakePrivateModulePublic",			(void*)NSMakePrivateModulePublic},
    {"__dyld_NSIsSymbolNameDefined",				(void*)client_NSIsSymbolNameDefined},
    {"__dyld_NSIsSymbolNameDefinedWithHint",		(void*)NSIsSymbolNameDefinedWithHint },
    {"__dyld_NSIsSymbolNameDefinedInImage",			(void*)NSIsSymbolNameDefinedInImage},
    {"__dyld_NSNameOfModule",						(void*)NSNameOfModule },
    {"__dyld_NSLibraryNameForModule",				(void*)NSLibraryNameForModule },
    {"__dyld_NSAddLibrary",							(void*)NSAddLibrary },
    {"__dyld_NSAddLibraryWithSearching",			(void*)NSAddLibraryWithSearching },
    {"__dyld_NSAddImage",							(void*)NSAddImage },
    {"__dyld_launched_prebound",					(void*)_dyld_launched_prebound },
    {"__dyld_all_twolevel_modules_prebound",		(void*)_dyld_all_twolevel_modules_prebound },
    {"__dyld_call_module_initializers_for_dylib",   (void*)_dyld_call_module_initializers_for_dylib },
    {"__dyld_NSCreateObjectFileImageFromFile",			(void*)NSCreateObjectFileImageFromFile },
    {"__dyld_NSCreateObjectFileImageFromMemory",		(void*)NSCreateObjectFileImageFromMemory },
    {"__dyld_NSDestroyObjectFileImage",					(void*)NSDestroyObjectFileImage },
    {"__dyld_NSLinkModule",								(void*)NSLinkModule },
    {"__dyld_NSSymbolDefinitionCountInObjectFileImage",	(void*)NSSymbolDefinitionCountInObjectFileImage },
    {"__dyld_NSSymbolDefinitionNameInObjectFileImage",	(void*)NSSymbolDefinitionNameInObjectFileImage },
    {"__dyld_NSIsSymbolDefinedInObjectFileImage",		(void*)NSIsSymbolDefinedInObjectFileImage },
    {"__dyld_NSSymbolReferenceNameInObjectFileImage",	(void*)NSSymbolReferenceNameInObjectFileImage },
    {"__dyld_NSSymbolReferenceCountInObjectFileImage",	(void*)NSSymbolReferenceCountInObjectFileImage },
    {"__dyld_NSGetSectionDataInObjectFileImage",		(void*)NSGetSectionDataInObjectFileImage },
#if OLD_LIBSYSTEM_SUPPORT
    {"__dyld_link_module",							(void*)_dyld_link_module },
#endif
#pragma clang diagnostic pop
#endif //DEPRECATED_APIS_SUPPORTED

    {NULL, 0}
};



#if DEPRECATED_APIS_SUPPORTED

static void dyldAPIhalt(const char* apiName, const char* errorMsg)
{
	dyld::log("dyld: %s() error\n", apiName);
	dyld::halt(errorMsg);
}

// dyld's abstract type NSSymbol is implemented as const ImageLoader::Symbol*
inline NSSymbol SymbolToNSSymbol(const ImageLoader::Symbol* sym)
{
	return (NSSymbol)sym;
}	
inline const ImageLoader::Symbol* NSSymbolToSymbol(NSSymbol sym)
{
	return (const ImageLoader::Symbol*)sym;
}	

// dyld's abstract type NSModule is implemented as ImageLoader*
inline NSModule ImageLoaderToNSModule(const ImageLoader* image)
{
	return (NSModule)image;
}	
inline ImageLoader* NSModuleToImageLoader(NSModule module)
{
	ImageLoader* image = (ImageLoader*)module;
	if ( dyld::validImage(image) )
		return image;
	return NULL;
}

// actual definition for opaque type
struct __NSObjectFileImage
{
	ImageLoader*	image;	
	const void*		imageBaseAddress;	// not used with OFI created from files
	size_t			imageLength;		// not used with OFI created from files
};
typedef __NSObjectFileImage*  NSObjectFileImage;


VECTOR_NEVER_DESTRUCTED(NSObjectFileImage);
static std::vector<NSObjectFileImage> sObjectFileImages;



//
// __NSObjectFileImage are deleted in NSDestroyObjectFileImage()
// The contained image is delete in one of two places:
//	NSUnLinkModule deletes the image if there is no __NSObjectFileImage with a reference to it
//	NSDestroyObjectFileImage deletes the image if image is not in list of valid images
//



static void setLastError(NSLinkEditErrors code, int errnum, const char* file, const char* message)
{
	dyld::setErrorMessage(message);
	strncpy(sLastErrorFilePath, file, 1024);
	sLastErrorFilePath[1023] = '\0';
	sLastErrorFileCode = code;
	sLastErrorNo = errnum;
}

#endif // DEPRECATED_APIS_SUPPORTED

/*
 *_dyld_NSGetExecutablePath is the dyld side of _NSGetExecutablePath which
 * copies the path of the executable into the buffer and returns 0 if the path
 * was successfully copied in the provided buffer. If the buffer is not large
 * enough, -1 is returned and the expected buffer size is copied in *bufsize.
 * Note that _NSGetExecutablePath will return "a path" to the executable not a
 * "real path" to the executable. That is the path may be a symbolic link and
 * not the real file. And with deep directories the total bufsize needed could
 * be more than MAXPATHLEN.
 */
int _NSGetExecutablePath(char* buf, uint32_t *bufsize)
{
	if ( dyld::gLogAPIs )
		dyld::log("%s(...)\n", __func__);
	const char* exePath = dyld::getExecutablePath();
	if(*bufsize < strlen(exePath) + 1){
	    *bufsize = (uint32_t)(strlen(exePath) + 1);
	    return -1;
	}
	strcpy(buf, exePath);
	return 0;
}

uint32_t _dyld_image_count(void)
{
	if ( dyld::gLogAPIs )
		dyld::log("%s()\n", __func__);
	return allImagesCount();
}

const struct mach_header* _dyld_get_image_header(uint32_t image_index)
{
	if ( dyld::gLogAPIs )
		dyld::log("%s(%u)\n", __func__, image_index);
	return allImagesIndexedMachHeader(image_index);
}

intptr_t _dyld_get_image_vmaddr_slide(uint32_t image_index)
{
	if ( dyld::gLogAPIs )
		dyld::log("%s(%u)\n", __func__, image_index);
	const struct mach_header* mh = allImagesIndexedMachHeader(image_index);
	if ( mh != NULL )
		return ImageLoaderMachO::computeSlide(mh);
	else
		return 0;
}

intptr_t _dyld_get_image_slide(const struct mach_header* mh)
{
	if ( dyld::gLogAPIs )
		dyld::log("%s(%p)\n", __func__, mh);
	return ImageLoaderMachO::computeSlide(mh);
}


const char* _dyld_get_image_name(uint32_t image_index)
{
	if ( dyld::gLogAPIs )
		dyld::log("%s(%u)\n", __func__, image_index);
	return allImagesIndexedPath(image_index);
}

const struct mach_header* _dyld_get_prog_image_header()
{
	if ( dyld::gLogAPIs )
		dyld::log("%s()\n", __func__);
	
	return dyld::mainExecutable()->machHeader();
}

static const void *stripPointer(const void *ptr) {
#if __has_feature(ptrauth_calls)
	return __builtin_ptrauth_strip(ptr, ptrauth_key_asia);
#else
	return ptr;
#endif
}

static void *stripPointer(void *ptr) {
#if __has_feature(ptrauth_calls)
	return __builtin_ptrauth_strip(ptr, ptrauth_key_asia);
#else
	return ptr;
#endif
}

const struct mach_header * dyld_image_header_containing_address(const void* address)
{
	if ( dyld::gLogAPIs )
		dyld::log("%s(%p)\n", __func__, address);
	address = stripPointer(address);
#if SUPPORT_ACCELERATE_TABLES
	const mach_header* mh;
	const char* path;
	if ( dyld::addressInCache(address, &mh, &path) )
		return mh;
#endif
	ImageLoader* image = dyld::findImageContainingAddress(address);
	if ( image != NULL )
		return image->machHeader();
	return NULL;
}


void _dyld_register_func_for_add_image(void (*func)(const struct mach_header *mh, intptr_t vmaddr_slide))
{
	if ( dyld::gLogAPIs )
		dyld::log("%s(%p)\n", __func__, (void *)func);
	dyld::registerAddCallback(func);
}

void _dyld_register_func_for_remove_image(void (*func)(const struct mach_header *mh, intptr_t vmaddr_slide))
{
	if ( dyld::gLogAPIs )
		dyld::log("%s(%p)\n", __func__, (void *)func);
	dyld::registerRemoveCallback(func);
}



// called by crt before main() by programs linked with 10.4 or earlier crt1.o
static void _dyld_make_delayed_module_initializer_calls()
{
	if ( dyld::gLogAPIs )
		dyld::log("%s()\n", __func__);
		
#if SUPPORT_OLD_CRT_INITIALIZATION
	if ( dyld::gRunInitializersOldWay )
		dyld::initializeMainExecutable();
#endif
}



#if DEPRECATED_APIS_SUPPORTED

//
// _dyld_call_module_initializers_for_dylib() is the dyld side of
// __initialize_Cplusplus() which is in dylib1.o.
// It is intended to only be called inside -init rouintes.
// -init routines are called before module initializers (what C++
// initializers use).  Calling __initialize_Cplusplus() in a -init
// routine causes the module initializers for an image to be called
// which then allows C++ to be used inside a -init routine
//
static void _dyld_call_module_initializers_for_dylib(const struct mach_header* mh_dylib_header)
{
	if ( dyld::gLogAPIs )
		dyld::log("__initialize_Cplusplus()\n");
	
	// for now, do nothing...
}


void _dyld_lookup_and_bind_fully(const char* symbolName, void** address, NSModule* module)
{
	if ( dyld::gLogAPIs )
		dyld::log("%s(\"%s\", %p, %p)\n", __func__, symbolName, address, module);
	ImageLoader* image;
	const ImageLoader::Symbol* sym;
	dyld::clearErrorMessage();
	if ( dyld::flatFindExportedSymbol(symbolName, &sym, (const ImageLoader**)&image) ) {	
		try {
			image->bindAllLazyPointers(dyld::gLinkContext, true);
			if ( address != NULL)
				*address = (void*)image->getExportedSymbolAddress(sym, dyld::gLinkContext);
			if ( module != NULL)
				*module = ImageLoaderToNSModule(image);
		}
		catch (const char* msg) {
			dyldAPIhalt(__func__, msg);
		}
	}
	else {
		// on failure to find symbol return NULLs
		if ( address != NULL)
			*address = NULL;
		if ( module != NULL)
			*module = NULL;
	}
}

// Note: This cannot have public name because dyld is built with a static copy of libc.a
// which calls dyld_lookup_and_bind() and expects to find dyld's symbols not host process
static void client_dyld_lookup_and_bind(const char* symbolName, void** address, NSModule* module)
{
	if ( dyld::gLogAPIs )
		dyld::log("_dyld_lookup_and_bind(\"%s\", %p, %p)\n", symbolName, address, module);
	const ImageLoader* image;
	const ImageLoader::Symbol* sym;
	if ( dyld::flatFindExportedSymbol(symbolName, &sym, &image) ) {
		if ( address != NULL)
			*address = (void*)image->getExportedSymbolAddress(sym, dyld::gLinkContext);
		if ( module != NULL)
			*module = ImageLoaderToNSModule(image);
	}
	else {
		// on failure to find symbol return NULLs
		if ( address != NULL)
			*address = NULL;
		if ( module != NULL)
			*module = NULL;
	}
}

void _dyld_lookup_and_bind_with_hint(const char* symbolName, const char* library_name_hint, void** address, NSModule* module)
{
	if ( dyld::gLogAPIs )
		dyld::log("%s(\"%s\", \"%s\", %p, %p)\n", __func__, symbolName, library_name_hint, address, module);
	const ImageLoader* image;
	const ImageLoader::Symbol* sym;
	// Look for library whose path contains the hint.  If that fails search everywhere
	if (  dyld::flatFindExportedSymbolWithHint(symbolName, library_name_hint, &sym, &image) 
	  ||  dyld::flatFindExportedSymbol(symbolName, &sym, &image) ) {
		if ( address != NULL)
			*address = (void*)image->getExportedSymbolAddress(sym, dyld::gLinkContext);
		if ( module != NULL)
			*module = ImageLoaderToNSModule(image);
	}
	else {
		// on failure to find symbol return NULLs
		if ( address != NULL)
			*address = NULL;
		if ( module != NULL)
			*module = NULL;
	}
}


NSSymbol NSLookupAndBindSymbol(const char *symbolName)
{
	if ( dyld::gLogAPIs )
		dyld::log("%s(\"%s\")\n", __func__, symbolName);
	const ImageLoader* image;
	const ImageLoader::Symbol* sym;
	if ( dyld::flatFindExportedSymbol(symbolName, &sym, &image) ) {
		return SymbolToNSSymbol(sym);
	}
	// return NULL on failure
	return NULL;
}

NSSymbol NSLookupAndBindSymbolWithHint(const char* symbolName, const char* libraryNameHint)
{
	if ( dyld::gLogAPIs )
		dyld::log("%s(\"%s\", \"%s\")\n", __func__, symbolName, libraryNameHint);
	const ImageLoader* image;
	const ImageLoader::Symbol* sym;
	bool found = dyld::flatFindExportedSymbolWithHint(symbolName, libraryNameHint, &sym, &image);
	if ( ! found ) {
		// hint failed, do slow search of all images
		 found = dyld::flatFindExportedSymbol(symbolName, &sym, &image);
	}
	if ( found )
		return SymbolToNSSymbol(sym);
		
	// return NULL on failure and log
	if ( dyld::gLogAPIs )
		dyld::log("%s(\"%s\", \"%s\") => NULL \n", __func__, symbolName, libraryNameHint);
	return NULL;
}




static __attribute__((noinline)) 
const struct mach_header* addImage(void* callerAddress, const char* path, bool search, bool dontLoad, bool matchInstallName, bool abortOnError)
{
	ImageLoader*	image = NULL;
	std::vector<const char*> rpathsFromCallerImage;
	try {
		dyld::clearErrorMessage();
		ImageLoader* callerImage = dyld::findImageContainingAddress(callerAddress);
		// like dlopen, use rpath from caller image and from main executable
		if ( callerImage != NULL )
			callerImage->getRPaths(dyld::gLinkContext, rpathsFromCallerImage);
		ImageLoader::RPathChain callersRPaths(NULL, &rpathsFromCallerImage);
		if ( callerImage != dyld::mainExecutable() ) {
			dyld::mainExecutable()->getRPaths(dyld::gLinkContext, rpathsFromCallerImage);
		}
		dyld::LoadContext context;
		context.useSearchPaths		= search;
		context.useFallbackPaths	= search;
		context.useLdLibraryPath	= false;
		context.implicitRPath		= false;
		context.matchByInstallName	= matchInstallName;
		context.dontLoad			= dontLoad;
		context.mustBeBundle		= false;
		context.mustBeDylib			= true;
		context.canBePIE			= false;
		context.origin				= callerImage != NULL ? callerImage->getPath() : NULL; // caller's image's path
		context.rpath				= &callersRPaths; 	// rpaths from caller and main executable

		unsigned cacheIndex;
		image = load(path, context, cacheIndex);
		if ( image != NULL ) {
			if ( context.matchByInstallName )
				image->setMatchInstallPath(true);
			dyld::link(image, false, false, callersRPaths, cacheIndex);
			dyld::runInitializers(image);
			// images added with NSAddImage() can never be unloaded
			image->setNeverUnload(); 
		}
	}
	catch (const char* msg) {
		dyld::garbageCollectImages();
		if ( abortOnError) {
			char pathMsg[strlen(msg)+strlen(path)+4];
			strcpy(pathMsg, msg);
			strcat(pathMsg, " ");
			strcat(pathMsg, path);
			dyldAPIhalt("NSAddImage", pathMsg);
		}
		// not halting, so set error state for NSLinkEditError to find
		setLastError(NSLinkEditOtherError, 0, path, msg);
		free((void*)msg); 	// our free() will do nothing if msg is a string literal
		image = NULL;
	}
	// free rpaths (getRPaths() malloc'ed each string)
	for(std::vector<const char*>::iterator it=rpathsFromCallerImage.begin(); it != rpathsFromCallerImage.end(); ++it) {
		const char* str = *it;
		free((void*)str);
	}
	if ( image == NULL )
		return NULL;
	else
		return image->machHeader();
}


const struct mach_header* NSAddImage(const char* path, uint32_t options)
{
	if ( dyld::gLogAPIs )
		dyld::log("%s(\"%s\", 0x%08X)\n", __func__, path, options);
	const bool dontLoad = ( (options & NSADDIMAGE_OPTION_RETURN_ONLY_IF_LOADED) != 0 );
	const bool search = ( (options & NSADDIMAGE_OPTION_WITH_SEARCHING) != 0 );
	const bool matchInstallName = ( (options & NSADDIMAGE_OPTION_MATCH_FILENAME_BY_INSTALLNAME) != 0 );
	const bool abortOnError = ( (options & (NSADDIMAGE_OPTION_RETURN_ON_ERROR|NSADDIMAGE_OPTION_RETURN_ONLY_IF_LOADED)) == 0 );
	void* callerAddress = __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
	return addImage(callerAddress, path, search, dontLoad, matchInstallName, abortOnError);
}

bool NSAddLibrary(const char* path)
{
	if ( dyld::gLogAPIs )
		dyld::log("%s(\"%s\")\n", __func__, path);
	void* callerAddress = __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
	return (addImage(callerAddress, path, false, false, false, false) != NULL);
}

bool NSAddLibraryWithSearching(const char* path)
{
	if ( dyld::gLogAPIs )
		dyld::log("%s(\"%s\")\n", __func__, path);
	void* callerAddress = __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
	return (addImage(callerAddress, path, true, false, false, false) != NULL);
}



//#define NSADDIMAGE_OPTION_NONE                  	0x0
//#define NSADDIMAGE_OPTION_RETURN_ON_ERROR       	0x1
//#define NSADDIMAGE_OPTION_MATCH_FILENAME_BY_INSTALLNAME	0x8

bool NSIsSymbolNameDefinedInImage(const struct mach_header* mh, const char* symbolName)
{
	if ( dyld::gLogAPIs )
		dyld::log("%s(%p, \"%s\")\n", __func__, (void *)mh, symbolName);
	ImageLoader* image = dyld::findImageByMachHeader(mh);
	if ( image != NULL ) {
		if ( image->findExportedSymbol(symbolName, true, NULL) != NULL)
			return true;
	}
	return false;
}


NSSymbol NSLookupSymbolInImage(const struct mach_header* mh, const char* symbolName, uint32_t options)
{
	if ( dyld::gLogAPIs )
		dyld::log("%s(%p, \"%s\", 0x%08X)\n", __func__, mh, symbolName, options);
	const ImageLoader::Symbol* symbol = NULL;
	dyld::clearErrorMessage();
	ImageLoader* image = dyld::findImageByMachHeader(mh);
	if ( image != NULL ) {
		const char* symbolToFind = symbolName;
		try {
			if ( options & NSLOOKUPSYMBOLINIMAGE_OPTION_BIND_FULLY ) {
				image->bindAllLazyPointers(dyld::gLinkContext, true);
			}
			else if ( options & NSLOOKUPSYMBOLINIMAGE_OPTION_BIND_NOW ) {
				image->bindAllLazyPointers(dyld::gLinkContext, false);
			}
		}
		catch (const char* msg) {
			if ( (options & NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR) == 0 ) {
				dyldAPIhalt(__func__, msg);
			}
		}
		symbol = image->findExportedSymbol(symbolToFind, true, NULL);
	}
	if ( dyld::gLogAPIs && (symbol == NULL) )
		dyld::log("%s(%p, \"%s\", 0x%08X) ==> NULL\n", __func__, mh, symbolName, options);
	return SymbolToNSSymbol(symbol);
}


// Note: This cannot have public name because dyld is built with a static copy of libc.a
// which calls NSIsSymbolNameDefined() and expects to find dyld's symbols not host process
static bool client_NSIsSymbolNameDefined(const char* symbolName)
{
	if ( dyld::gLogAPIs )
		dyld::log("NSIsSymbolNameDefined(\"%s\")\n", symbolName);
	const ImageLoader* image;
	const ImageLoader::Symbol* sym;
	return dyld::flatFindExportedSymbol(symbolName, &sym, &image);
}

bool NSIsSymbolNameDefinedWithHint(const char* symbolName, const char* libraryNameHint)
{
	if ( dyld::gLogAPIs )
		dyld::log("%s(\"%s\", \"%s\")\n", __func__, symbolName, libraryNameHint);
	const ImageLoader* image;
	const ImageLoader::Symbol* sym;
	bool found = dyld::flatFindExportedSymbolWithHint(symbolName, libraryNameHint, &sym, &image);
	if ( ! found ) {
		// hint failed, do slow search of all images
		 found = dyld::flatFindExportedSymbol(symbolName, &sym, &image);
	}
	if ( !found && dyld::gLogAPIs )
		dyld::log("%s(\"%s\", \"%s\") => false \n", __func__, symbolName, libraryNameHint);
	return found;
}

const char* NSNameOfSymbol(NSSymbol symbol)
{
	if ( dyld::gLogAPIs )
		dyld::log("%s(%p)\n", __func__, (void *)symbol);
	const char* result = NULL;
	ImageLoader* image = dyld::findImageContainingSymbol(symbol);
	if ( image != NULL ) 
		result = image->getExportedSymbolName(NSSymbolToSymbol(symbol));
	return result;
}

void* NSAddressOfSymbol(NSSymbol symbol)
{
	if ( dyld::gLogAPIs )
		dyld::log("%s(%p)\n", __func__, (void *)symbol);
	if ( symbol == NULL )
		return NULL;
	void* result = NULL;
	ImageLoader* image = dyld::findImageContainingSymbol(symbol);
	if ( image != NULL ) 
		result = (void*)image->getExportedSymbolAddress(NSSymbolToSymbol(symbol), dyld::gLinkContext);

#if __has_feature(ptrauth_calls)
	// Sign the pointer if it points to a function
	if ( result ) {
		const ImageLoader* symbolImage = image;
		if (!symbolImage->containsAddress(result)) {
			symbolImage = dyld::findImageContainingAddress(result);
		}
		const macho_section *sect = symbolImage ? symbolImage->findSection(result) : NULL;
		if ( sect && ((sect->flags & S_ATTR_PURE_INSTRUCTIONS) || (sect->flags & S_ATTR_SOME_INSTRUCTIONS)) )
			result = __builtin_ptrauth_sign_unauthenticated(result, ptrauth_key_asia, 0);
	}
#endif
	return result;
}

NSModule NSModuleForSymbol(NSSymbol symbol)
{
	if ( dyld::gLogAPIs )
		dyld::log("%s(%p)\n", __func__, (void *)symbol);
	NSModule result = NULL;
	ImageLoader* image = dyld::findImageContainingSymbol(symbol);
	if ( image != NULL ) 
		result = ImageLoaderToNSModule(image);
	return result;
}




bool _dyld_all_twolevel_modules_prebound(void)
{
	if ( dyld::gLogAPIs )
		dyld::log("%s()\n", __func__);
	return FALSE; 
}

bool _dyld_bind_fully_image_containing_address(const void* address)
{
	if ( dyld::gLogAPIs )
		dyld::log("%s(%p)\n", __func__, address);
	address = stripPointer(address);
	dyld::clearErrorMessage();
	ImageLoader* image = dyld::findImageContainingAddress(address);
	if ( image != NULL ) {
		try {
			image->bindAllLazyPointers(dyld::gLinkContext, true);
			return true;
		}
		catch (const char* msg) {
			dyldAPIhalt(__func__, msg);
		}
	}
	return false;
}

bool _dyld_image_containing_address(const void* address)
{
	if ( dyld::gLogAPIs )
		dyld::log("%s(%p)\n", __func__, address);
	ImageLoader *imageLoader = dyld::findImageContainingAddress(address);
	return (NULL != imageLoader);
}

static NSObjectFileImage createObjectImageFile(ImageLoader* image, const void* address = NULL, size_t len=0)
{
	NSObjectFileImage result = new __NSObjectFileImage();
	result->image = image;
	result->imageBaseAddress = address;
	result->imageLength = len;
	sObjectFileImages.push_back(result);
	return result;
}

NSObjectFileImageReturnCode NSCreateObjectFileImageFromFile(const char* pathName, NSObjectFileImage *objectFileImage)
{
	if ( dyld::gLogAPIs )
		dyld::log("%s(\"%s\", ...)\n", __func__, pathName);
	try {
		void* callerAddress = __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
		ImageLoader* callerImage = dyld::findImageContainingAddress(callerAddress);

		dyld::LoadContext context;
		context.useSearchPaths		= false;
		context.useFallbackPaths	= false;
		context.useLdLibraryPath	= false;
		context.implicitRPath		= false;
		context.matchByInstallName	= false;
		context.dontLoad			= false;
		context.mustBeBundle		= true;
		context.mustBeDylib			= false;
		context.canBePIE			= false;
		context.origin				= callerImage != NULL ? callerImage->getPath() : NULL; // caller's image's path
		context.rpath				= NULL; // support not yet implemented

		unsigned cacheIndex;
		ImageLoader* image = dyld::load(pathName, context, cacheIndex);
		// Note:  We DO NOT link the image!  NSLinkModule will do that
		if ( image != NULL ) {
			if ( !image->isBundle() ) {
				// the image must have been already loaded (since context.mustBeBundle will prevent it from being loaded)
				return NSObjectFileImageInappropriateFile;
			}
			*objectFileImage = createObjectImageFile(image);
			return NSObjectFileImageSuccess;
		}
	}
	catch (const char* msg) {
		//dyld::log("dyld: NSCreateObjectFileImageFromFile() error: %s\n", msg);
		dyld::garbageCollectImages();
		free((void*)msg);
		return NSObjectFileImageInappropriateFile;
	}
	return NSObjectFileImageFailure;
}


NSObjectFileImageReturnCode NSCreateObjectFileImageFromMemory(const void* address, size_t size, NSObjectFileImage *objectFileImage)
{
	if ( dyld::gLogAPIs )
		dyld::log("%s(%p, %lu, %p)\n", __func__, address, size, objectFileImage);
	
	try {
		ImageLoader* image = dyld::loadFromMemory((const uint8_t*)address, size, NULL); 
		if ( ! image->isBundle() ) {
			// this API can only be used with bundles...
			dyld::garbageCollectImages();
			return NSObjectFileImageInappropriateFile;
		}
		// Note:  We DO NOT link the image!  NSLinkModule will do that
		if ( image != NULL ) {
			*objectFileImage = createObjectImageFile(image, address, size);
			return NSObjectFileImageSuccess;
		}
	}
	catch (const char* msg) {
		free((void*)msg);
		dyld::garbageCollectImages();
		//dyld::log("dyld: NSCreateObjectFileImageFromMemory() error: %s\n", msg);
	}
	return NSObjectFileImageFailure;
}

static bool validOFI(NSObjectFileImage objectFileImage)
{
	const size_t ofiCount = sObjectFileImages.size();
	for (size_t i=0; i < ofiCount; ++i) {
		if ( sObjectFileImages[i] == objectFileImage )
			return true;
	}
	return false;
}

bool NSDestroyObjectFileImage(NSObjectFileImage objectFileImage)
{
	if ( dyld::gLogAPIs )
		dyld::log("%s(%p)\n", __func__, objectFileImage);
	
	if ( validOFI(objectFileImage) ) {
		// a failure during NSLinkModule will delete the image
		if ( objectFileImage->image != NULL ) {
			// if the image has never been linked or has been unlinked, the image is not in the list of valid images
			// and we should delete it
			bool linkedImage = dyld::validImage(objectFileImage->image);
			if ( ! linkedImage )  {
				ImageLoader::deleteImage(objectFileImage->image);
				objectFileImage->image = NULL;
			}
		}
		
		// remove from list of ofi's
		for (std::vector<NSObjectFileImage>::iterator it=sObjectFileImages.begin(); it != sObjectFileImages.end(); it++) {
			if ( *it == objectFileImage ) {
				sObjectFileImages.erase(it);
				break;
			}
		}
		
		// if object was created from a memory, release that memory
		// NOTE: this is the way dyld has always done this. NSCreateObjectFileImageFromMemory() hands over ownership of the memory to dyld
		if ( objectFileImage->imageBaseAddress != NULL ) {
			bool freed = false;
			if ( (dyld::gLibSystemHelpers != NULL) && (dyld::gLibSystemHelpers->version >= 6) ) {
				size_t sz = (*dyld::gLibSystemHelpers->malloc_size)(objectFileImage->imageBaseAddress);
				if ( sz != 0 ) {
					(*dyld::gLibSystemHelpers->free)((void*)(objectFileImage->imageBaseAddress));
					freed = true;
				}
			}
			if ( ! freed )
				vm_deallocate(mach_task_self(), (vm_address_t)objectFileImage->imageBaseAddress, objectFileImage->imageLength);
		}
		
		// free ofi object
		delete objectFileImage;
		
		return true;
	}
	return false;
}

uint32_t NSSymbolDefinitionCountInObjectFileImage(NSObjectFileImage objectFileImage)
{
	if ( dyld::gLogAPIs )
		dyld::log("%s(%p)\n", __func__, objectFileImage);
	return objectFileImage->image->getExportedSymbolCount();
}

const char* NSSymbolDefinitionNameInObjectFileImage(NSObjectFileImage objectFileImage, uint32_t ordinal)
{
	if ( dyld::gLogAPIs )
		dyld::log("%s(%p,%d)\n", __func__, objectFileImage, ordinal);
	const ImageLoader::Symbol* sym = objectFileImage->image->getIndexedExportedSymbol(ordinal);
	return objectFileImage->image->getExportedSymbolName(sym);	
}

uint32_t NSSymbolReferenceCountInObjectFileImage(NSObjectFileImage objectFileImage)
{
	if ( dyld::gLogAPIs )
		dyld::log("%s(%p)\n", __func__, objectFileImage);
	return objectFileImage->image->getImportedSymbolCount();
}

const char * NSSymbolReferenceNameInObjectFileImage(NSObjectFileImage objectFileImage, uint32_t ordinal, 
													bool* tentative_definition)
{
	if ( dyld::gLogAPIs )
		dyld::log("%s(%p,%d)\n", __func__, objectFileImage, ordinal);
	const ImageLoader::Symbol* sym = objectFileImage->image->getIndexedImportedSymbol(ordinal);
	if ( tentative_definition != NULL ) {
		ImageLoader::ReferenceFlags flags = objectFileImage->image->getImportedSymbolInfo(sym);
		if ( (flags & ImageLoader::kTentativeDefinition) != 0 )
			*tentative_definition = true;
		else
			*tentative_definition = false;
	}
	return objectFileImage->image->getImportedSymbolName(sym);	
}

void* NSGetSectionDataInObjectFileImage(NSObjectFileImage objectFileImage,
										const char* segmentName, const char* sectionName, unsigned long* size)
{
	if ( dyld::gLogAPIs )
		dyld::log("%s(%p,%s, %s)\n", __func__, objectFileImage, segmentName, sectionName);

	void* start;
	size_t length;
	if ( objectFileImage->image->getSectionContent(segmentName, sectionName, &start, &length) ) {
		if ( size != NULL )
			*size = length;
		return start;
	}
	return NULL;
}



bool NSIsSymbolDefinedInObjectFileImage(NSObjectFileImage objectFileImage, const char* symbolName)
{
	if ( dyld::gLogAPIs )
		dyld::log("%s(%p,%s)\n", __func__, objectFileImage, symbolName);
	const ImageLoader::Symbol* sym = objectFileImage->image->findExportedSymbol(symbolName, true, NULL);
	return ( sym != NULL );
}



NSModule NSLinkModule(NSObjectFileImage objectFileImage, const char* moduleName, uint32_t options)
{
	if ( dyld::gLogAPIs )
		dyld::log("%s(%p, \"%s\", 0x%08X)\n", __func__, objectFileImage, moduleName, options); 
	
	dyld::clearErrorMessage();
	try {
		if ( (options & NSLINKMODULE_OPTION_CAN_UNLOAD) != 0 )
			objectFileImage->image->setCanUnload();

		// NSLinkModule allows a bundle to be link multpile times
		// each link causes the bundle to be copied to a new address
		if ( objectFileImage->image->isLinked() ) {
			// already linked, so clone a new one and link it
			objectFileImage->image = dyld::cloneImage(objectFileImage->image);
		}
		
		// for memory based images, set moduleName as the name anyone calling _dyld_get_image_name() will see
		if ( objectFileImage->image->getPath() == NULL ) {
			objectFileImage->image->setPath(moduleName);
			// <rdar://problem/8812589> dyld has NULL paths in image info array
			dyld_image_info info;
			info.imageLoadAddress = objectFileImage->image->machHeader();
			info.imageFilePath = moduleName;
			info.imageFileModDate = 0;
			addImagesToAllImages(1, &info);
		}

		// support private bundles
		if ( (options & NSLINKMODULE_OPTION_PRIVATE) != 0 )
			objectFileImage->image->setHideExports();
	
		// set up linking options
		bool forceLazysBound = ( (options & NSLINKMODULE_OPTION_BINDNOW) != 0 );
		
		// load libraries, rebase, bind, to make this image usable
		dyld::link(objectFileImage->image, forceLazysBound, false, ImageLoader::RPathChain(NULL,NULL), UINT32_MAX);
		
		// bump reference count to keep this bundle from being garbage collected
		objectFileImage->image->incrementDlopenReferenceCount();

		// run initializers unless magic flag says not to
		if ( (options & NSLINKMODULE_OPTION_DONT_CALL_MOD_INIT_ROUTINES) == 0 )
			dyld::runInitializers(objectFileImage->image);

		return ImageLoaderToNSModule(objectFileImage->image);
	}
	catch (const char* msg) {
		dyld::garbageCollectImages();
		if ( (options & NSLINKMODULE_OPTION_RETURN_ON_ERROR) == 0 )
			dyldAPIhalt(__func__, msg);
		// not halting, so set error state for NSLinkEditError to find
		setLastError(NSLinkEditOtherError, 0, moduleName, msg);
		// dyld::link() deleted the image so lose our reference
		objectFileImage->image = NULL;
		free((void*)msg);
		return NULL;
	}
}


#if OLD_LIBSYSTEM_SUPPORT
// This is for compatibility with old libSystems (libdyld.a) which process ObjectFileImages outside dyld
static NSModule _dyld_link_module(NSObjectFileImage object_addr, size_t object_size, const char* moduleName, uint32_t options)
{
	if ( dyld::gLogAPIs )
		dyld::log("%s(%p, \"%s\", 0x%08X)\n", "NSLinkModule", object_addr,  moduleName, options); // note name/args translation
	ImageLoader* image = NULL;
	dyld::clearErrorMessage();
	try {
		const char* imageName = moduleName;			
		image = dyld::loadFromMemory((const uint8_t*)object_addr, object_size, imageName); 
		
		if ( image != NULL ) {		
			// support private bundles
			if ( (options & NSLINKMODULE_OPTION_PRIVATE) != 0 )
				image->setHideExports();
		
			// set up linking options
			bool forceLazysBound = ( (options & NSLINKMODULE_OPTION_BINDNOW) != 0 );
			
			// load libraries, rebase, bind, to make this image usable
			dyld::link(image, forceLazysBound, false, ImageLoader::RPathChain(NULL,NULL), UINT32_MAX);
			
			// run initializers unless magic flag says not to
			if ( (options & NSLINKMODULE_OPTION_DONT_CALL_MOD_INIT_ROUTINES) == 0 )
				dyld::runInitializers(image);
		}
	}
	catch (const char* msg) {
		if ( (options & NSLINKMODULE_OPTION_RETURN_ON_ERROR) == 0 )
			dyldAPIhalt("NSLinkModule", msg);
		// not halting, so set error state for NSLinkEditError to find
		setLastError(NSLinkEditOtherError, 0, moduleName, msg);
		// if image was created for this bundle, destroy it
		if ( image != NULL ) {
			dyld::removeImage(image);
			ImageLoader::deleteImage(image);
		}
		image = NULL;
		free((void*)msg);
	}
	return ImageLoaderToNSModule(image);
}
#endif

NSSymbol NSLookupSymbolInModule(NSModule module, const char* symbolName)
{
	if ( dyld::gLogAPIs )
		dyld::log("%s(%p, \"%s\")\n", __func__, (void *)module, symbolName);
	ImageLoader* image = NSModuleToImageLoader(module);
	if ( image == NULL ) 
		return NULL;
	return SymbolToNSSymbol(image->findExportedSymbol(symbolName, false, NULL));
}

const char* NSNameOfModule(NSModule module)
{
	if ( dyld::gLogAPIs )
		dyld::log("%s(%p)\n", __func__, module);
	ImageLoader* image = NSModuleToImageLoader(module);
	if ( image == NULL ) 
		return NULL;
	return image->getPath();
}

const char* NSLibraryNameForModule(NSModule module)
{
	if ( dyld::gLogAPIs )
		dyld::log("%s(%p)\n", __func__, module);
	ImageLoader* image = NSModuleToImageLoader(module);
	if ( image == NULL ) 
		return NULL;
	return image->getPath();
}

bool NSUnLinkModule(NSModule module, uint32_t options)
{
	if ( dyld::gLogAPIs )
		dyld::log("%s(%p, 0x%08X)\n", __func__, module, options); 
	if ( module == NULL )
		return false;
	ImageLoader* image = NSModuleToImageLoader(module);
	if ( image == NULL ) 
		return false;
	dyld::runImageStaticTerminators(image);
	if ( (dyld::gLibSystemHelpers != NULL) && (dyld::gLibSystemHelpers->version >= 13) ) {
		__cxa_range_t ranges[image->segmentCount()];
		int rangeCount = 0;
		for (unsigned int j=0; j < image->segmentCount(); ++j) {
			if ( !image->segExecutable(j) )
				continue;
			ranges[rangeCount].addr = (const void*)image->segActualLoadAddress(j);
			ranges[rangeCount].length = image->segSize(j);
			++rangeCount;
		}
		(*dyld::gLibSystemHelpers->cxa_finalize_ranges)(ranges, rangeCount);
	}
	dyld::removeImage(image);
	
	if ( (options & NSUNLINKMODULE_OPTION_KEEP_MEMORY_MAPPED) != 0 )
		image->setLeaveMapped();
		
	// TODO: NSUNLINKMODULE_OPTION_RESET_LAZY_REFERENCES

	// Only delete image if there is no ofi referencing it
	// That means the ofi was destroyed after linking, so no one is left to delete this image	
	const size_t ofiCount = sObjectFileImages.size();
	bool found = false;
	for (size_t i=0; i < ofiCount; ++i) {
		NSObjectFileImage ofi = sObjectFileImages[i];
		if ( ofi->image == image )
			found = true;
	}
	if ( !found )
		ImageLoader::deleteImage(image);
	
	return true;
}

// internal name and parameters do not match public name and parameters...
static void _dyld_install_handlers(void* undefined, void* multiple, void* linkEdit)
{
	if ( dyld::gLogAPIs )
		dyld::log("NSLinkEditErrorHandlers()\n");

	dyld::registerUndefinedHandler((dyld::UndefinedHandler)undefined);
	// no support for multiple or linkedit handlers
}




void NSLinkEditError(NSLinkEditErrors* c, int* errorNumber, const char** fileName, const char** errorString)
{
	// FIXME FIXME
	*c = sLastErrorFileCode;
	*errorNumber = sLastErrorNo;
	*fileName = sLastErrorFilePath;
	*errorString = dyld::getErrorMessage();
}



static void _dyld_register_binding_handler(void * (*bindingHandler)(const char *, const char *, void *), ImageLoader::BindingOptions bindingOptions)
{
	if ( dyld::gLogAPIs )
		dyld::log("%s()\n", __func__);
	dyld::gLinkContext.bindingHandler = bindingHandler;
	dyld::gLinkContext.bindingOptions = bindingOptions;
}

#endif //DEPRECATED_APIS_SUPPORTED


// Call by fork() in libSystem after the kernel trap is done on the child side
void _dyld_fork_child()
{
	if ( dyld::gLogAPIs )
		dyld::log("%s()\n", __func__);
	// The implementation of fork() in libSystem knows to reset the variable mach_task_self_
	// in libSystem for the child of a fork.  But dyld is built with a static copy
	// of libc.a and has its own copy of mach_task_self_ which we reset here.
	//
	// In mach_init.h mach_task_self() is #defined to mach_task_self_ and
	// in mach_init() mach_task_self_ is initialized to task_self_trap().
	//
	extern mach_port_t	mach_task_self_;
	mach_task_self_ = task_self_trap();
 	
	// If dyld is sending load/unload notices to CoreSymbolication, the shared memory
	// page is not copied on fork. <rdar://problem/6797342>
 	// NULL the CoreSymbolication shared memory pointer to prevent a crash.
 	dyld::gProcessInfo->coreSymbolicationShmPage = NULL;
	// for safety, make sure child starts with clean systemOrderFlag
	dyld::gProcessInfo->systemOrderFlag = 0;
}


#if DEPRECATED_APIS_SUPPORTED
// returns true if prebinding was used in main executable
bool _dyld_launched_prebound()
{
	if ( dyld::gLogAPIs )
		dyld::log("%s()\n", __func__);
		
	// ¥¥¥Êif we deprecate prebinding, we may want to consider always returning true or false here
	return dyld::mainExecutablePrebound();
}


//
// _dyld_NSMakePrivateModulePublic() is the dyld side of the hack
// NSMakePrivateModulePublic() needed for the dlopen() to turn it's
// RTLD_LOCAL handles into RTLD_GLOBAL.  It just simply turns off the private
// flag on the image for this module.  If the module was found and it was
// private then everything worked and TRUE is returned else FALSE is returned.
//
static bool NSMakePrivateModulePublic(NSModule module)
{
	ImageLoader* image = NSModuleToImageLoader(module);
	if ( image != NULL ) {
		if ( image->hasHiddenExports() ) {
			image->setHideExports(false);
			return true;
		}
	}
	return false;
}

#endif // DEPRECATED_APIS_SUPPORTED

int _dyld_func_lookup(const char* name, void** address)
{
	for (const dyld_func* p = dyld_funcs; p->name != NULL; ++p) {
	    if ( strcmp(p->name, name) == 0 ) {
			if( p->implementation == unimplemented )
				dyld::log("unimplemented dyld function: %s\n", p->name);
			*address = p->implementation;
			return true;
	    }
	}
	*address = 0;
	return false;
}


static void registerThreadHelpers(const dyld::LibSystemHelpers* helpers)
{
	dyld::gLibSystemHelpers = helpers;
	
#if !SUPPORT_ZERO_COST_EXCEPTIONS
	if ( helpers->version >= 5 )  {
		// create key use by dyld exception handling
		pthread_key_t key;
		int result = helpers->pthread_key_create(&key, NULL);
		if ( result == 0 )
			__Unwind_SjLj_SetThreadKey(key);
	}
#endif
}


static void dlerrorClear()
{
	if ( dyld::gLibSystemHelpers != NULL ) {
		// <rdar://problem/10595338> dlerror buffer leak
		// dlerrorClear() should not force allocation, but zero it if already allocated
		if ( dyld::gLibSystemHelpers->version >= 10 ) {
			if ( ! (*dyld::gLibSystemHelpers->hasPerThreadBufferFor_dlerror)() )
				return;
		}

		// first char of buffer is flag whether string (starting at second char) is valid
		char* buffer = (*dyld::gLibSystemHelpers->getThreadBufferFor_dlerror)(2);
		buffer[0] = '\0';
		buffer[1] = '\0';
	}
}

static void dlerrorSet(const char* msg)
{
	if ( dyld::gLibSystemHelpers != NULL ) {
		// first char of buffer is flag whether string (starting at second char) is valid
		char* buffer = (*dyld::gLibSystemHelpers->getThreadBufferFor_dlerror)(strlen(msg)+2);
		buffer[0] = '\1';
		strcpy(&buffer[1], msg);
	}
}


bool dlopen_preflight_internal(const char* path, void* callerAddress)
{
	if ( dyld::gLogAPIs )
		dyld::log("%s(%s)\n", __func__, path);

	dlerrorClear();
	
	CRSetCrashLogMessage("dyld: in dlopen_preflight()");

	const bool leafName = (strchr(path, '/') == NULL);
	const bool absolutePath = (path[0] == '/');
#if TARGET_OS_IPHONE
	char canonicalPath[PATH_MAX]; 
	// <rdar://problem/7017050> dlopen() not opening frameworks from shared cache with // or ./ in path
	if ( !leafName ) {
		// make path canonical if it contains a // or ./
		if ( (strstr(path, "//") != NULL) || (strstr(path, "./") != NULL) ) {
			const char* lastSlash = strrchr(path, '/');
			char dirPath[PATH_MAX]; 
			if ( strlcpy(dirPath, path, sizeof(dirPath)) < sizeof(dirPath) ) {
				dirPath[lastSlash-path] = '\0';
				if ( realpath(dirPath, canonicalPath) ) {
					strlcat(canonicalPath, "/", sizeof(canonicalPath));
					if ( strlcat(canonicalPath, lastSlash+1, sizeof(canonicalPath)) < sizeof(canonicalPath) ) {
						// if all fit in buffer, use new canonical path
						path = canonicalPath;
					}
				}
			}
		}
	}
#endif
#if SUPPORT_ACCELERATE_TABLES
	if  ( dyld::isPathInCache(path) )
		return true;
#endif

	// <rdar://problem/5910137> dlopen_preflight() on image in shared cache leaves it loaded but not objc initialized
	// if requested path is to something in the dyld shared cache, always succeed
	if ( dyld::inSharedCache(path) )
		return true;

#if TARGET_OS_OSX
	// <rdar://problem/47464387> dlopen_preflight() on symlink to image in shared cache leaves it half loaded
	if ( strncmp(path, "/System/Library/", 16) == 0 ) {
		char canonicalPath[PATH_MAX];
		if ( realpath(path, canonicalPath) ) {
			if ( dyld::inSharedCache(canonicalPath) )
				return true;
		}
	}
#endif

	bool result = false;
	std::vector<const char*> rpathsFromCallerImage;
	try {
		ImageLoader* callerImage = dyld::findImageContainingAddress(callerAddress);
		// for dlopen, use rpath from caller image and from main executable
		if ( callerImage != NULL )
			callerImage->getRPaths(dyld::gLinkContext, rpathsFromCallerImage);
		ImageLoader::RPathChain callersRPaths(NULL, &rpathsFromCallerImage);
		if ( callerImage != dyld::mainExecutable() ) {
			dyld::mainExecutable()->getRPaths(dyld::gLinkContext, rpathsFromCallerImage);
		}

		ImageLoader*	image = NULL;
		dyld::LoadContext context;
		context.useSearchPaths	= true;
		context.useFallbackPaths= leafName;					// a partial path implies don't use fallback paths
		context.useLdLibraryPath= leafName;					// a leafname implies should search 
		context.implicitRPath	= !absolutePath;			// a non-absolute path implies try rpath searching 
		context.matchByInstallName = true;
		context.dontLoad		= false;
		context.mustBeBundle	= false;
		context.mustBeDylib		= false;
		context.canBePIE		= true;
		context.origin			= callerImage != NULL ? callerImage->getPath() : NULL; // caller's image's path
		context.rpath			= &callersRPaths;	// rpaths from caller and main executable

		unsigned cacheIndex;
		image = load(path, context, cacheIndex);
		if ( image != NULL ) {
			dyld::preflight(image, callersRPaths, cacheIndex);	// image object deleted by dyld::preflight()
			result = true;
		}
	}
	catch (const char* msg) {
		const char* str = dyld::mkstringf("dlopen_preflight(%s): %s", path, msg);
		dlerrorSet(str);
		free((void*)str);
		free((void*)msg); 	// our free() will do nothing if msg is a string literal
	}
	// free rpaths (getRPaths() malloc'ed each string)
	for(std::vector<const char*>::iterator it=rpathsFromCallerImage.begin(); it != rpathsFromCallerImage.end(); ++it) {
		const char* str = *it;
		free((void*)str);
	}
	CRSetCrashLogMessage(NULL);
	return result;
}

#if SUPPORT_ACCELERATE_TABLES
bool static callerIsNonOSApp(void* callerAddress, const char** shortName)
{
	*shortName = NULL;
	const mach_header* unusedMh;
	const char* unusedPath;
	unsigned unusedIndex;
	// any address in shared cache is not from app
	if ( dyld::addressInCache(callerAddress, &unusedMh, &unusedPath, &unusedIndex) )
		return false;

	ImageLoader* callerImage = dyld::findImageContainingAddress(callerAddress);
	if ( callerImage == NULL )
		return false;

	*shortName = callerImage->getShortName();
	return ( strncmp(callerImage->getPath(), "/var/containers/", 16) == 0 );
}
#endif

void* dlopen_internal(const char* path, int mode, void* callerAddress)
{
	if ( dyld::gLogAPIs )
		dyld::log("%s(%s, 0x%08X)\n", __func__, ((path==NULL) ? "NULL" : path), mode);

#if SUPPORT_ACCELERATE_TABLES
	if ( dyld::gLogAppAPIs ) {
		const char* shortName;
		if ( callerIsNonOSApp(callerAddress, &shortName) ) {
			dyld::log("%s: %s(%s, 0x%08X)\n", shortName, __func__, ((path==NULL) ? "NULL" : path), mode);
		}
	}
#endif

	dlerrorClear();

	// passing NULL for path means return magic object
	if ( path == NULL ) {
		// RTLD_FIRST means any dlsym() calls on the handle should only search that handle and not subsequent images
		if ( (mode & RTLD_FIRST) != 0 )
			return RTLD_MAIN_ONLY;
		else
			return RTLD_DEFAULT;
	}
	
	// acquire global dyld lock (dlopen is special - libSystem glue does not do locking)
	bool lockHeld = false;
	if ( (dyld::gLibSystemHelpers != NULL) && (dyld::gLibSystemHelpers->version >= 4) ) {
		dyld::gLibSystemHelpers->acquireGlobalDyldLock();
		CRSetCrashLogMessage("dyld: in dlopen()");
		lockHeld = true;
	}
		
	void* result = NULL;
	const bool leafName = (strchr(path, '/') == NULL);
	const bool absolutePath = (path[0] == '/');
#if TARGET_OS_IPHONE
	char canonicalPath[PATH_MAX]; 
	// <rdar://problem/7017050> dlopen() not opening frameworks from shared cache with // or ./ in path
	if ( !leafName ) {
		// make path canonical if it contains a // or ./
		if ( (strstr(path, "//") != NULL) || (strstr(path, "./") != NULL) ) {
			const char* lastSlash = strrchr(path, '/');
			char dirPath[PATH_MAX]; 
			if ( strlcpy(dirPath, path, sizeof(dirPath)) < sizeof(dirPath) ) {
				dirPath[lastSlash-path] = '\0';
				if ( realpath(dirPath, canonicalPath) ) {
					strlcat(canonicalPath, "/", sizeof(canonicalPath));
					if ( strlcat(canonicalPath, lastSlash+1, sizeof(canonicalPath)) < sizeof(canonicalPath) ) {
						// if all fit in buffer, use new canonical path
						path = canonicalPath;
					}
				}
			}
		}
	}
#endif
#if SUPPORT_ACCELERATE_TABLES
	if ( dyld::dlopenFromCache(path, mode, &result) ) {
		// Note: dlopenFromCache() releases the lock
		if ( dyld::gLogAPIs )
			dyld::log("  %s(%s) ==> %p\n", __func__, path, result);
		return result;
	}
#endif

	ImageLoader* image = NULL;
	std::vector<const char*> rpathsFromCallerImage;
	ImageLoader::RPathChain callersRPaths(NULL, &rpathsFromCallerImage);
	try {
		ImageLoader* callerImage = dyld::findImageContainingAddress(callerAddress);
		if ( (mode & RTLD_NOLOAD) == 0 ) {
			// for dlopen, use rpath from caller image and from main executable
			if ( callerImage != NULL )
				callerImage->getRPaths(dyld::gLinkContext, rpathsFromCallerImage);
			if ( callerImage != dyld::mainExecutable() )
				dyld::mainExecutable()->getRPaths(dyld::gLinkContext, rpathsFromCallerImage);
		}
 
		dyld::LoadContext context;
		context.useSearchPaths	= true;
		context.useFallbackPaths= leafName;				// a partial path means no fallback paths
		context.useLdLibraryPath= leafName;				// a leafname implies should search 
		context.implicitRPath   = !absolutePath;		// a non-absolute path implies try rpath searching 
		context.matchByInstallName = true;
		context.dontLoad		= ( (mode & RTLD_NOLOAD) != 0 );
		context.mustBeBundle	= false;
		context.mustBeDylib		= false;
		context.canBePIE		= true;
		context.origin			= callerImage != NULL ? callerImage->getPath() : NULL; // caller's image's path
		context.rpath			= &callersRPaths;				// rpaths from caller and main executable

		unsigned cacheIndex;
		image = load(path, context, cacheIndex);
#if SUPPORT_ACCELERATE_TABLES
		if ( (image != NULL) && (cacheIndex != UINT32_MAX) ) {
            // found in cache, but under a different path
            const char* betterPath = dyld::getPathFromIndex(cacheIndex);
            if ( (betterPath != NULL) && dyld::dlopenFromCache(betterPath, mode, &result) ) {
                // Note: dlopenFromCache() releases the lock
                if ( dyld::gLogAPIs )
                    dyld::log("  %s(%s) ==> %p\n", __func__, path, result);
                return result;
			}
		}
#endif
		if ( image != NULL ) {
			// bump reference count.  Do this before link() so that if an initializer calls dlopen and fails
			// this image is not garbage collected
			image->incrementDlopenReferenceCount();
			// link in all dependents
			if ( (mode & RTLD_NOLOAD) == 0 ) {
				bool alreadyLinked = image->isLinked();
				bool forceLazysBound = ( (mode & RTLD_NOW) != 0 );
				dyld::link(image, forceLazysBound, false, callersRPaths, cacheIndex);
				if ( alreadyLinked ) {
					// upgrade
					if ( ((mode & RTLD_LOCAL) == 0) && image->hasHiddenExports() )
						image->setHideExports(false);
				}
				else {
					// only hide exports if image is not already in use
					if ( (mode & RTLD_LOCAL) != 0 )
						image->setHideExports(true);
				}
			}
			
			// RTLD_NODELETE means don't unmap image even after dlclosed. This is what dlcompat did on Mac OS X 10.3
			// On other *nix OS's, it means dlclose() should do nothing, but the handle should be invalidated. 
			// The subtle differences are: 
			//  1) if the image has any termination routines, whether they are run during dlclose or when the process terminates
			//  2) If someone does a supsequent dlopen() on the same image, whether the same address should be used. 
			if ( (mode & RTLD_NODELETE) != 0 )
				image->setLeaveMapped();
			
			// release global dyld lock early, this enables initializers to do threaded operations
			if ( lockHeld ) {
				CRSetCrashLogMessage(NULL);
				dyld::gLibSystemHelpers->releaseGlobalDyldLock();
				lockHeld = false;
			}
			
			// RTLD_NOLOAD means dlopen should fail unless path is already loaded. 
			// don't run initializers when RTLD_NOLOAD is set.  This only matters if dlopen() is
			// called from within an initializer because it can cause initializers to run
			// out of order. Most uses of RTLD_NOLOAD are "probes".  If they want initialzers
			// to run, then don't use RTLD_NOLOAD.
			if ( (mode & RTLD_NOLOAD) == 0 ) {
				// run initializers
				dyld::runInitializers(image);
			}
			
			// RTLD_FIRST means any dlsym() calls on the handle should only search that handle and not subsequent images
			// this is tracked by setting the low bit of the handle, which is usually zero by malloc alignment
			if ( (mode & RTLD_FIRST) != 0 )
				result = (void*)(((uintptr_t)image)|1);
			else
				result = image;
		}
	}
	catch (const char* msg) {
		if ( image != NULL ) {
			// load() succeeded but, link() failed
			// back down reference count and do GC
			image->decrementDlopenReferenceCount();
			if ( image->dlopenCount() == 0 )
				dyld::garbageCollectImages();
		}
		const char* str = dyld::mkstringf("dlopen(%s, %d): %s", path, mode, msg);
		if ( dyld::gLogAPIs )
			dyld::log("  %s() failed, error: '%s'\n", __func__, str);
		dlerrorSet(str);
		free((void*)str);
		free((void*)msg); 	// our free() will do nothing if msg is a string literal
		result = NULL;
	}
	// free rpaths (getRPaths() malloc'ed each string)
	for(std::vector<const char*>::iterator it=rpathsFromCallerImage.begin(); it != rpathsFromCallerImage.end(); ++it) {
		const char* str = *it;
		free((void*)str);
	}
	
	// when context.dontLoad is set, load() returns NULL instead of throwing an exception 
	if ( (mode & RTLD_NOLOAD) && (result == NULL) ) {
		dlerrorSet("image not already loaded");
	}
	
	if ( lockHeld ) {
		CRSetCrashLogMessage(NULL);
		dyld::gLibSystemHelpers->releaseGlobalDyldLock();
	}
	if ( dyld::gLogAPIs && (result != NULL) )
		dyld::log("  %s(%s) ==> %p\n", __func__, path, result);
	return result;
}

int dlclose(void* handle)
{
	if ( dyld::gLogAPIs )
		dyld::log("%s(%p)\n", __func__, handle);

	// silently accept magic handles for main executable
	if ( handle == RTLD_MAIN_ONLY )
		return 0;
	if ( handle == RTLD_DEFAULT )
		return 0;

#if SUPPORT_ACCELERATE_TABLES
	if ( dyld::isCacheHandle(handle) ) {
		dlerrorClear();
		return 0;
	}
#endif

	ImageLoader* image = (ImageLoader*)(((uintptr_t)handle) & (-4));	// clear mode bits
	if ( dyld::validImage(image) ) {
		dlerrorClear();
		// decrement use count
		if ( image->decrementDlopenReferenceCount() ) {
			dlerrorSet("dlclose() called too many times");
			return -1;
		}
		// remove image if reference count went to zero
		if ( image->dlopenCount() == 0 )
			dyld::garbageCollectImages();
		return 0;
	}
	else {
		dlerrorSet("invalid handle passed to dlclose()");
		return -1;
	}
}



int dladdr(const void* address, Dl_info* info)
{
	if ( dyld::gLogAPIs )
		dyld::log("%s(%p, %p)\n", __func__, address, info);

	// <rdar://problem/42171466> calling dladdr(xx,NULL) crashes
	if ( info == NULL )
		return 0; // failure

	address = stripPointer(address);

	CRSetCrashLogMessage("dyld: in dladdr()");
#if SUPPORT_ACCELERATE_TABLES
	if ( dyld::dladdrFromCache(address, info) ) {
		CRSetCrashLogMessage(NULL);
		return 1; // success
	}
#endif

	ImageLoader* image = dyld::findImageContainingAddress(address);
	if ( image != NULL ) {
		info->dli_fname = image->getRealPath();
		info->dli_fbase = (void*)image->machHeader();
		if ( address == info->dli_fbase ) {
			// special case lookup of header
			info->dli_sname = "__dso_handle";
			info->dli_saddr = info->dli_fbase;
			CRSetCrashLogMessage(NULL);
			return 1; // success
		}
		// find closest symbol in the image
		info->dli_sname = image->findClosestSymbol(address, (const void**)&info->dli_saddr);
		// never return the mach_header symbol
		if ( info->dli_saddr == info->dli_fbase ) {
			info->dli_sname = NULL;
			info->dli_saddr = NULL;
			CRSetCrashLogMessage(NULL);
			return 1; // success
		}
		if ( info->dli_sname != NULL ) {
			if ( info->dli_sname[0] == '_' )
				info->dli_sname = info->dli_sname +1; // strip off leading underscore
			//dyld::log("dladdr(%p) => %p %s\n", address, info->dli_saddr, info->dli_sname);
			CRSetCrashLogMessage(NULL);
			return 1; // success
		}
		info->dli_sname = NULL;
		info->dli_saddr = NULL;
		CRSetCrashLogMessage(NULL);
		return 1; // success
	}
	CRSetCrashLogMessage(NULL);
	return 0;  // failure
}


char* dlerror()
{
	if ( dyld::gLogAPIs )
		dyld::log("%s()\n", __func__);

	if ( dyld::gLibSystemHelpers != NULL ) {
		// if using newer libdyld.dylib and buffer if buffer not yet allocated, return NULL
		if ( dyld::gLibSystemHelpers->version >= 10 ) {
			if ( ! (*dyld::gLibSystemHelpers->hasPerThreadBufferFor_dlerror)() )
				return NULL;
		}

		// first char of buffer is flag whether string (starting at second char) is valid
		char* buffer = (*dyld::gLibSystemHelpers->getThreadBufferFor_dlerror)(2);
		if ( buffer[0] != '\0' ) {	// if valid buffer
			buffer[0] = '\0';		// mark invalid, so next call to dlerror returns NULL
			return &buffer[1];		// return message
		}
	}
	return NULL;
}

void* dlsym_internal(void* handle, const char* symbolName, void* callerAddress)
{
	if ( dyld::gLogAPIs )
		dyld::log("%s(%p, %s)\n", __func__, handle, symbolName);

#if SUPPORT_ACCELERATE_TABLES
	if ( dyld::gLogAppAPIs ) {
		const char* shortName;
		if ( callerIsNonOSApp(callerAddress, &shortName) ) {
			dyld::log("%s: %s(%p, %s)\n", shortName, __func__, handle, symbolName);
		}
	}
#endif

	CRSetCrashLogMessage("dyld: in dlsym()");
	dlerrorClear();

	const ImageLoader* image;
	const ImageLoader::Symbol* sym;
	void* result;

	// dlsym() assumes symbolName passed in is same as in C source code
	// dyld assumes all symbol names have an underscore prefix
	char underscoredName[strlen(symbolName)+2];
	underscoredName[0] = '_';
	strcpy(&underscoredName[1], symbolName);
	
	// magic "search all" handle
	if ( handle == RTLD_DEFAULT ) {
		if ( dyld::flatFindExportedSymbol(underscoredName, &sym, &image) ) {
			CRSetCrashLogMessage(NULL);
			result = (void*)image->getExportedSymbolAddress(sym, dyld::gLinkContext, NULL, false, underscoredName);
#if __has_feature(ptrauth_calls)
			// Sign the pointer if it points to a function
			// Note we only do this if the main executable is arm64e as otherwise we
			// may end up calling containsAddress on the accelerator tables.
			if ( result && ((dyld::gLinkContext.mainExecutable->machHeader()->cpusubtype  & ~CPU_SUBTYPE_MASK) == CPU_SUBTYPE_ARM64E) ) {
				const ImageLoader* symbolImage = image;
				if (!symbolImage->containsAddress(result)) {
					symbolImage = dyld::findImageContainingAddress(result);
				}
				const macho_section *sect = symbolImage ? symbolImage->findSection(result) : NULL;
				if ( sect && ((sect->flags & S_ATTR_PURE_INSTRUCTIONS) || (sect->flags & S_ATTR_SOME_INSTRUCTIONS)) )
					result = __builtin_ptrauth_sign_unauthenticated(result, ptrauth_key_asia, 0);
			}
#endif
			if ( dyld::gLogAPIs )
				dyld::log("  %s(RTLD_DEFAULT, %s) ==> %p\n", __func__, symbolName, result);
			return result;
		}
		const char* str = dyld::mkstringf("dlsym(RTLD_DEFAULT, %s): symbol not found", symbolName);
		dlerrorSet(str);
		free((void*)str);
		CRSetCrashLogMessage(NULL);
		if ( dyld::gLogAPIs )
			dyld::log("  %s(RTLD_DEFAULT, %s) ==> NULL\n", __func__, symbolName);
		return NULL;
	}
	
	// magic "search only main executable" handle
	else if ( handle == RTLD_MAIN_ONLY ) {
		image = dyld::mainExecutable();
		sym = image->findExportedSymbol(underscoredName, true, &image); // search RTLD_FIRST way
		if ( sym != NULL ) {
			CRSetCrashLogMessage(NULL);
			result = (void*)image->getExportedSymbolAddress(sym, dyld::gLinkContext, NULL, false, underscoredName);
#if __has_feature(ptrauth_calls)
			// Sign the pointer if it points to a function
			// Note we only do this if the main executable is arm64e as otherwise we
			// may end up calling containsAddress on the accelerator tables.
			if ( result && ((dyld::gLinkContext.mainExecutable->machHeader()->cpusubtype  & ~CPU_SUBTYPE_MASK) == CPU_SUBTYPE_ARM64E) ) {
				const ImageLoader* symbolImage = image;
				if (!symbolImage->containsAddress(result)) {
					symbolImage = dyld::findImageContainingAddress(result);
				}
				const macho_section *sect = symbolImage ? symbolImage->findSection(result) : NULL;
				if ( sect && ((sect->flags & S_ATTR_PURE_INSTRUCTIONS) || (sect->flags & S_ATTR_SOME_INSTRUCTIONS)) )
					result = __builtin_ptrauth_sign_unauthenticated(result, ptrauth_key_asia, 0);
			}
#endif
			if ( dyld::gLogAPIs )
				dyld::log("  %s(RTLD_MAIN_ONLY, %s) ==> %p\n", __func__, symbolName, result);
			return result;
		}
		const char* str = dyld::mkstringf("dlsym(RTLD_MAIN_ONLY, %s): symbol not found", symbolName);
		dlerrorSet(str);
		free((void*)str);
		CRSetCrashLogMessage(NULL);
		if ( dyld::gLogAPIs )
			dyld::log("  %s(RTLD_MAIN_ONLY, %s) ==> NULL\n", __func__, symbolName);
		return NULL;
	}
	
	// magic "search what I would see" handle
	else if ( handle == RTLD_NEXT ) {
#if SUPPORT_ACCELERATE_TABLES
		const mach_header* mh;
		const char* path;
		unsigned index;
		if ( dyld::addressInCache(callerAddress, &mh, &path, &index) ) {
			// if dylib in cache is calling dlsym(RTLD_NEXT,xxx) handle search differently
			result = dyld::dlsymFromCache(RTLD_NEXT, underscoredName, index);
			if ( dyld::gLogAPIs )
				dyld::log("  %s(RTLD_NEXT, %s) ==> %p\n", __func__, symbolName, result);
			return result;
		}
#endif
		ImageLoader* callerImage = dyld::findImageContainingAddress(callerAddress);
		sym = callerImage->findExportedSymbolInDependentImages(underscoredName, dyld::gLinkContext, &image); // don't search image, but do search what it links against
		if ( sym != NULL ) {
			CRSetCrashLogMessage(NULL);
			result = (void*)image->getExportedSymbolAddress(sym, dyld::gLinkContext , callerImage, false, underscoredName);
#if __has_feature(ptrauth_calls)
			// Sign the pointer if it points to a function
			// Note we only do this if the main executable is arm64e as otherwise we
			// may end up calling containsAddress on the accelerator tables.
			if ( result && ((dyld::gLinkContext.mainExecutable->machHeader()->cpusubtype  & ~CPU_SUBTYPE_MASK) == CPU_SUBTYPE_ARM64E) ) {
				const ImageLoader* symbolImage = image;
				if (!symbolImage->containsAddress(result)) {
					symbolImage = dyld::findImageContainingAddress(result);
				}
				const macho_section *sect = symbolImage ? symbolImage->findSection(result) : NULL;
				if ( sect && ((sect->flags & S_ATTR_PURE_INSTRUCTIONS) || (sect->flags & S_ATTR_SOME_INSTRUCTIONS)) )
					result = __builtin_ptrauth_sign_unauthenticated(result, ptrauth_key_asia, 0);
			}
#endif
			if ( dyld::gLogAPIs )
				dyld::log("  %s(RTLD_NEXT, %s) ==> %p\n", __func__, symbolName, result);
			return result;
		}
		const char* str = dyld::mkstringf("dlsym(RTLD_NEXT, %s): symbol not found", symbolName);
		dlerrorSet(str);
		free((void*)str);
		CRSetCrashLogMessage(NULL);
		if ( dyld::gLogAPIs )
			dyld::log("  %s(RTLD_NEXT, %s) ==> NULL\n", __func__, symbolName);
		return NULL;
	}
	// magic "search me, then what I would see" handle
	else if ( handle == RTLD_SELF ) {
#if SUPPORT_ACCELERATE_TABLES
		const mach_header* mh;
		const char* path;
		unsigned index;
		if ( dyld::addressInCache(callerAddress, &mh, &path, &index) ) {
			// if dylib in cache is calling dlsym(RTLD_SELF,xxx) handle search differently
			result = dyld::dlsymFromCache(RTLD_SELF, underscoredName, index);
			if ( dyld::gLogAPIs )
				dyld::log("  %s(RTLD_SELF, %s) ==> %p\n", __func__, symbolName, result);
			return result;
		}
#endif
		ImageLoader* callerImage = dyld::findImageContainingAddress(callerAddress);
		sym = callerImage->findExportedSymbolInImageOrDependentImages(underscoredName, dyld::gLinkContext, &image); // search image and what it links against
		if ( sym != NULL ) {
			CRSetCrashLogMessage(NULL);
			result = (void*)image->getExportedSymbolAddress(sym, dyld::gLinkContext, callerImage, false, underscoredName);
#if __has_feature(ptrauth_calls)
			// Sign the pointer if it points to a function
			// Note we only do this if the main executable is arm64e as otherwise we
			// may end up calling containsAddress on the accelerator tables.
			if ( result && ((dyld::gLinkContext.mainExecutable->machHeader()->cpusubtype & ~CPU_SUBTYPE_MASK) == CPU_SUBTYPE_ARM64E) ) {
				const ImageLoader* symbolImage = image;
				if (!symbolImage->containsAddress(result)) {
					symbolImage = dyld::findImageContainingAddress(result);
				}
				const macho_section *sect = symbolImage ? symbolImage->findSection(result) : NULL;
				if ( sect && ((sect->flags & S_ATTR_PURE_INSTRUCTIONS) || (sect->flags & S_ATTR_SOME_INSTRUCTIONS)) )
					result = __builtin_ptrauth_sign_unauthenticated(result, ptrauth_key_asia, 0);
			}
#endif
			if ( dyld::gLogAPIs )
				dyld::log("  %s(RTLD_SELF, %s) ==> %p\n", __func__, symbolName, result);
			return result;
		}
		const char* str = dyld::mkstringf("dlsym(RTLD_SELF, %s): symbol not found", symbolName);
		dlerrorSet(str);
		free((void*)str);
		CRSetCrashLogMessage(NULL);
		if ( dyld::gLogAPIs )
			dyld::log("  %s(RTLD_SELF, %s) ==> NULL\n", __func__, symbolName);
		return NULL;
	}
#if SUPPORT_ACCELERATE_TABLES
	// check for mega dylib handle
	else if ( dyld::isCacheHandle(handle) ) {
		result = dyld::dlsymFromCache(handle, underscoredName, 0);
		if ( dyld::gLogAPIs )
			dyld::log("  %s(%p, %s) ==> %p\n", __func__, handle, symbolName, result);
		return result;
	}
#endif
	// real handle
	image = (ImageLoader*)(((uintptr_t)handle) & (-4));	// clear mode bits
	if ( dyld::validImage(image) ) {
		if ( (((uintptr_t)handle) & 1) != 0 )
			sym = image->findExportedSymbol(underscoredName, true, &image); // search RTLD_FIRST way
		else
			sym = image->findExportedSymbolInImageOrDependentImages(underscoredName, dyld::gLinkContext, &image); // search image and what it links against
		
		if ( sym != NULL ) {
			CRSetCrashLogMessage(NULL);
			ImageLoader* callerImage = NULL;
			if ( sDynamicInterposing ) {
				// only take time to look up caller, if dynamic interposing in use
				callerImage = dyld::findImageContainingAddress(callerAddress);
			}
			result = (void*)image->getExportedSymbolAddress(sym, dyld::gLinkContext, callerImage, false, underscoredName);
#if __has_feature(ptrauth_calls)
			// Sign the pointer if it points to a function
			// Note we only do this if the main executable is arm64e as otherwise we
			// may end up calling containsAddress on the accelerator tables.
			if ( result && ((dyld::gLinkContext.mainExecutable->machHeader()->cpusubtype & ~CPU_SUBTYPE_MASK) == CPU_SUBTYPE_ARM64E) ) {
				const ImageLoader* symbolImage = image;
				if (!symbolImage->containsAddress(result)) {
					symbolImage = dyld::findImageContainingAddress(result);
				}
				const macho_section *sect = symbolImage ? symbolImage->findSection(result) : NULL;
				if ( sect && ((sect->flags & S_ATTR_PURE_INSTRUCTIONS) || (sect->flags & S_ATTR_SOME_INSTRUCTIONS)) )
					result = __builtin_ptrauth_sign_unauthenticated(result, ptrauth_key_asia, 0);
			}
#endif
			if ( dyld::gLogAPIs )
				dyld::log("  %s(%p, %s) ==> %p\n", __func__, handle, symbolName, result);
			return result;
		}
		const char* str = dyld::mkstringf("dlsym(%p, %s): symbol not found", handle, symbolName);
		dlerrorSet(str);
		free((void*)str);
	}
	else {
		dlerrorSet("invalid handle passed to dlsym()");
	}
	CRSetCrashLogMessage(NULL);
	if ( dyld::gLogAPIs )
		dyld::log("  %s(%p, %s) ==> NULL\n", __func__, handle, symbolName);
	return NULL;
}

// Note this is only here to support ___pthread_abort in libpthread.a
void* dlsym(void* handle, const char* symbolName) {
	return dlsym_internal(handle, symbolName, __builtin_return_address(1));
}


// <rdar://problem/40352925> *_compat functions are for old binaries that have __dyld section and use it to bypass libdyld.dylib
void* dlopen_compat(const char* path, int mode)
{
	return dlopen_internal(path, mode, (void*)dyld::mainExecutable()->machHeader());
}
bool  dlopen_preflight_compat(const char* path)
{
	return dlopen_preflight_internal(path, (void*)dyld::mainExecutable()->machHeader());
}
void* dlsym_compat(void* handle, const char* symbolName)
{
	return dlsym_internal(handle, symbolName, (void*)dyld::mainExecutable()->machHeader());
}




const struct dyld_all_image_infos* _dyld_get_all_image_infos()
{
	return dyld::gProcessInfo;
}


#if SUPPORT_ZERO_COST_EXCEPTIONS
static bool client_dyld_find_unwind_sections(void* addr, dyld_unwind_sections* info)
{
	//if ( dyld::gLogAPIs )
	//	dyld::log("%s(%p, %p)\n", __func__, addr, info);

	addr = stripPointer(addr);
	
#if SUPPORT_ACCELERATE_TABLES
	if ( dyld::findUnwindSections(addr, info) )
		return true;
#endif
	ImageLoader* image = dyld::findImageContainingAddress(addr);
	if ( image != NULL ) {
		image->getUnwindInfo(info);
		return true;
	}
	return false;
}
#endif


const char* dyld_image_path_containing_address(const void* address)
{
	if ( dyld::gLogAPIs )
		dyld::log("%s(%p)\n", __func__, address);

    address = (void*)stripPointer(address);
    
#if SUPPORT_ACCELERATE_TABLES
	const mach_header* mh;
	const char* path;
	if ( dyld::addressInCache(address, &mh, &path) )
		return path;
#endif

	ImageLoader* image = dyld::findImageContainingAddress(address);
	if ( image != NULL ) {
		return image->getRealPath();
	}
	return NULL;
}



bool dyld_shared_cache_some_image_overridden()
{
	return dyld::gSharedCacheOverridden;
}


void dyld_dynamic_interpose(const struct mach_header* mh, const struct dyld_interpose_tuple array[], size_t count)
{
	if ( mh == NULL )
		return;
	if ( array == NULL )
		return;
	if ( count == 0 )
		return;
	ImageLoader* image = dyld::findImageByMachHeader(mh);
	if ( image == NULL )
		return;

	// make the cache writable for this block
	DyldSharedCache::DataConstScopedWriter patcher(dyld::gLinkContext.dyldCache, mach_task_self(), (dyld::gLinkContext.verboseMapping ? &dyld::log : nullptr));
	
	// make pass at bound references in this image and update them
	dyld::gLinkContext.dynamicInterposeArray = array;
	dyld::gLinkContext.dynamicInterposeCount = count;
		image->dynamicInterpose(dyld::gLinkContext);
	dyld::gLinkContext.dynamicInterposeArray = NULL;
	dyld::gLinkContext.dynamicInterposeCount = 0;
	
	// leave interposing info so any future (lazy) binding will get it too
	image->addDynamicInterposingTuples(array, count);
	
	sDynamicInterposing = true;
}


bool _dyld_is_memory_immutable(const void* addr, size_t length)
{
	if ( dyld::gLogAPIs )
		dyld::log("%s(%p, %ld)\n", __func__, addr, length);

	uintptr_t checkStart = (uintptr_t)addr;
	uintptr_t checkEnd   = checkStart + length;

	// quick check to see if in r/o region of shared cache.  If so return true.
    const DyldSharedCache* cache = (DyldSharedCache*)dyld::imMemorySharedCacheHeader();
    if ( cache != nullptr ) {
        const dyld_cache_mapping_info* const mappings = (dyld_cache_mapping_info*)((char*)cache + cache->header.mappingOffset);
		uintptr_t roStart    = (uintptr_t)cache;
		uintptr_t roEnd      = roStart + (uintptr_t)mappings[0].size;
		if ( (roStart < checkStart) && (checkEnd < roEnd) )
			return true;
    }

	// Otherwise find if addr is in a dyld loaded image
	ImageLoader* image = dyld::findImageContainingAddress(addr);
	if ( image != NULL ) {
		// <rdar://problem/24091154> already checked for r/o portion of cache
		if ( image->inSharedCache() )
			return false;
		if ( !image->neverUnload() )
			return false;
		for (unsigned i=0, e=image->segmentCount(); i < e; ++i) {
			if ( (image->segActualLoadAddress(i) < checkStart) && (checkEnd < image->segActualEndAddress(i)) ) {
				return !image->segWriteable(i);
			}
		}
	}
	return false;
}



void _dyld_objc_notify_register(_dyld_objc_notify_mapped    mapped,
                                _dyld_objc_notify_init      init,
                                _dyld_objc_notify_unmapped  unmapped)
{
	dyld::registerObjCNotifiers(mapped, init, unmapped);
}


bool _dyld_get_shared_cache_uuid(uuid_t uuid)
{
	return dyld::sharedCacheUUID(uuid);
}

const void* _dyld_get_shared_cache_range(size_t* length)
{
    const DyldSharedCache* cache = (DyldSharedCache*)dyld::imMemorySharedCacheHeader();
    if ( cache != nullptr ) {
        const dyld_cache_mapping_info* const mappings = (dyld_cache_mapping_info*)((char*)cache + cache->header.mappingOffset);
		const dyld_cache_mapping_info* lastMapping = &mappings[cache->header.mappingCount - 1];
        *length = (size_t)((lastMapping->address + lastMapping->size) - cache->unslidLoadAddress());
        return cache;
    }
	return nullptr;
}

void _dyld_images_for_addresses(unsigned count, const void* addresses[], struct dyld_image_uuid_offset infos[])
{
	for (unsigned i=0; i < count; ++i) {
        const void* addr = addresses[i];
		addr = stripPointer(addr);
        bzero(&infos[i], sizeof(dyld_image_uuid_offset));
#if SUPPORT_ACCELERATE_TABLES
		const mach_header* 	mh;
		const char* 		path;
		if ( dyld::addressInCache(addr, &mh, &path) ) {
			infos[i].image         = mh;
			infos[i].offsetInImage = (uintptr_t)addr - (uintptr_t)mh;
			((dyld3::MachOFile*)mh)->getUuid(infos[i].uuid);
			continue;
		}
#endif
		ImageLoader* image = dyld::findImageContainingAddress(addr);
        if ( image != nullptr ) {
            infos[i].image         = image->machHeader();
            infos[i].offsetInImage = (uintptr_t)addr - (uintptr_t)(image->machHeader());
            image->getUUID(infos[i].uuid);
        }
    }
}

void _dyld_register_for_image_loads(void (*func)(const mach_header* mh, const char* path, bool unloadable))
{
	if ( dyld::gLogAPIs )
		dyld::log("%s(%p)\n", __func__, (void *)func);
	dyld::registerLoadCallback(func);
}

void _dyld_register_for_bulk_image_loads(void (*func)(unsigned imageCount, const struct mach_header* mhs[], const char* paths[]))
{
	if ( dyld::gLogAPIs )
		dyld::log("%s(%p)\n", __func__, (void *)func);
	dyld::registerBulkLoadCallback(func);
}

void _dyld_register_driverkit_main(void (*mainFunc)())
{
	dyld::setMainEntry(mainFunc);
}