summaryrefslogtreecommitdiff
path: root/src/pal/src/loader/module.cpp
blob: b7074b4c7db73193655c29117a1ea9cec7538d43 (plain)
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
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information. 
//

/*++



Module Name:

    module.c

Abstract:

    Implementation of module related functions in the Win32 API



--*/

#include "pal/thread.hpp"
#include "pal/malloc.hpp"
#include "pal/file.hpp"
#include "pal/palinternal.h"
#include "pal/dbgmsg.h"
#include "pal/module.h"
#include "pal/cs.hpp"
#include "pal/process.h"
#include "pal/file.h"
#include "pal/utils.h"
#include "pal/init.h"
#include "pal/modulename.h"
#include "pal/misc.h"
#include "pal/virtual.h"
#include "pal/map.hpp"

#include <sys/param.h>
#include <errno.h>
#include <string.h>
#include <limits.h>
#if NEED_DLCOMPAT
#include "dlcompat.h"
#else   // NEED_DLCOMPAT
#include <dlfcn.h>
#endif  // NEED_DLCOMPAT
#if HAVE_ALLOCA_H
#include <alloca.h>
#endif  // HAVE_ALLOCA_H

#ifdef __APPLE__
#include <mach-o/dyld.h>
#include <mach-o/loader.h>
#endif // __APPLE__

#include <sys/types.h>
#include <sys/mman.h>

#include <gnu/lib-names.h>

using namespace CorUnix;

SET_DEFAULT_DEBUG_CHANNEL(LOADER);

// In safemath.h, Template SafeInt uses macro _ASSERTE, which need to use variable
// defdbgchan defined by SET_DEFAULT_DEBUG_CHANNEL. Therefore, the include statement
// should be placed after the SET_DEFAULT_DEBUG_CHANNEL(LOADER)
#include <safemath.h>

/* macro definitions **********************************************************/

/* get the full name of a module if available, and the short name otherwise*/
#define MODNAME(x) ((x)->lib_name)

/* Which path should FindLibrary search? */
#if defined(__APPLE__)
#define LIBSEARCHPATH "DYLD_LIBRARY_PATH"
#else
#define LIBSEARCHPATH "LD_LIBRARY_PATH"
#endif

#define LIBC_NAME_WITHOUT_EXTENSION "libc"

/* static variables ***********************************************************/

/* critical section that regulates access to the module list */
CRITICAL_SECTION module_critsec;

MODSTRUCT exe_module; /* always the first, in the in-load-order list */
MODSTRUCT pal_module; /* always the second, in the in-load-order list */

PDLLMAIN g_pRuntimeDllMain = NULL;
// Use the g_szCoreCLRPath global to determine whether we're really part of CoreCLR or just a standalone PAL
// linked into some utility.
extern char g_szCoreCLRPath[MAX_PATH];

#if defined(CORECLR) && defined(__APPLE__)
// Under CoreCLR/Mac the pal_module above actually represents the PAL, the PALRT and mscorwks (they're all
// linked into one binary). The PAL has no DllMain, but the other two do. Cache their DllMain entrypoints here
// so we can call them properly (e.g. thread attaches).
PDLLMAIN g_pPalRTDllMain = NULL;
#endif // CORECLR && __APPLE__

/* static function declarations ***********************************************/

static BOOL LOADValidateModule(MODSTRUCT *module);
static LPWSTR LOADGetModuleFileName(MODSTRUCT *module);
static HMODULE LOADLoadLibrary(LPCSTR ShortAsciiName, BOOL fDynamic);
static void LOAD_SEH_CallDllMain(MODSTRUCT *module, DWORD dwReason, LPVOID lpReserved);
static MODSTRUCT *LOADAllocModule(void *dl_handle, LPCSTR name);
#if !defined(CORECLR) || !defined(__APPLE__)
static INT FindLibrary(CHAR* pszRelName, CHAR** ppszFullName);
#endif // !CORECLR || !__APPLE__

/* API function definitions ***************************************************/

/*++
Function:
  LoadLibraryA

See MSDN doc.
--*/
HMODULE
PALAPI
LoadLibraryA(
         IN LPCSTR lpLibFileName)
{
    return LoadLibraryExA(lpLibFileName, NULL, 0);
}

/*++
Function:
  LoadLibraryW

See MSDN doc.
--*/
HMODULE
PALAPI
LoadLibraryW(
         IN LPCWSTR lpLibFileName)
{
    return LoadLibraryExW(lpLibFileName, NULL, 0);
}

/*++
Function:
LoadLibraryExA

See MSDN doc.
--*/
HMODULE
PALAPI
LoadLibraryExA(
        IN LPCSTR lpLibFileName,
        IN /*Reserved*/ HANDLE hFile,
        IN DWORD dwFlags)
{
    if (dwFlags != 0) 
    {
        // UNIXTODO: Implement this!
        ASSERT("Needs Implementation!!!");
        return NULL;
    }

    LPSTR lpstr = NULL;
    HMODULE hModule = NULL;
    CPalThread *pThread = NULL;

    PERF_ENTRY(LoadLibraryA);
    ENTRY("LoadLibraryExA (lpLibFileName=%p (%s)) \n",
          (lpLibFileName)?lpLibFileName:"NULL",
          (lpLibFileName)?lpLibFileName:"NULL");

    if(NULL == lpLibFileName)
    {
        ERROR("lpLibFileName is NULL;Exit.\n");
        SetLastError(ERROR_MOD_NOT_FOUND);
        goto Done;
    }

    if(lpLibFileName[0]=='\0')
    {
        ERROR("can't load library with NULL file name...\n");
        SetLastError(ERROR_INVALID_PARAMETER);
        goto Done;
    }

    pThread = InternalGetCurrentThread();
    /* do the Dos/Unix conversion on our own copy of the name */
    lpstr = InternalStrdup(pThread, lpLibFileName);
    if(!lpstr)
    {
        ERROR("InternalStrdup failure!\n");
        SetLastError(ERROR_NOT_ENOUGH_MEMORY);
        goto Done;
    }
    FILEDosToUnixPathA(lpstr);

    hModule = LOADLoadLibrary(lpstr, TRUE);

    /* let LOADLoadLibrary call SetLastError */
 Done:
    if (lpstr != NULL)
    {
        InternalFree(pThread, lpstr);
    }

    LOGEXIT("LoadLibraryExA returns HMODULE %p\n", hModule);
    PERF_EXIT(LoadLibraryExA);
    return hModule;
    
}

/*++
Function:
LoadLibraryExW

See MSDN doc.
--*/
HMODULE
PALAPI
LoadLibraryExW(
        IN LPCWSTR lpLibFileName,
        IN /*Reserved*/ HANDLE hFile,
        IN DWORD dwFlags)
{
    if (dwFlags != 0) 
    {
        // UNIXTODO: Implement this!
        ASSERT("Needs Implementation!!!");
        return NULL;
    }
    
    CHAR lpstr[MAX_PATH];
    INT name_length;
    HMODULE hModule = NULL;

    PERF_ENTRY(LoadLibraryExW);
    ENTRY("LoadLibraryExW (lpLibFileName=%p (%S)) \n",
          lpLibFileName?lpLibFileName:W16_NULLSTRING,
          lpLibFileName?lpLibFileName:W16_NULLSTRING);

    if(NULL == lpLibFileName)
    {
        ERROR("lpLibFileName is NULL;Exit.\n");
        SetLastError(ERROR_MOD_NOT_FOUND);
        goto done;
    }

    if(lpLibFileName[0]==0)
    {
        ERROR("Can't load library with NULL file name...\n");
        SetLastError(ERROR_INVALID_PARAMETER);
        goto done;
    }

    /* do the Dos/Unix conversion on our own copy of the name */

    name_length = WideCharToMultiByte(CP_ACP, 0, lpLibFileName, -1, lpstr,
                                      MAX_PATH, NULL, NULL);
    if( name_length == 0 )
    {
        DWORD dwLastError = GetLastError();
        if( dwLastError == ERROR_INSUFFICIENT_BUFFER )
        {
            ERROR("lpLibFileName is larger than MAX_PATH (%d)!\n", MAX_PATH);
        }
        else
        {
            ASSERT("WideCharToMultiByte failure! error is %d\n", dwLastError);
        }
        SetLastError(ERROR_INVALID_PARAMETER);
        goto done;
    }

    FILEDosToUnixPathA(lpstr);

    /* let LOADLoadLibrary call SetLastError in case of failure */
    hModule = LOADLoadLibrary(lpstr, TRUE);

done:
    LOGEXIT("LoadLibraryExW returns HMODULE %p\n", hModule);
    PERF_EXIT(LoadLibraryExW);
    return hModule;
}

/*++
Function:
  GetProcAddress

See MSDN doc.
--*/
FARPROC
PALAPI
GetProcAddress(
           IN HMODULE hModule,
           IN LPCSTR lpProcName)
{
    MODSTRUCT *module;
    FARPROC ProcAddress = NULL;
#if !defined(CORECLR) || !defined(__APPLE__)
    LPCSTR symbolName = lpProcName;
#endif // !defined(CORECLR) || !defined(__APPLE__)

    PERF_ENTRY(GetProcAddress);
    ENTRY("GetProcAddress (hModule=%p, lpProcName=%p (%s))\n",
          hModule, lpProcName?lpProcName:"NULL", lpProcName?lpProcName:"NULL");

    LockModuleList();

    module = (MODSTRUCT *) hModule;

    /* parameter validation */

    if( (lpProcName == NULL) || (*lpProcName == '\0') )
    {
        TRACE("No function name given\n");
        SetLastError(ERROR_INVALID_PARAMETER);
        goto done;
    }

    if( !LOADValidateModule( module ) )
    {
        TRACE("Invalid module handle %p\n", hModule);
        SetLastError(ERROR_INVALID_HANDLE);
        goto done;
    }
    
    /* try to assert on attempt to locate symbol by ordinal */
    /* this can't be an exact test for HIWORD((DWORD)lpProcName) == 0
       because of the address range reserved for ordinals contain can
       be a valid string address on non-Windows systems
    */
    if( (DWORD_PTR)lpProcName < VIRTUAL_PAGE_SIZE )
    {
        ASSERT("Attempt to locate symbol by ordinal?!\n");
    }

    // Get the symbol's address.
    
    // If we're looking for a symbol inside the PAL, we try the PAL_ variant
    // first because otherwise we run the risk of having the non-PAL_
    // variant preferred over the PAL's implementation.
#if !defined(CORECLR) || !defined(__APPLE__)
    if (module->dl_handle == pal_module.dl_handle)
    {
        int iLen = 4 + strlen(lpProcName) + 1;
        LPSTR lpPALProcName = (LPSTR) alloca(iLen);
        
        if (strcpy_s(lpPALProcName, iLen, "PAL_") != SAFECRT_SUCCESS)
        {
            ERROR("strcpy_s failed!\n");
            SetLastError(ERROR_INSUFFICIENT_BUFFER);
            goto done;
        }

        if (strcat_s(lpPALProcName, iLen, lpProcName) != SAFECRT_SUCCESS)
        {
            ERROR("strcat_s failed!\n");
            SetLastError(ERROR_INSUFFICIENT_BUFFER);
            goto done;
        }

        ProcAddress = (FARPROC) dlsym(module->dl_handle, lpPALProcName);
        symbolName = lpPALProcName;
    }
#else // !CORECLR || !__APPLE__
    if (module == &pal_module)
    {
        // Attempting to lookup a symbol exported by the PAL/runtime itself.

        // Under CoreCLR/Mac the PAL "module" represents either the entire CoreCLR binary (including PAL,
        // PALRT and mscorwks) or just the PAL in the (uncommon) case of a standalone PAL. We can tell the
        // difference in these cases by whether the sys_module field of pal_module was initialized to contain
        // a non-NULL value: this is only done in the CoreCLR case.
        if (pal_module.sys_module)
        {
            // Trying to locate a symbol in the PAL, PALRT or mscorwks.
            int iLen = 4 + strlen(lpProcName) + 1;
            LPSTR lpPALProcName = (LPSTR) alloca(iLen);
            
            if (strcpy_s(lpPALProcName, iLen, "PAL_") != SAFECRT_SUCCESS)
            {
                ERROR("strcpy_s failed!\n");
                SetLastError(ERROR_INSUFFICIENT_BUFFER);
                goto done;
            }

            if (strcat_s(lpPALProcName, iLen, lpProcName) != SAFECRT_SUCCESS)
            {
                ERROR("strcat_s failed!\n");
                SetLastError(ERROR_INSUFFICIENT_BUFFER);
                goto done;
            }

            ProcAddress = (FARPROC)LookupFunctionInCoreCLR(pal_module.sys_module, lpPALProcName);
        }
        else
        {
            // Trying to locate a symbol in the standalone PAL. We don't support this (it's brittle to lump
            // the PAL namespace in with some random host code). Just fall through to the failure case.
            ASSERT("Attempted to lookup proc address in a standalone PAL");
        }
    }
#endif // !CORECLR || !__APPLE__

    // If we aren't looking inside the PAL or we didn't find a PAL_ variant
    // inside the PAL, fall back to a normal search.
    if (ProcAddress == NULL)
    {
#if defined(CORECLR) && defined(__APPLE__)
        if (module->dl_handle)
        {
#endif // CORECLR && __APPLE__
            ProcAddress = (FARPROC) dlsym(module->dl_handle, lpProcName);
#if defined(CORECLR) && defined(__APPLE__)
        }
        else if (module->sys_module)
        {
            ProcAddress = (FARPROC)LookupFunctionInCoreCLR(module->sys_module, lpProcName);
        }
#endif // CORECLR && __APPLE__
    }

    if (ProcAddress)
    {
        TRACE("Symbol %s found at address %p in module %p (named %S)\n",
              lpProcName, ProcAddress, module, MODNAME(module));

        /* if we don't know the module's full name yet, this is our chance to
           obtain it */
        if(!module->lib_name && module->dl_handle)
        {
            const char* libName = PAL_dladdr((LPVOID)ProcAddress);
            if (libName)
            {
                module->lib_name = UTIL_MBToWC_Alloc(libName, -1);
                if(NULL == module->lib_name)
                {
                    ERROR("MBToWC failure; can't save module's full name\n");
                }
                else
                {
                    TRACE("Saving full path of module %p as %s\n",
                          module, libName);
                }
            }
        }
    }
    else
    {
        TRACE("Symbol %s not found in module %p (named %S), dlerror message is \"%s\"\n",
              lpProcName, module, MODNAME(module), dlerror());
        SetLastError(ERROR_PROC_NOT_FOUND);
    }
done:
    UnlockModuleList();
    LOGEXIT("GetProcAddress returns FARPROC %p\n", ProcAddress);
    PERF_EXIT(GetProcAddress);
    return ProcAddress;
}


/*++
Function:
  FreeLibrary

See MSDN doc.
--*/
BOOL
PALAPI
FreeLibrary(
        IN OUT HMODULE hLibModule)
{
    MODSTRUCT *module;
    BOOL retval = FALSE;
    CPalThread *pThread;

    PERF_ENTRY(FreeLibrary);
    ENTRY("FreeLibrary (hLibModule=%p)\n", hLibModule);

    LockModuleList();

    module = (MODSTRUCT *) hLibModule;

    if (terminator)
    {
        /* PAL shutdown is in progress - ignore FreeLibrary calls */
        retval = TRUE;
        goto done;
    }

    if( !LOADValidateModule( module ) )
    {
        TRACE("Can't free invalid module handle %p\n", hLibModule);
        SetLastError(ERROR_INVALID_HANDLE);
        goto done;
    }

    if( module->refcount == -1 )
    {
        /* special module - never released */
        retval=TRUE;
        goto done;
    }

    module->refcount--;
    TRACE("Reference count for module %p (named %S) decreases to %d\n",
            module, MODNAME(module), module->refcount);

    if( module->refcount != 0 )
    {
        retval=TRUE;
        goto done;
    }

    /* Releasing the last reference : call dlclose(), remove module from the
       process-wide module list */

    TRACE("Reference count for module %p (named %S) now 0; destroying "
            "module structure.\n", module, MODNAME(module));

    /* unlink the module structure from the list */
    module->prev->next = module->next;
    module->next->prev = module->prev;

    /* remove the circular reference so that LOADValidateModule will fail */
    module->self=NULL;

    /* Call DllMain if the module contains one */
    if(module->pDllMain)
    {
        TRACE("Calling DllMain (%p) for module %S\n",
                module->pDllMain, 
                module->lib_name ? module->lib_name : W16_NULLSTRING);

/* reset ENTRY nesting level back to zero while inside the callback... */
#if !_NO_DEBUG_MESSAGES_
    {
        int old_level;
        old_level = DBG_change_entrylevel(0);
#endif /* !_NO_DEBUG_MESSAGES_ */
    
        {
            // This module may be foreign to our PAL, so leave our PAL.
            // If it depends on us, it will re-enter.
            PAL_LeaveHolder holder;
            module->pDllMain((HMODULE)module, DLL_PROCESS_DETACH, NULL);
        }

/* ...and set nesting level back to what it was */
#if !_NO_DEBUG_MESSAGES_
        DBG_change_entrylevel(old_level);
    }
#endif /* !_NO_DEBUG_MESSAGES_ */
    }

    if(module->dl_handle && 0!=dlclose(module->dl_handle))
    {
        /* report dlclose() failure, but proceed anyway. */
        WARN("dlclose() call failed! error message is \"%s\"\n", dlerror());
    }

    pThread = InternalGetCurrentThread();
    /* release all memory */
    InternalFree(pThread, module->lib_name);
    InternalFree(pThread, module);

    retval=TRUE;

done:
    UnlockModuleList();
    LOGEXIT("FreeLibrary returns BOOL %d\n", retval);
    PERF_EXIT(FreeLibrary);
    return retval;
}


/*++
Function:
  FreeLibraryAndExitThread

See MSDN doc.

--*/
PALIMPORT
VOID
PALAPI
FreeLibraryAndExitThread(
             IN HMODULE hLibModule,
             IN DWORD dwExitCode)
{
    PERF_ENTRY(FreeLibraryAndExitThread);
    ENTRY("FreeLibraryAndExitThread()\n"); 
    FreeLibrary(hLibModule);
    ExitThread(dwExitCode);
    LOGEXIT("FreeLibraryAndExitThread\n");
    PERF_EXIT(FreeLibraryAndExitThread);
}


/*++
Function:
  GetModuleFileNameA

See MSDN doc.

Notes :
    because of limitations in the dlopen() mechanism, this will only return the
    full path name if a relative or absolute path was given to LoadLibrary, or
    if the module was used in a GetProcAddress call. otherwise, this will return
    the short name as given to LoadLibrary. The exception is if hModule is
    NULL : in this case, the full path of the executable is always returned.
--*/
DWORD
PALAPI
GetModuleFileNameA(
           IN HMODULE hModule,
           OUT LPSTR lpFileName,
           IN DWORD nSize)
{
    INT name_length;
    DWORD retval=0;
    LPWSTR wide_name = NULL;

    PERF_ENTRY(GetModuleFileNameA);
    ENTRY("GetModuleFileNameA (hModule=%p, lpFileName=%p, nSize=%u)\n",
          hModule, lpFileName, nSize);

    LockModuleList();
    if(hModule && !LOADValidateModule((MODSTRUCT *)hModule))
    {
        TRACE("Can't find name for invalid module handle %p\n", hModule);
        SetLastError(ERROR_INVALID_HANDLE);
        goto done;
    }
    wide_name=LOADGetModuleFileName((MODSTRUCT *)hModule);

    if(!wide_name)
    {
        ASSERT("Can't find name for valid module handle %p\n", hModule);
        SetLastError(ERROR_INTERNAL_ERROR);
        goto done;
    }

    /* Convert module name to Ascii, place it in the supplied buffer */

    name_length = WideCharToMultiByte(CP_ACP, 0, wide_name, -1, lpFileName,
                                      nSize, NULL, NULL);
    if( name_length==0 )
    {
        TRACE("Buffer too small to copy module's file name.\n");
        SetLastError(ERROR_INSUFFICIENT_BUFFER);
        goto done;
    }

    TRACE("File name of module %p is %s\n", hModule, lpFileName);
    retval=name_length;
done:
    UnlockModuleList();
    LOGEXIT("GetModuleFileNameA returns DWORD %d\n", retval);
    PERF_EXIT(GetModuleFileNameA);
    return retval;
}


/*++
Function:
  GetModuleFileNameW

See MSDN doc.

Notes :
    because of limitations in the dlopen() mechanism, this will only return the
    full path name if a relative or absolute path was given to LoadLibrary, or
    if the module was used in a GetProcAddress call. otherwise, this will return
    the short name as given to LoadLibrary. The exception is if hModule is
    NULL : in this case, the full path of the executable is always returned.
--*/
DWORD
PALAPI
GetModuleFileNameW(
           IN HMODULE hModule,
           OUT LPWSTR lpFileName,
           IN DWORD nSize)
{
    INT name_length;
    DWORD retval=0;
    LPWSTR wide_name = NULL;

    PERF_ENTRY(GetModuleFileNameW);
    ENTRY("GetModuleFileNameW (hModule=%p, lpFileName=%p, nSize=%u)\n",
          hModule, lpFileName, nSize);

    LockModuleList();

    if(hModule && !LOADValidateModule((MODSTRUCT *)hModule))
    {
        TRACE("Can't find name for invalid module handle %p\n", hModule);
        SetLastError(ERROR_INVALID_HANDLE);
        goto done;
    }
    wide_name=LOADGetModuleFileName((MODSTRUCT *)hModule);

    if(!wide_name)
    {
        ASSERT("Can't find name for valid module handle %p\n", hModule);
        SetLastError(ERROR_INTERNAL_ERROR);
        goto done;
    }

    /* Copy module name into supplied buffer */

    name_length = lstrlenW(wide_name);
    if(name_length>=(INT)nSize)
    {
        TRACE("Buffer too small to copy module's file name.\n");
        SetLastError(ERROR_INSUFFICIENT_BUFFER);
        goto done;
    }
    
    wcscpy_s(lpFileName, nSize, wide_name);

    TRACE("file name of module %p is %S\n", hModule, lpFileName);
    retval=name_length;
done:
    UnlockModuleList();
    LOGEXIT("GetModuleFileNameW returns DWORD %u\n", retval);
    PERF_EXIT(GetModuleFileNameW);
    return retval;
}

/*++
Function:
  PAL_RegisterLibraryW

  Same as LoadLibraryW, but with only the base name of
  the library instead of a full filename.
--*/

HMODULE
PALAPI
PAL_RegisterLibraryW(
         IN LPCWSTR lpLibFileName)
{
    HMODULE hModule = NULL;
    CHAR    lpstr[MAX_PATH];
    INT     cbMultiByteShortName = 0;

    static const char LIB_PREFIX[] = PAL_SHLIB_PREFIX;
    static const char LIB_SUFFIX[] = PAL_SHLIB_SUFFIX;
    static const int LIB_PREFIX_LENGTH = sizeof(LIB_PREFIX) - 1;
    static const int LIB_SUFFIX_LENGTH = sizeof(LIB_SUFFIX) - 1;

    PERF_ENTRY(PAL_RegisterLibraryW);
    ENTRY("PAL_RegisterLibraryW (lpLibFileName=%p (%S)) \n",
          lpLibFileName?lpLibFileName:W16_NULLSTRING,
          lpLibFileName?lpLibFileName:W16_NULLSTRING);

    // First, copy the prefix into the buffer
    if (strcpy_s(lpstr, sizeof(lpstr), LIB_PREFIX) != SAFECRT_SUCCESS)
    {
        ERROR("strcpy_s failed!\n");
        SetLastError(ERROR_INSUFFICIENT_BUFFER);
        goto Done;
    }

    // Second, copy the file name, converting to multibyte along the way
    cbMultiByteShortName = WideCharToMultiByte(CP_ACP, 0, lpLibFileName, -1, 
                                               lpstr + LIB_PREFIX_LENGTH, 
                                               MAX_PATH - (LIB_PREFIX_LENGTH + LIB_SUFFIX_LENGTH),
                                               NULL, NULL);

    if (cbMultiByteShortName == 0)
    {
        DWORD dwLastError = GetLastError();
        if (dwLastError == ERROR_INSUFFICIENT_BUFFER)
        {
            if (lstrlenW(lpLibFileName) + LIB_PREFIX_LENGTH + LIB_SUFFIX_LENGTH < MAX_PATH)
            {
                ASSERT("Insufficient buffer error returned incorrectly from WideCharToMultiByte!\n");
            }
            ERROR("lpLibFileName is larger than MAX_PATH (%d)!\n", MAX_PATH);
        }
        else
        {
            ASSERT("WideCharToMultiByte failure! error is %d\n", dwLastError);
        }
        SetLastError(ERROR_INVALID_PARAMETER);
        goto Done;
    }

    // Last, add the suffix
    if (strcat_s(lpstr, sizeof(lpstr), LIB_SUFFIX) != SAFECRT_SUCCESS)
    {
        ERROR("strcat_s failed!\n");
        SetLastError(ERROR_INSUFFICIENT_BUFFER);
        goto Done;
    }

    FILEDosToUnixPathA(lpstr);

    hModule = LOADLoadLibrary(lpstr, FALSE);

Done:
    LOGEXIT("PAL_RegisterLibraryW returns HMODULE %p\n", hModule);
    PERF_EXIT(PAL_RegisterLibraryW);
    return hModule;
}


/*++
Function:
  PAL_UnregisterLibraryW

  Same as FreeLibrary.
--*/
BOOL
PALAPI
PAL_UnregisterLibraryW(
        IN OUT HMODULE hLibModule)
{
    BOOL retval;

    PERF_ENTRY(PAL_UnregisterLibraryW);
    ENTRY("PAL_UnregisterLibraryW (hLibModule=%p)\n", hLibModule);

    retval = FreeLibrary(hLibModule);

    LOGEXIT("PAL_UnregisterLibraryW returns BOOL %d\n", retval);
    PERF_EXIT(PAL_UnregisterLibraryW);
    return retval;
}

/* Internal PAL functions *****************************************************/

#if !defined(CORECLR) || !defined(__APPLE__)
/*++
    LOADGetLibRotorPalSoFileName

    Search LD_LIBRARY_PATH (or DYLD_LIBRARY_PATH) for LibRotorPal.  This 
    defines the working directory for PAL.

Parameters:
    OUT LPSTR pszBuf - WCHAR buffer of MAX_PATH length to receive file name

Return value:
    0 if successful
    -1 if failure, with last error set.
--*/
extern "C"
int LOADGetLibRotorPalSoFileName(LPSTR pszBuf)
{
    INT     iRetVal = -1;
    CHAR*   pszFileName = NULL;
    CPalThread *pthrThread = InternalGetCurrentThread();

    if (!pszBuf)
    {
        ASSERT("LOADGetLibRotorPalSoFileName requires non-NULL pszBuf\n");
        SetLastError(ERROR_INTERNAL_ERROR);
        goto Done;
    }
    iRetVal = FindLibrary((CHAR*)MAKEDLLNAME_A("CoreClrPal"), &pszFileName);
    if (pszFileName)
    {
        UINT cchFileName = strlen(pszFileName);
        if (cchFileName + 1  > MAX_PATH)
        {
            ASSERT("Filename returned by FindLibrary was longer than"
                "MAX_PATH!\n");
            SetLastError(ERROR_FILENAME_EXCED_RANGE);
            goto Done;
        }
        // If the path is relative, get current working directory and prepend 
        // it (Note that this function is called only on PAL startup, so 
        // current working directory should still be correct)
        if (pszFileName[0] != '/')
        {
            CHAR    szCurDir[MAX_PATH];
            CHAR*   pszRetVal = NULL;
            if ((pszRetVal = InternalGetcwd(pthrThread, szCurDir, MAX_PATH)) == NULL)
            {
                SetLastError(DIRGetLastErrorFromErrno());
                goto Done;
            }
            // If the strings would overflow (note that if the sum of the 
            // lengths == MAX_PATH, the string would overflow b/c of the null
            // terminator -- the 1 is added to account for the /)
            if ((strlen(szCurDir) + strlen(pszFileName) + 1) >= MAX_PATH)
            {
                SetLastError(ERROR_FILENAME_EXCED_RANGE);
                goto Done;
            }
            strcat_s(pszBuf, MAX_PATH, szCurDir);
            strcat_s(pszBuf, MAX_PATH,  "/");
            strcat_s(pszBuf, MAX_PATH,  pszFileName);
        }
        else
        {
            strcpy_s(pszBuf, MAX_PATH, pszFileName);
        }
        iRetVal = 0;        
    }
Done:
    if (pszFileName)
    {
        InternalFree(pthrThread, pszFileName);
    }
    return iRetVal;
}
#endif // !CORECLR || !__APPLE__

/*++
Function :
    LOADInitializeModules

    Initialize the process-wide list of modules (2 initial modules : 1 for
    the executable and 1 for the PAL)

Parameters :
    LPWSTR exe_name : full path to executable

Return value:
    TRUE  if initialization succeedded
    FALSE otherwise

Notes :
    the module manager takes ownership of the exe_name string
--*/
extern "C"
BOOL LOADInitializeModules(LPWSTR exe_name)
{
#if !defined(CORECLR) || !defined(__APPLE__)
    LPWSTR  lpwstr = NULL;
#endif // !defined(CORECLR) || !defined(__APPLE__)

#if RETURNS_NEW_HANDLES_ON_REPEAT_DLOPEN
    LPSTR   pszExeName = NULL;
    CPalThread *pThread = NULL;
#endif

    BOOL    fRetCode = FALSE;

    if(exe_module.prev)
    {
        ERROR("Module manager already initialized!\n");
        SetLastError(ERROR_INTERNAL_ERROR);
        goto Done;
    }

    InternalInitializeCriticalSection(&module_critsec);

    /* initialize module for main executable */
    TRACE("Initializing module for main executable\n");
    exe_module.self=(HMODULE)&exe_module;
#if defined(CORECLR) && defined(__APPLE__)
    exe_module.sys_module = NULL;
#endif // CORECLR && __APPLE__
    exe_module.dl_handle=dlopen(NULL, RTLD_LAZY);
    if(!exe_module.dl_handle)
    {
        ASSERT("Main executable module will be broken : dlopen(NULL) failed. "
             "dlerror message is \"%s\" \n", dlerror());
    }
    exe_module.lib_name = exe_name;
    exe_module.refcount=-1;
    exe_module.next=&pal_module;
    exe_module.prev=&pal_module;
    exe_module.pDllMain = NULL;
    exe_module.ThreadLibCalls = TRUE;
    
    TRACE("Initializing module for PAL library\n");
    pal_module.self=(HANDLE)&pal_module;

#if !defined(CORECLR) || !defined(__APPLE__)
    if (g_szCoreCLRPath[0] == '\0')
    {
        pal_module.lib_name=NULL;
        pal_module.dl_handle=NULL;
    } else
    {
        TRACE("PAL library is %s\n", g_szCoreCLRPath);
        lpwstr = UTIL_MBToWC_Alloc(g_szCoreCLRPath, -1);
        if(NULL == lpwstr)
        {
            ERROR("MBToWC failure, unable to save full name of PAL module\n");
            goto Done;
        }
        pal_module.lib_name=lpwstr;
        pal_module.dl_handle=dlopen(g_szCoreCLRPath, RTLD_LAZY);

        if(pal_module.dl_handle)
        {
            g_pRuntimeDllMain = (PDLLMAIN)dlsym(pal_module.dl_handle, "CoreDllMain");
        }
        else
        {
#if !defined(__hppa__)
            ASSERT("PAL module will be broken : dlopen(%s) failed. dlerror "
                 "message is \"%s\"\n ", g_szCoreCLRPath, dlerror());
#endif
        }
    }
#else // !CORECLR || !__APPLE__
    // Under CoreCLR/Mac we have a single binary instead of separate dynamic libraries. Here pal_module
    // represents all of that dylib (with dl_handle == NULL and sys_module != NULL). We still support some
    // scenarios with a standalone PAL statically linked into host code. These cases are differented by
    // sys_module being NULL (and GetProcAddress() will not work on such a module).
    pal_module.lib_name = UTIL_MBToWC_Alloc("CoreCLR", -1);
    if(NULL == pal_module.lib_name)
    {
        ERROR("MBToWC failure, unable to save full name of PAL module\n");
        goto Done;
    }
    pal_module.dl_handle = NULL;

    // Determine whether we're part of CoreCLR or a standalone PAL. Do this by looking at the g_szCoreCLRPath
    // global: this is set to a non-zero length string by PAL initialization in the CoreCLR case.
    if (g_szCoreCLRPath[0] != '\0')
    {
        // We're part of a full CoreCLR. Determine our module's handle and cache it for future
        // GetProcAddress() operations).
        pal_module.sys_module = FindCoreCLRHandle();
        if (pal_module.sys_module == NULL)
        {
            ASSERT("FindCoreCLRHandle() failure");
            goto Done;
        }
    }
    else
    {
        // We're just a standalone PAL. Disable any functionality that needs to peek into the containing
        // module (since we know nothing about that module).
        pal_module.sys_module = NULL;
    }

    // If we really are running in CoreCLR then we need to locate and remember the DllMain routines for the
    // PalRT and mscorwks (the PAL itself doesn't have one). We use these to keep the components up to date
    // with thread attaches and detaches. We can't call them here for the process attach, however, since we
    // are still partway through PAL initialization. We rely on PAL_InitializeCoreCLR to call us back on
    // LOADInitCoreCLRModules once PAL initialization is complete.
    if (pal_module.sys_module)
    {
        g_pPalRTDllMain = (PDLLMAIN)LookupFunctionInCoreCLR(pal_module.sys_module, "PalRtDllMain");
        if (g_pPalRTDllMain == NULL)
        {
            ERROR("Failed to locate PalRT DllMain\n");
            SetLastError(ERROR_INVALID_DLL);
            goto Done;
        }

        g_pRuntimeDllMain = (PDLLMAIN)LookupFunctionInCoreCLR(pal_module.sys_module, "CoreDllMain");
        if (g_pRuntimeDllMain == NULL)
        {
            ERROR("Failed to locate Mscorwks DllMain\n");
            SetLastError(ERROR_INVALID_DLL);
            goto Done;
        }
    }
#endif // !CORECLR || !__APPLE__

    pal_module.refcount=-1;
    pal_module.next=&exe_module;
    pal_module.prev=&exe_module;
    pal_module.pDllMain = NULL;
    pal_module.ThreadLibCalls = TRUE;

    // For platforms where we can't trust the handle to be constant, we need to 
    // store the inode/device pairs for the modules we just initialized.
#if RETURNS_NEW_HANDLES_ON_REPEAT_DLOPEN
    {
        struct stat stat_buf;
        pszExeName = UTIL_WCToMB_Alloc(exe_name, -1);
        if (NULL == pszExeName)
        {
            ERROR("WCToMB failure, unable to get full name of exe\n");
            goto Done;
        }
        if ( -1 == stat(pszExeName, &stat_buf))
        {
            SetLastError(ERROR_MOD_NOT_FOUND);
            goto Done;
        }

        TRACE("Executable has inode %d and device %d\n", 
            stat_buf.st_ino, stat_buf.st_dev);

        exe_module.inode = stat_buf.st_ino; 
        exe_module.device = stat_buf.st_dev;
        if ( -1 == stat(librotor_fname, &stat_buf))
        {
            SetLastError(ERROR_MOD_NOT_FOUND);
            goto Done;
        }

        TRACE("PAL Library has inode %d and device %d\n", 
            stat_buf.st_ino, stat_buf.st_dev);

        pal_module.inode = stat_buf.st_ino; 
        pal_module.device = stat_buf.st_dev;
    }
#endif

    // If we got here, init succeeded.
    fRetCode = TRUE;
 Done:
    if (!fRetCode && GetLastError() == ERROR_SUCCESS)
    {
        ASSERT("returning failure, but last error not set\n");
    }

#if RETURNS_NEW_HANDLES_ON_REPEAT_DLOPEN
    pThread = InternalGetCurrentThread();
    if (pszExeName)
        InternalFree(pThread, pszExeName);
#endif
    TRACE("Module manager initialization returning %d.\n", fRetCode);
    return fRetCode;
}

/*++
Function :
    LOADFreeModules

    Release all resources held by the module manager (including dlopen handles)

Parameters:
    BOOL bTerminateUnconditionally: If TRUE, this will avoid calling any DllMains

    (no return value)
--*/
extern "C"
void LOADFreeModules(BOOL bTerminateUnconditionally)
{
    MODSTRUCT *module;
    CPalThread *pThread = InternalGetCurrentThread();

    if(!exe_module.prev)
    {
        ERROR("Module manager not initialized!\n");
        return;
    }

    LockModuleList();

    /* Go through the list of modules, release any references we still hold.
       The list is traversed from newest module to oldest */
    do
    {
        module = exe_module.prev;

        // Call DllMain if the module contains one and if we're supposed
        // to call DllMains.
        if( !bTerminateUnconditionally && module->pDllMain )
        {
           /* Exception-safe call to DllMain */
           LOAD_SEH_CallDllMain( module, DLL_PROCESS_DETACH, (LPVOID)-1 );
        }

        /* Remove the current MODSTRUCT from the list, then free its memory */
        module->prev->next = module->next;
        module->next->prev = module->prev;
        module->self = NULL;

        if (module->dl_handle)
            dlclose( module->dl_handle );

        InternalFree( pThread, module->lib_name );
        module->lib_name = NULL;
        if (module != &exe_module && module != &pal_module)
        {
            InternalFree( pThread, module );
        }
    }
    while( module != &exe_module );

    /* Flag the module manager as uninitialized */
    exe_module.prev = NULL;

    TRACE("Module manager stopped.\n");

    UnlockModuleList();
    DeleteCriticalSection(&module_critsec);
}

/*++
Function :
    LOADCallDllMain

    Call DllMain for all modules (that have one) with the given "fwReason"

Parameters :
    DWORD dwReason : parameter to pass down to DllMain, one of DLL_PROCESS_ATTACH, DLL_PROCESS_DETACH, 
        DLL_THREAD_ATTACH, DLL_THREAD_DETACH

    LPVOID lpReserved : parameter to pass down to DllMain
        If dwReason is DLL_PROCESS_ATTACH, lpvReserved is NULL for dynamic loads and non-NULL for static loads.
        If dwReason is DLL_PROCESS_DETACH, lpvReserved is NULL if DllMain has been called by using FreeLibrary 
            and non-NULL if DllMain has been called during process termination. 

(no return value)

Notes :
    This is used to send DLL_THREAD_*TACH messages to modules
--*/
extern "C"
void LOADCallDllMain(DWORD dwReason, LPVOID lpReserved)
{
    MODSTRUCT *module = NULL;
    BOOL InLoadOrder = TRUE; /* true if in load order, false for reverse */
    CPalThread *pThread;
    
    pThread = InternalGetCurrentThread();
    if (UserCreatedThread != pThread->GetThreadType())
    {
        return;
    }

    /* Validate dwReason */
    switch(dwReason)
    {
    case DLL_PROCESS_ATTACH: 
        ASSERT("got called with DLL_PROCESS_ATTACH parameter! Why?\n");
        break;
    case DLL_PROCESS_DETACH:
        ASSERT("got called with DLL_PROCESS_DETACH parameter! Why?\n");
        InLoadOrder = FALSE;
        break;
    case DLL_THREAD_ATTACH:
        TRACE("Calling DllMain(DLL_THREAD_ATTACH) on all known modules.\n");
        break;
    case DLL_THREAD_DETACH:
        TRACE("Calling DllMain(DLL_THREAD_DETACH) on all known modules.\n");
        InLoadOrder = FALSE;
        break;
    default:
        ASSERT("LOADCallDllMain called with unknown parameter %d!\n", dwReason);
        return;
    }

    LockModuleList();

#if defined(CORECLR) && defined(__APPLE__)
    // The CoreCLR needs to simulate PalRT and mscorwks being separate libraries rather
    // than a single binary.
    if (InLoadOrder && g_pPalRTDllMain)
    {
#if !_NO_DEBUG_MESSAGES_
        /* reset ENTRY nesting level back to zero while inside the callback... */
        int old_level;
        old_level = DBG_change_entrylevel(0);
#endif /* !_NO_DEBUG_MESSAGES_ */

        {
            PAL_LeaveHolder holder;
            g_pPalRTDllMain((HMODULE) module, dwReason, lpReserved);
        }
        g_pRuntimeDllMain((HMODULE) module, dwReason, lpReserved);

#if !_NO_DEBUG_MESSAGES_
        /* ...and set nesting level back to what it was */
        DBG_change_entrylevel(old_level);
#endif /* !_NO_DEBUG_MESSAGES_ */
    }
#endif // CORECLR && __APPLE__

    module = &exe_module;
    do {
        if (!InLoadOrder)
            module = module->prev;

        if (module->ThreadLibCalls)
        {
            if(module->pDllMain)
            {
#if !_NO_DEBUG_MESSAGES_
                /* reset ENTRY nesting level back to zero while inside the callback... */
                int old_level;
                old_level = DBG_change_entrylevel(0);
#endif /* !_NO_DEBUG_MESSAGES_ */

                {
                    // This module may be foreign to our PAL, so leave our PAL.
                    // If it depends on us, it will re-enter.
                    PAL_LeaveHolder holder;
                    module->pDllMain((HMODULE) module, dwReason, lpReserved);
                }

#if !_NO_DEBUG_MESSAGES_
                /* ...and set nesting level back to what it was */
                DBG_change_entrylevel(old_level);
#endif /* !_NO_DEBUG_MESSAGES_ */
            }
        }

        if (InLoadOrder)
            module = module->next;
    } while (module != &exe_module);

#if defined(CORECLR) && defined(__APPLE__)
    // The CoreCLR needs to simulate PalRT and CoreCLR being separate libraries rather
    // than a single binary.
    if (!InLoadOrder && g_pPalRTDllMain)
    {
#if !_NO_DEBUG_MESSAGES_
        /* reset ENTRY nesting level back to zero while inside the callback... */
        int old_level;
        old_level = DBG_change_entrylevel(0);
#endif /* !_NO_DEBUG_MESSAGES_ */

        g_pRuntimeDllMain((HMODULE) module, dwReason, lpReserved);
        {
            PAL_LeaveHolder holder;
            g_pPalRTDllMain((HMODULE) module, dwReason, lpReserved);
        }

#if !_NO_DEBUG_MESSAGES_
        /* ...and set nesting level back to what it was */
        DBG_change_entrylevel(old_level);
#endif /* !_NO_DEBUG_MESSAGES_ */
    }
#endif // CORECLR && __APPLE__

    UnlockModuleList();
}


/*++
Function:
    DisableThreadLibraryCalls

See MSDN doc.
--*/
BOOL
PALAPI
DisableThreadLibraryCalls(
    IN HMODULE hLibModule)
{
    BOOL ret = FALSE;
    MODSTRUCT *module;
    PERF_ENTRY(DisableThreadLibraryCalls);
    ENTRY("DisableThreadLibraryCalls(hLibModule=%p)\n", hLibModule);

    if (terminator)
    {
        /* PAL shutdown in progress - ignore DisableThreadLibraryCalls */
        ret = TRUE;
        goto done_nolock;
    }

    LockModuleList();
    module = (MODSTRUCT *) hLibModule;

    if(!module || !LOADValidateModule(module))
    {
        // DisableThreadLibraryCalls() does nothing when given
        // an invalid module handle. This matches the Windows
        // behavior, though it is counter to MSDN.
        WARN("Invalid module handle %p\n", hLibModule);
        ret = TRUE;
        goto done;
    }

    module->ThreadLibCalls = FALSE;
    ret = TRUE;

done:
    UnlockModuleList();
done_nolock:
    LOGEXIT("DisableThreadLibraryCalls returns BOOL %d\n", ret);
    PERF_EXIT(DisableThreadLibraryCalls);
    return ret;
}


/* Static function definitions ************************************************/

/*++
Function :
    LOADValidateModule

    Check whether the given MODSTRUCT pointer is valid

Parameters :
    MODSTRUCT *module : module to check

Return value :
    TRUE if module is valid, FALSE otherwise

--*/
static BOOL LOADValidateModule(MODSTRUCT *module)
{
    MODSTRUCT *modlist_enum;

    LockModuleList();

    modlist_enum=&exe_module;

    /* enumerate through the list of modules to make sure the given handle is
       really a module (HMODULEs are actually MODSTRUCT pointers) */
    do 
    {
        if(module==modlist_enum)
        {
            /* found it; check its integrity to be on the safe side */
            if(module->self!=module)
            {
                ERROR("Found corrupt module %p!\n",module);
                UnlockModuleList();
                return FALSE;
            }
            UnlockModuleList();
            TRACE("Module %p is valid (name : %S)\n", module,
                  MODNAME(module));
            return TRUE;
        }
        modlist_enum = modlist_enum->next;
    }
    while (modlist_enum != &exe_module);

    TRACE("Module %p is NOT valid.\n", module);
    UnlockModuleList();
    return FALSE;
}

/*++
Function :
    LOADGetModuleFileName [internal]

    Retrieve the module's full path if it is known, the short name given to
    LoadLibrary otherwise.

Parameters :
    MODSTRUCT *module : module to check

Return value :
    pointer to internal buffer with name of module (Unicode)

Notes :
    this function assumes that the module critical section is held, and that
    the module has already been validated.
--*/
static LPWSTR LOADGetModuleFileName(MODSTRUCT *module)
{
    LPWSTR module_name;
    /* special case : if module is NULL, we want the name of the executable */
    if(!module)
    {
        module_name = exe_module.lib_name;
        TRACE("Returning name of main executable\n");
        return module_name;
    }

    /* return "real" name of module if it is known. we have this if LoadLibrary
       was given an absolute or relative path; we can also determine it at the
       first GetProcAdress call. */
    TRACE("Returning full path name of module\n");
    return module->lib_name;
}

/*++
Function :
    LOADAllocModule

    Allocate and initialize a new MODSTRUCT structure

Parameters :
    void *dl_handle :   handle returned by dl_open, goes in MODSTRUCT::dl_handle
    
    char *name :        name of new module. after conversion to widechar, 
                        goes in MODSTRUCT::lib_name
                        
Return value:
    a pointer to a new, initialized MODSTRUCT strucutre, or NULL on failure.
    
Notes :
    'name' is used to initialize MODSTRUCT::lib_name. The other member is set to NULL
    In case of failure (in malloc or MBToWC), this function sets LastError.
--*/
static MODSTRUCT *LOADAllocModule(void *dl_handle, LPCSTR name)
{   
    MODSTRUCT *module;
    LPWSTR wide_name;
    CPalThread* pThread = NULL;

    pThread = InternalGetCurrentThread();	
    /* no match found : try to create a new module structure */
    module=(MODSTRUCT *) InternalMalloc(pThread, sizeof(MODSTRUCT));
    if(!module)
    {
        ERROR("malloc() failed! errno is %d (%s)\n", errno, strerror(errno));
        return NULL;
    }

    wide_name = UTIL_MBToWC_Alloc(name, -1);
    if(NULL == wide_name)
    {
        ERROR("couldn't convert name to a wide-character string\n");
        InternalFree(pThread, module);
        return NULL;
    }

    module->dl_handle = dl_handle;
#if defined(CORECLR) && defined(__APPLE__)
    module->sys_module = NULL;
#endif // CORECLR && __APPLE__
#if NEED_DLCOMPAT
    if (isdylib(module))
    {
        module->refcount = -1;
    }
    else
    {
        module->refcount = 1;
    }
#else   // NEED_DLCOMPAT
    module->refcount = 1;
#endif  // NEED_DLCOMPAT
    module->self = module;
    module->ThreadLibCalls = TRUE;
    module->next = NULL;
    module->prev = NULL;

    module->lib_name = wide_name;

    return module;
}

/*++
Function :
    LOADLoadLibrary [internal]

    implementation of LoadLibrary (for use by the A/W variants)

Parameters :
    LPSTR ShortAsciiName : name of module as specified to LoadLibrary

    BOOL fDynamic : TRUE if dynamic load through LoadLibrary, FALSE if static load through RegisterLibrary

Return value :
    handle to loaded module

--*/
static HMODULE LOADLoadLibrary(LPCSTR ShortAsciiName, BOOL fDynamic)
{
    CHAR fullLibraryName[MAX_PATH];
    MODSTRUCT *module = NULL;
    void *dl_handle;
    DWORD dwError;

    // Check whether we have been requested to load 'libc'. If that's the case then use the
    // full name of the library that is defined in <gnu/lib-names.h> by the LIBC_SO constant.
    // The problem is that calling dlopen("libc.so") will fail for libc even thought it works
    // for other libraries. The reason is that libc.so is just linker script (i.e. a test file).
    // As a result, we have to use the full name (i.e. lib.so.6) that is defined by LIBC_SO.
    if (strcmp(ShortAsciiName, LIBC_NAME_WITHOUT_EXTENSION) == 0)
    {
        ShortAsciiName = LIBC_SO;
    }

    LockModuleList();

    /* see if file can be dlopen()ed; this should work even if it's already
        loaded */

    {
        // See GetProcAddress for an explanation why we leave the PAL.
        PAL_LeaveHolder holder;
        dl_handle = dlopen(ShortAsciiName, RTLD_LAZY);

        // P/Invoke calls are often defined without an extension in the name of the 
        // target library. So if we failed to load the specified library, try adding
        // a proper extension and load the library again.
        if (!dl_handle)
        {
            if (snprintf(fullLibraryName, MAX_PATH, "%s%s", ShortAsciiName, PAL_SHLIB_SUFFIX) < MAX_PATH)
            {
                dl_handle = dlopen(fullLibraryName, RTLD_LAZY);
                if (dl_handle)
                {
                    ShortAsciiName = fullLibraryName;
                }
            }
        }
    }

    if (!dl_handle)
    {
        WARN("dlopen() failed; dlerror says '%s'\n", dlerror()); 
        SetLastError(ERROR_MOD_NOT_FOUND);
        goto done;
    }
    TRACE("dlopen() found module %s\n", ShortAsciiName);


#if !RETURNS_NEW_HANDLES_ON_REPEAT_DLOPEN
    /* search module list for a match. */
    module = &exe_module;
    do
    {
        if (dl_handle == module->dl_handle)
        {   
            /* found the handle. increment the refcount and return the 
               existing module structure */
            TRACE("Found matching module %p for module name %s\n",
                 module, ShortAsciiName);
            if (module->refcount != -1)
                module->refcount++;
            dlclose(dl_handle);
            goto done;
        }
        module = module->next;
    } while (module != &exe_module);
#endif

    TRACE("Module doesn't exist : creating %s.\n", ShortAsciiName);
    module = LOADAllocModule(dl_handle, ShortAsciiName);

    if(NULL == module)
    {
        ERROR("couldn't create new module\n");
        SetLastError(ERROR_NOT_ENOUGH_MEMORY);
        dlclose(dl_handle);
        goto done;
    }

    /* Add the new module on to the end of the list */
    module->prev = exe_module.prev;
    module->next = &exe_module;
    exe_module.prev->next = module;
    exe_module.prev = module;

#if RETURNS_NEW_HANDLES_ON_REPEAT_DLOPEN
    module->inode = stat_buf.st_ino; 
    module->device = stat_buf.st_dev;
#endif

    /* If we get here, then we have created a new module structure. We can now
       get the address of DllMain if the module contains one. We save
       the last error and restore it afterward, because our caller doesn't
       care about GetProcAddress failures. */
    dwError = GetLastError();

    module->pDllMain = (PDLLMAIN)GetProcAddress((HMODULE)module, "DllMain");

    SetLastError(dwError);

    /* If it did contain a DllMain, call it. */
    if(module->pDllMain)
    {
        DWORD dllmain_retval;

        TRACE("Calling DllMain (%p) for module %S\n", 
              module->pDllMain, 
              module->lib_name ? module->lib_name : W16_NULLSTRING);

        {
#if !_NO_DEBUG_MESSAGES_
            /* reset ENTRY nesting level back to zero while inside the callback... */
            int old_level;
            old_level = DBG_change_entrylevel(0);
#endif /* !_NO_DEBUG_MESSAGES_ */

            {
                // This module may be foreign to our PAL, so leave our PAL.
                // If it depends on us, it will re-enter.
                PAL_LeaveHolder holder;
                dllmain_retval = module->pDllMain((HINSTANCE) module,
                    DLL_PROCESS_ATTACH, fDynamic ? NULL : (LPVOID)-1);
            }

#if !_NO_DEBUG_MESSAGES_
            /* ...and set nesting level back to what it was */
            DBG_change_entrylevel(old_level);
#endif /* !_NO_DEBUG_MESSAGES_ */
        }

        /* If DlMain(DLL_PROCESS_ATTACH) returns FALSE, we must immediately
           unload the module.*/
        if(FALSE == dllmain_retval)
        {
            TRACE("DllMain returned FALSE; unloading module.\n");
            module->pDllMain = NULL;
            FreeLibrary((HMODULE) module);
            ERROR("DllMain failed and returned NULL. \n");
            SetLastError(ERROR_DLL_INIT_FAILED);
            module = NULL;
        }
    }
    else
    {
        TRACE("Module does not contain a DllMain function.\n");
    }

done:
    UnlockModuleList();
    return (HMODULE)module;
}

/*++
Function :
    LOAD_SEH_CallDllMain

    Exception-safe call to DllMain.

Parameters :
    MODSTRUCT *module : module whose DllMain must be called

    DWORD dwReason : parameter to pass down to DllMain, one of DLL_PROCESS_ATTACH, DLL_PROCESS_DETACH, 
        DLL_THREAD_ATTACH, DLL_THREAD_DETACH

    LPVOID lpvReserved : parameter to pass down to DllMain,
        If dwReason is DLL_PROCESS_ATTACH, lpvReserved is NULL for dynamic loads and non-NULL for static loads. 
        If dwReason is DLL_PROCESS_DETACH, lpvReserved is NULL if DllMain has been called by using FreeLibrary 
            and non-NULL if DllMain has been called during process termination. 

(no return value)

Notes :
This function is called from LOADFreeModules. Since we get there from
PAL_Terminate, we can't let exceptions in DllMain go unhandled :
TerminateProcess would be called, and would have to abort uncleanly because
termination was already started. So we catch the exception and ignore it;
we're terminating anyway.
*/
static void LOAD_SEH_CallDllMain(MODSTRUCT *module, DWORD dwReason, LPVOID lpReserved)
{
#if !_NO_DEBUG_MESSAGES_
    /* reset ENTRY nesting level back to zero while inside the callback... */
    int old_level = DBG_change_entrylevel(0);
#endif /* !_NO_DEBUG_MESSAGES_ */
    
    struct Param
    {
        MODSTRUCT *module;
        DWORD dwReason;
        LPVOID lpReserved;
    } param;
    param.module = module;
    param.dwReason = dwReason;
    param.lpReserved = lpReserved;

    PAL_TRY(Param *, pParam, &param)
    {
        TRACE("Calling DllMain (%p) for module %S\n",
              pParam->module->pDllMain, 
              pParam->module->lib_name ? pParam->module->lib_name : W16_NULLSTRING);
        
        {
            // This module may be foreign to our PAL, so leave our PAL.
            // If it depends on us, it will re-enter.
            PAL_LeaveHolder holder;
            pParam->module->pDllMain((HMODULE)pParam->module, pParam->dwReason, pParam->lpReserved);
        }
    }
    PAL_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
    {
        WARN("Call to DllMain (%p) got an unhandled exception; "
              "ignoring.\n", module->pDllMain);
    }
    PAL_ENDTRY

#if !_NO_DEBUG_MESSAGES_
    /* ...and set nesting level back to what it was */
    DBG_change_entrylevel(old_level);
#endif /* !_NO_DEBUG_MESSAGES_ */
}

/*++
Function:
  LockModuleList

Abstract
  Enter the critical section associated to the module list

Parameter
  void

Return
  void
--*/
extern "C"
void LockModuleList()
{
    CPalThread * pThread = 
        (PALIsThreadDataInitialized() ? InternalGetCurrentThread() : NULL);

    InternalEnterCriticalSection(pThread , &module_critsec);
}

/*++
Function:
  UnlockModuleList

Abstract
  Leave the critical section associated to the module list

Parameter
  void

Return
  void
--*/
extern "C"
void UnlockModuleList()
{
    CPalThread * pThread = 
        (PALIsThreadDataInitialized() ? InternalGetCurrentThread() : NULL);

    InternalLeaveCriticalSection(pThread , &module_critsec);
}

/*++
    PAL_LOADLoadPEFile

    Map a PE format file into memory like Windows LoadLibrary() would do.
    Doesn't apply base relocations if the function is relocated.

Parameters:
    IN hFile - file to map

Return value:
    non-NULL - the base address of the mapped image
    NULL - error, with last error set.
--*/

void * PAL_LOADLoadPEFile(HANDLE hFile)
{
    ENTRY("PAL_LOADLoadPEFile (hFile=%p)\n", hFile);

    void * loadedBase = MAPMapPEFile(hFile);

#ifdef _DEBUG
    if (loadedBase != NULL)
    {
        char* envVar = getenv("PAL_ForcePEMapFailure");
        if (envVar && strlen(envVar) > 0)
        {
            TRACE("Forcing failure of PE file map, and retry\n");
            PAL_LOADUnloadPEFile(loadedBase); // unload it
            loadedBase = MAPMapPEFile(hFile); // load it again
        }
    }
#endif // _DEBUG

    LOGEXIT("PAL_LOADLoadPEFile returns %p\n", loadedBase);
    return loadedBase;
}


/*++
    PAL_LOADUnloadPEFile

    Unload a PE file that was loaded by PAL_LOADLoadPEFile().

Parameters:
    IN ptr - the file pointer returned by PAL_LOADLoadPEFile()

Return value:
    TRUE - success
    FALSE - failure (incorrect ptr, etc.)
--*/

BOOL PAL_LOADUnloadPEFile(void * ptr)
{
    BOOL retval = FALSE;

    ENTRY("PAL_LOADUnloadPEFile (ptr=%p)\n", ptr);

    if (NULL == ptr)
    {
        ERROR( "Invalid pointer value\n" );
    }
    else
    {
        retval = MAPUnmapPEFile(ptr);
    }

    LOGEXIT("PAL_LOADUnloadPEFile returns %d\n", retval);
    return retval;
}

#if !defined(CORECLR) || !defined(__APPLE__)
/*++
Function:
  FindLibrary

Abstract
    Search LD_LIBRARY_PATH/DYLD_LIBRARY_PATH for a file named pszRelName

Parameter
    pszRelName: The relative name of the file sought
    ppszFullName: A pointer that will be filled in with the full filename if
        we find it

Return
    0 if completed successfully, even if library not found
    -1 on error
--*/
INT FindLibrary(CHAR* pszRelName, CHAR** ppszFullName)
{
    CPalThread *pThread = NULL;
    CHAR*   pszLibPath = NULL;
    CHAR*   pszNext = NULL;
    CHAR**  rgpLibDirSeparators = NULL;
    UINT    cSeparators = 0;
    UINT    iSeparator = 0;
    UINT    iStringLen = 0;
    INT     iRetVal = 0;
    CHAR*   pszSearchPath = NULL;
    BOOL    fSearchPathNeedsFreeing = FALSE;

    if (!ppszFullName)
    {
        SetLastError(ERROR_INVALID_PARAMETER);
        iRetVal = -1;
        goto Done;
    }
    *ppszFullName = NULL;

    // First, get the LD_LIBRARY_PATH to figure out where to look
    // Note that pszLibPath points to system memory -- don't free.
    pszLibPath = MiscGetenv(LIBSEARCHPATH);
    if (!pszLibPath)
    {
        TRACE("FindLibrary: " LIBSEARCHPATH " not set\n");
        pszLibPath = (char*)".";
    }
    else
    {
        TRACE("FindLibrary: " LIBSEARCHPATH " is %s\n", pszLibPath);
    }

    pThread = InternalGetCurrentThread();
    iStringLen = strlen(pszLibPath);

    // We want to make sure that we always search the current directory,
    // regardless of whether LD_LIBRARY_PATH includes it (this mimics
    // Windows behavior)
    if ( (!(strstr(pszLibPath, ":.:"))) && // if you don't find '.' in the middle
         (!(iStringLen == 1 && pszLibPath[0] == '.')) && // if it's not just equal to '.'
         (!(iStringLen >= 2 && pszLibPath[0] == '.' 
                            && pszLibPath[1] == ':')) && // if it doesn't start with ".:"
         (!(iStringLen >= 2 && pszLibPath[iStringLen-2] == ':' 
                            && pszLibPath[iStringLen-1] == '.')) ) // if it doesn't end with ":."
    {
        // 3 is hardcoded here for :. and null
        int iLen = sizeof(pszSearchPath[0]) * (iStringLen + 3);
        pszSearchPath = (char*) InternalMalloc (pThread, iLen);
        if (!pszSearchPath)
        {
            SetLastError(ERROR_NOT_ENOUGH_MEMORY);
            iRetVal = -1;
            goto Done;
        }
        iStringLen += 3; // This 3 is hard coded for :. and null
        fSearchPathNeedsFreeing = TRUE;
        if (strcpy_s(pszSearchPath, iLen, pszLibPath) != SAFECRT_SUCCESS)
        {
            ERROR("strcpy_s failed!\n");
            SetLastError(ERROR_INSUFFICIENT_BUFFER);
            goto Done;
        }

        if (strcat_s(pszSearchPath, iLen, ":.") != SAFECRT_SUCCESS)
        {
            ERROR("strcat_s failed!\n");
            SetLastError(ERROR_INSUFFICIENT_BUFFER);
            goto Done;
        }
    }
    // If LD_LIBRARY_PATH already includes a reference to the current
    // directory, we'll search it in the right order.
    else
    {
        pszSearchPath = pszLibPath;
    }
      
    _ASSERTE(strchr(pszSearchPath, '.'));

    // Allocate an array for pointers to separators -- there can't be more than
    // the length of LD_LIBRARY_PATH - 1 separators (since we always have atleast a '.' in it )
    //                      + 2 implicit seperators...
    rgpLibDirSeparators = (char **) 
                InternalMalloc(pThread, sizeof(rgpLibDirSeparators[0]) * (iStringLen+1));
    if (!rgpLibDirSeparators)
    {
        SetLastError(ERROR_NOT_ENOUGH_MEMORY);
        iRetVal = -1;
        goto Done;
    }

    // Now, find the separators in LD_LIBRARY_PATH.  Set a pointer to each :
    pszNext = pszSearchPath;
    // There's an implicit separator at the start...
    rgpLibDirSeparators[0] = pszNext - 1;
    cSeparators = 1;
    while (*pszNext != '\0')
    {
        if (*pszNext == ':')
        {
            _ASSERTE(cSeparators < iStringLen);
            rgpLibDirSeparators[cSeparators] = pszNext;
            cSeparators++;
        }
        pszNext++;
    }

    _ASSERTE(cSeparators <= iStringLen);
    // And there's an implicit separator at the end.
    rgpLibDirSeparators[cSeparators] = pszNext;
    cSeparators++;

    // Now, check each path for the File
    // Note that cSeparators is always >= 2, so the < -1 check is safe
    for (iSeparator = 0; iSeparator < (cSeparators-1); iSeparator++)
    {
        CHAR        szFileName[MAX_PATH + 1];
        CHAR        szDirName[MAX_PATH + 1];
        struct stat stat_buf;
        UINT        cchDirName = 0;

        // length of DirName is number of chars between the first char after 
        // the colon and the next colon
        cchDirName = rgpLibDirSeparators[iSeparator + 1] - 
                        (rgpLibDirSeparators[iSeparator] + 1);
        memcpy(szDirName, rgpLibDirSeparators[iSeparator] + 1, cchDirName);
        szDirName[cchDirName] = '\0';
        snprintf(szFileName, MAX_PATH, "%s/%s", szDirName, pszRelName);
        if (0 == stat(szFileName, &stat_buf))
        {
            // First, make sure we've got the canonical path
            CHAR   szRealPath[PATH_MAX + 1];

            if(!realpath(szFileName, szRealPath))
            {
                ASSERT("realpath() failed! problem path is %s\n", szFileName);
                SetLastError(ERROR_INTERNAL_ERROR);
                goto Done;
            }
            // We've found it.  Rejoice!
            TRACE("FindLibrary: found file: %s\n", szRealPath);
            *ppszFullName = InternalStrdup(pThread, szRealPath);
            if (!*ppszFullName)
            {
                SetLastError(ERROR_NOT_ENOUGH_MEMORY);
                iRetVal = -1;
            }
            goto Done;
        }
    }

Done:
    if (rgpLibDirSeparators)
        InternalFree(pThread, rgpLibDirSeparators);
    if (fSearchPathNeedsFreeing)
        InternalFree(pThread, pszSearchPath);
    // Don't treat it as an error if the library's not found -- just set
    // *ppszFullName to NULL.
    return iRetVal;
}
#endif // !CORECLR || !__APPLE__

/*++
    LOADInitCoreCLRModules

    Run the initialization methods for CoreCLR modules that used to be standalone dynamic libraries (PALRT and
    mscorwks).

Parameters:
    void

Return value:
    TRUE if successful
    FALSE if failure
--*/
BOOL LOADInitCoreCLRModules()
{
#ifdef __APPLE__
    {
        PAL_LeaveHolder holder;
        if (!g_pPalRTDllMain((HMODULE)&pal_module, DLL_PROCESS_ATTACH, NULL))
            return FALSE;
    }
#endif // __APPLE__
    return g_pRuntimeDllMain((HMODULE)&pal_module, DLL_PROCESS_ATTACH, NULL);
}

#if defined(CORECLR) && defined(__APPLE__)
// Abstract the API used to load and query for functions in the CoreCLR binary to make it easier to change the
// underlying implementation.

// Load the CoreCLR module into memory given the directory in which it resides. Returns NULL on failure.
CORECLRHANDLE LoadCoreCLR(const char *szPath)
{
    CFStringRef hPath = NULL;
    CFURLRef    hUrl = NULL;
    CFBundleRef hBundle = NULL;

    // We're handed the full path to the CoreCLR directory but CFBundleCreate wants the path of the bundle
    // directory that contains it. So we have to strip two directory components off.
    int iLen = strlen(szPath) + 1;
    char *szBundlePath = (char*)alloca(iLen);
    
    if (strcpy_s(szBundlePath, iLen, szPath) != SAFECRT_SUCCESS)
    {
        ERROR("strcpy_s failed!\n");
        SetLastError(ERROR_INSUFFICIENT_BUFFER);
        goto done;
    }

    // Null out the last three slashes:
    //      <foo>/CoreCLR.bundle/Contents/MacOS/ -> <foo>/CoreCLR.bundle/Contents/MacOS
    //      <foo>/CoreCLR.bundle/Contents/MacOS -> <foo>/CoreCLR.bundle/Contents
    //      <foo>/CoreCLR.bundle/Contents -> <foo>/CoreCLR.bundle
    TRACE("LoadCoreCLR: szPath = \"%s\"\n", szPath);
    for (int i = 0; i < 3; i++)
    {
        char *szLastSlash = rindex(szBundlePath, '/');
        if (szLastSlash == NULL)
        {
            ERROR("Got invalid bundle path \"%s\"\n", szPath);
            SetLastError(ERROR_INVALID_PARAMETER);
            goto done;
        }
        *szLastSlash = '\0';
    }

    // Convert the pathname provided as a cstring to a CFString.
    hPath = CFStringCreateWithCString(kCFAllocatorDefault, szBundlePath, kCFStringEncodingUTF8);
    if (hPath == NULL)
    {
        SetLastError(ERROR_NOT_ENOUGH_MEMORY);
        goto done;
    }

    // Convert the path into a URL.
    hUrl = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, hPath, kCFURLPOSIXPathStyle, TRUE);
    if (hUrl == NULL)
    {
        SetLastError(ERROR_NOT_ENOUGH_MEMORY);
        goto done;
    }

    // Load the bundle from the URL.
    hBundle = CFBundleCreate(kCFAllocatorDefault, hUrl);

  done:
    if (hUrl)
        CFRelease(hUrl);
    if (hPath)
        CFRelease(hPath);

    return hBundle;
}

// Lookup the named function in the given CoreCLR image. Returns NULL on failure.
void *LookupFunctionInCoreCLR(CORECLRHANDLE hCoreCLR, const char *szFunction)
{
    CFStringRef hFunction = NULL;
    void       *pFunction = NULL;

    // Convert the function name provided as a cstring to a CFString.
    hFunction = CFStringCreateWithCString(kCFAllocatorDefault, szFunction, kCFStringEncodingUTF8);
    if (hFunction == NULL)
        goto done;

    // Look up the function name in the bundle.
    {
        // We temporarily leave PAL as a workaround for what is presumably a problem in gdb (as of version 477).
        // The function we call here may call into dyld for linking new images, and gdb sets a breakpoint deep
        // in there so that it knows about it, and can load new symbol files. We leave the PAL so that we
        // unhook the exception port for hardware breakpoints.
        //
        // Strictly speaking, we'd expect this to work without leaving the PAL: For a breakpoint exception, if
        // no managed debugger is attached, our thread-level handler sends back a message to the system that
        // we do not with to handle it. This causes the system to forward the exception message to the task
        // and host-level handlers. However, gdb's host-level handler seems to hang in this case.
        PAL_LeaveHolder holder;
        pFunction = CFBundleGetFunctionPointerForName(hCoreCLR, hFunction);
    }

  done:
    if (hFunction)
        CFRelease(hFunction);

    return pFunction;
}

// Locate the CoreCLR module handle associated with the code currently executing. Returns NULL on failure.
CORECLRHANDLE FindCoreCLRHandle()
{
    // Return NULL when we're not really part of CoreCLR (i.e. we're a standalone PAL).
    if (g_szCoreCLRPath[0] == '\0')
    {
        SetLastError(ERROR_NOT_SUPPORTED);
        return NULL;
    }

    // Reloading the same bundle will just return a reference to the exiting copy and we know the path from
    // which the host originally loaded us.
    return LoadCoreCLR(g_szCoreCLRPath);
}
#endif // CORECLR && __APPLE__

/*++
Function:
  PAL_GetModuleBaseFromAddress

  Given an address, returns the base address of the dynamic module which contains that address, 
  or NULL if none.

  Notes:
    This is a replacement for code that casts HMODULEs to pointers on Windows.
    Ideally this would take an HMODULE instead of an address, but that is harder - we don't seem to
    have a way to map it directly to a dyld index or to get an address from it. Eg., we're not 
    guaranteed toh ave a module name, dllMain or dyld handle.
 */
#ifdef __APPLE__
PALAPI
LPCVOID
PAL_GetModuleBaseFromAddress(LPCVOID pAddress)
{
    LPCVOID retval = NULL;

    PERF_ENTRY(PAL_GetModuleBaseFromAddress);
    ENTRY("PAL_GetModuleBaseFromAddress (pAddress=%p)\n", pAddress);

    // Given a pointer into the module, get the header at the start of the module
    retval = _dyld_get_image_header_containing_address(pAddress);
    if (retval == NULL)
    {
        // All modules we load use dyld (even bundles are implemented using this in the OS)
        TRACE("Address isn't recognized as being in a dyld module: %p\n", pAddress);
        goto done;
    }

    TRACE("base address of module with address %p is %p\n", pAddress, retval);

done:
    LOGEXIT("PAL_GetModuleBaseFromAddress returns %p\n", retval);
    PERF_EXIT(PAL_GetModuleBaseFromAddress);
    return retval;
}

//---------------------------------------------------------------------------------------
//
// Retrieve the UUID in the image.
//
// Arguments:
//    pImageBase - the base address of where an image is loaded into memory
//    pUUID      - out parameter; return the UUID in the image
//
// Assumptions:
//    The buffer pointed to by pUUID must have at least 16 bytes.
//
// Return Value:
//    TRUE if this function successfully retrieves the UUID from the specified image
//

PALAPI
BOOL
PAL_GetUUIDOfImage(LPCVOID pImageBase, BYTE * pUUID)
{
        PERF_ENTRY(PAL_GetUUIDOfImage);
    ENTRY("PAL_GetUUIDOfImage (pImageBase=%p, pUUID=%p)\n", pImageBase, pUUID);

    // There should be a Mach-O header at the image base.
    const mach_header * pHeader;
    pHeader = reinterpret_cast<const mach_header *>(pImageBase);

    const load_command * pCurCommand = NULL;
    UINT32 cLoadCommands = 0;
    BOOL fFoundUUID = FALSE;
    
    // The offset to the magic number is the same for both mach_header and for
    // mach_header_64 (same size too), so it's safe to use it to check for
    // MH_MAGIC_64.
    if (pHeader->magic == MH_MAGIC)
    {
        // Immediately following the header are the load commands.
        cLoadCommands = pHeader->ncmds;
        pCurCommand = reinterpret_cast<const load_command *>(pHeader + 1);

    }
    else if (pHeader->magic == MH_MAGIC_64)
    {
        const mach_header_64 * pHeader64;
	pHeader64 = reinterpret_cast<const mach_header_64 *>(pImageBase);
	cLoadCommands = pHeader64->ncmds;
	pCurCommand = reinterpret_cast<const load_command *>(pHeader64 + 1);
    }

    if (pCurCommand)
    {
        // Loop through the load commmands to find the LC_UUID load command.
        for (UINT32 i = 0; i < cLoadCommands; i++)
	{
            if (pCurCommand->cmd == LC_UUID)
            {
                const uuid_command * pUUIDCommand = reinterpret_cast<const uuid_command *>(pCurCommand);

                // sanity check
                if (pUUIDCommand->cmdsize == sizeof(uuid_command))
                {
		    // Copy the 16-byte UUID into the out buffer.
                    memcpy(pUUID, pUUIDCommand->uuid, sizeof(pUUIDCommand->uuid));
                    fFoundUUID = TRUE;
                    break;
                }
            }
            pCurCommand = reinterpret_cast<const load_command *>((SIZE_T)pCurCommand + pCurCommand->cmdsize);
        }
    }

    LOGEXIT("PAL_GetUUIDOfImage\n");
    PERF_EXIT(PAL_GetUUIDOfImage);
    return fFoundUUID;
}

//---------------------------------------------------------------------------------------
// Retrieve the version stored in the Info.plist file in a bundle.
//
// Arguments:
//    bundle                 - Target bundle.
//    pwszVersionString      - out parameter; buffer to be filled with the version string
//    cchVersionStringBuffer - size of the buffer in # of characters pointed to by pwszVersionString
//    pcchVersionStringBufferRequired - required size in characters, including NULL.
//
// Return Value:
//    Return the number of characters in the version string (excluding NULL) or 0 if the operation fails.
//
// Notes:
//    Call GetLastError() to retrieve more information if the function fails.
//
static DWORD GetBundleVersionString(IN CFBundleRef bundle,
                                    IN WCHAR *pwszVersionString,
                                    IN DWORD cchVersionStringBuffer, 
                                    IN DWORD *pcchVersionStringBufferRequired)
{
    CFTypeRef   hVersionString     = NULL;
    CFStringRef hRealVersionString = NULL;

    *pcchVersionStringBufferRequired = 0;

    // Get a CFTypeRef to the version string stored in the Info.plist file in the CoreCLR bundle.
    // CFTypeRef is like an System.Object.  It's the base class in CoreFoundation.
    hVersionString = CFBundleGetValueForInfoDictionaryKey(bundle, kCFBundleVersionKey);
    if (hVersionString == NULL || CFGetTypeID(hVersionString) != CFStringGetTypeID())
    {
        SetLastError(ERROR_INVALID_DATA);
        return 0;
    }
    hRealVersionString = static_cast<CFStringRef>(hVersionString);

    // Get the length of the version string.
    S_UINT32 cchRealVersionString(ClrSafeInt<CFIndex>(CFStringGetLength(hRealVersionString)));
    if (cchRealVersionString.IsOverflow() || 
        !cchRealVersionString.addition(cchRealVersionString.Value(), 1ul, *pcchVersionStringBufferRequired))
    {
        SetLastError(ERROR_INVALID_DATA);
        return 0;
    }

    if (*pcchVersionStringBufferRequired > cchVersionStringBuffer)
    {
        SetLastError(ERROR_INSUFFICIENT_BUFFER);
        return 0;
    }

    // Copy the version string into the output buffer and make sure we put the NULL character at the end.
    CFStringGetCharacters(hRealVersionString, CFRangeMake(0, cchRealVersionString.Value()), pwszVersionString);
    pwszVersionString[cchRealVersionString.Value()] = L'\0';

    return cchRealVersionString.Value();
}

//---------------------------------------------------------------------------------------
//
// Retrieve the version stored in the Info.plist file in a bundle containing the passed in executable path.
//
// Arguments:
//    pwszCoreClrFullPath       - full path to CoreCLR
//    pwszVersionString         - out parameter; buffer to be filled with the version string
//    cchVersionStringBuffer    - size of the buffer in # of characters pointed to by pwszVersionString
//    pcchVersionStringBufferRequired - required size in characters, including NULL.
//
// Return Value:
//    Return the number of characters in the version string (excluding NULL) or 0 if the operation fails.
//
// Notes:
//    Call GetLastError() to retrieve more information if the function fails.
//

PALAPI
DWORD
PAL_GetVersionString(IN WCHAR * pwszCoreClrFullPath, 
                     IN OUT WCHAR * pwszVersionString, 
                     IN DWORD cchVersionStringBuffer,
                     OUT DWORD *pcchVersionStringBufferRequired)
{
    PERF_ENTRY(PAL_GetVersionString);
    ENTRY("PAL_GetVersionString (pwszCoreClrFullPath=%p (%S), pwszVersionString=%p, "
          "cchVersionStringBuffer=%u, pcchVersionStringBufferRequired=%p)\n", 
          (pwszCoreClrFullPath ? pwszCoreClrFullPath : W16_NULLSTRING),
          (pwszCoreClrFullPath ? pwszCoreClrFullPath : W16_NULLSTRING),
          pwszVersionString, cchVersionStringBuffer, pcchVersionStringBufferRequired);

    // various handles for dealing with the Core Foundation APIs
    CFStringRef hPath   = NULL;
    CFURLRef    hURL    = NULL;
    CFBundleRef hBundle = NULL;

    DWORD cchFullPath = PAL_wcslen(pwszCoreClrFullPath);
    DWORD cchVersionString = 0;

    // Make sure the full path is not too long.
    if (cchFullPath > MAX_PATH)
    {
        SetLastError(ERROR_INSUFFICIENT_BUFFER);
        goto LExit;
    }

    // Include an extra space for the NULL character.
    WCHAR wszBundlePath[MAX_PATH + 1];
    if (wcscpy_s(wszBundlePath, cchFullPath + 1, pwszCoreClrFullPath) != SAFECRT_SUCCESS)
    {
        SetLastError(ERROR_INSUFFICIENT_BUFFER);
        goto LExit;
    }

    // Null out the last three slashes:
    //      <foo>/CoreCLR.bundle/Contents/MacOS/ -> <foo>/CoreCLR.bundle/Contents/MacOS
    //      <foo>/CoreCLR.bundle/Contents/MacOS -> <foo>/CoreCLR.bundle/Contents
    //      <foo>/CoreCLR.bundle/Contents -> <foo>/CoreCLR.bundle
    for (int i = 0; i < 3; i++)
    {
        WCHAR * pwszLastSlash = PAL_wcsrchr(wszBundlePath, L'/');
        if (pwszLastSlash == NULL)
        {
            SetLastError(ERROR_INVALID_PARAMETER);
            goto LExit;
        }

        *pwszLastSlash = '\0';
    }

    // Create a CFStringRef representation of the bundle path.
    hPath = CFStringCreateWithCharacters(kCFAllocatorDefault, wszBundlePath, (CFIndex)PAL_wcslen(wszBundlePath));
    if (hPath == NULL)
    {
        SetLastError(ERROR_INSUFFICIENT_BUFFER);
        goto LExit;
    }

    // Create a CFURLRef representation of the bundle path.
    hURL = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, hPath, kCFURLPOSIXPathStyle, true);
    if (hURL == NULL)
    {
        SetLastError(ERROR_INSUFFICIENT_BUFFER);
        goto LExit;
    }

    // Create a handle to the CoreCLR bundle.
    hBundle = CFBundleCreate(kCFAllocatorDefault, hURL);
    if (hBundle == NULL)
    {
        SetLastError(ERROR_INSUFFICIENT_BUFFER);
        goto LExit;
    }

    cchVersionString = GetBundleVersionString(hBundle, pwszVersionString, cchVersionStringBuffer, 
        pcchVersionStringBufferRequired);

LExit:
    if (hURL != NULL)
    {
        CFRelease(hURL);
    }

    if (hPath != NULL)
    {
        CFRelease(hPath);
    }

    if (hBundle != NULL)
    {
        CFRelease(hBundle);
    }

    LOGEXIT("PAL_GetVersionString returns %u, pwszVersionString=\"%S\", *pcchVersionStringBufferRequired=%u\n",
        cchVersionString, (pwszVersionString ? pwszVersionString : W16_NULLSTRING),
        (pcchVersionStringBufferRequired ? *pcchVersionStringBufferRequired : 0));
    PERF_EXIT(PAL_GetVersionString);
    return cchVersionString;
}

//---------------------------------------------------------------------------------------
//
// Retrieve the version stored in the Info.plist file in the CoreCLR bundle.
//
// Arguments:
//    pwszVersionString         - out parameter; buffer to be filled with the version string
//    cchVersionStringBuffer    - size of the buffer in # of characters pointed to by pwszVersionString
//    pcchVersionStringBufferRequired - required size in characters, including NULL.
//
// Return Value:
//    Return the number of characters in the version string (excluding NULL) or 0 if the operation fails.
//
// Notes:
//    Call GetLastError() to retrieve more information if the function fails.
//

PALAPI
DWORD
PAL_GetCoreCLRVersionString(
                     IN OUT WCHAR * pwszVersionString, 
                     IN DWORD cchVersionStringBuffer,
                     IN DWORD *pcchVersionStringBufferRequired)
{
    PERF_ENTRY(PAL_GetCoreCLRVersionString);
    ENTRY("PAL_GetCoreCLRVersionString (pwszVersionString=%p, cchVersionStringBuffer=%u, "
          "pcchVersionStringBufferRequired=%p)\n", 
          pwszVersionString, cchVersionStringBuffer, pcchVersionStringBufferRequired);

    // various handles for dealing with the Core Foundation APIs
    CFBundleRef hBundle   = NULL;

    DWORD cchVersionString = 0;

    // NOTE: This code knows that CORECLRHANDLE is actually a CFBundleRef
    hBundle = (CFBundleRef)FindCoreCLRHandle();
    if (hBundle == NULL)
    {
        SetLastError(ERROR_INVALID_DATA);
        goto LExit;
    }

    cchVersionString = GetBundleVersionString(hBundle, pwszVersionString, cchVersionStringBuffer, 
        pcchVersionStringBufferRequired);

LExit:
    if (hBundle != NULL)
    {
        CFRelease(hBundle);
    }

    LOGEXIT("PAL_GetCoreCLRVersionString returns %u, pwszVersionString=\"%S\", *pcchVersionStringBufferRequired=%u\n",
        cchVersionString, (pwszVersionString ? pwszVersionString : W16_NULLSTRING),
        (pcchVersionStringBufferRequired ? *pcchVersionStringBufferRequired : 0));
    PERF_EXIT(PAL_GetCoreCLRVersionString);
    return cchVersionString;
}
#else // __APPLE__

// Get base address of the coreclr module
PALAPI
LPCVOID
PAL_GetCoreClrModuleBase()
{
    LPCVOID retval = NULL;

    PERF_ENTRY(PAL_GetModuleBaseFromHModule);
    ENTRY("PAL_GetCoreClrModuleBase\n");

    if(pal_module.dl_handle != NULL)
    {
        // To lookup module base address, we need an address inside of the module.
        // The coreclr.so contains the DllMain function, so we use it here.
        void* dllMain = dlsym(pal_module.dl_handle, "DllMain");
        if (dllMain != NULL)
        {
            Dl_info info;
            if (dladdr(dllMain, &info) != 0)
            {
                retval = info.dli_fbase;
            }
            else 
            {
                TRACE("Can't get base address of the libcoreclr.so\n");
                SetLastError(ERROR_INVALID_DATA);
            }
        }
        else
        {
            TRACE("Can't find DllMain in libcoreclr.so\n");
            SetLastError(ERROR_INVALID_DATA);
        }
    }
    else 
    {
        TRACE("Can't get libcoreclr.so base - the pal_module is not initialized\n");
        SetLastError(ERROR_MOD_NOT_FOUND);
    }

    LOGEXIT("PAL_GetCoreClrModuleBase returns %p\n", retval);
    PERF_EXIT(PAL_GetCoreClrModuleBase);
    return retval;
}

#endif // __APPLE__