summaryrefslogtreecommitdiff
path: root/src/binder/assemblybinder.cpp
blob: bd5dd18cc9f06425f1e8a9fcb71bde97105fab1d (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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// ============================================================
//
// AssemblyBinder.cpp
//


//
// Implements the AssemblyBinder class
//
// ============================================================

#include "assemblybinder.hpp"
#include "assemblyname.hpp"

#include "assembly.hpp"
#include "applicationcontext.hpp"
#include "loadcontext.hpp"
#include "bindresult.inl"
#include "failurecache.hpp"
#ifdef FEATURE_VERSIONING_LOG
#include "bindinglog.hpp"
#endif // FEATURE_VERSIONING_LOG
#include "utils.hpp"
#include "variables.hpp"
#include "stringarraylist.h"

#include "strongname.h"
#ifdef FEATURE_VERSIONING_LOG
#include "../dlls/mscorrc/fusres.h"
#endif // FEATURE_VERSIONING_LOG

#define APP_DOMAIN_LOCKED_INSPECTION_ONLY 0x01
#define APP_DOMAIN_LOCKED_UNLOCKED        0x02
#define APP_DOMAIN_LOCKED_CONTEXT         0x04

#define BIND_BEHAVIOR_STATIC            0
#define BIND_BEHAVIOR_ORDER_INDEPENDENT 1
#define BIND_BEHAVIOR_BEST_MATCH        2

#ifndef IMAGE_FILE_MACHINE_ARM64
#define IMAGE_FILE_MACHINE_ARM64             0xAA64  // ARM64 Little-Endian
#endif

BOOL IsCompilationProcess();

#if !defined(DACCESS_COMPILE) && !defined(CROSSGEN_COMPILE)
#include "clrprivbindercoreclr.h"
#include "clrprivbinderassemblyloadcontext.h"
// Helper function in the VM, invoked by the Binder, to invoke the host assembly resolver
extern HRESULT RuntimeInvokeHostAssemblyResolver(INT_PTR pManagedAssemblyLoadContextToBindWithin, 
                                                IAssemblyName *pIAssemblyName, CLRPrivBinderCoreCLR *pTPABinder,
                                                BINDER_SPACE::AssemblyName *pAssemblyName, ICLRPrivAssembly **ppLoadedAssembly);

// Helper to check if we have a host assembly resolver set
extern BOOL RuntimeCanUseAppPathAssemblyResolver(DWORD adid);

#endif // !defined(DACCESS_COMPILE) && !defined(CROSSGEN_COMPILE)

namespace BINDER_SPACE
{
    typedef enum
    {
        kVersionIgnore,
        kVersionExact,
        kVersionServiceRollForward,
        kVersionFeatureRollForward,
        kVersionFeatureExact,
        kVersionFeatureHighest,
        kVersionFeatureLowestHigher,
        kVersionFeatureHighestLower
    } VersionMatchMode;

    namespace
    {
        BOOL fAssemblyBinderInitialized = FALSE;

        //
        // This defines the assembly equivalence relation
        //
        HRESULT IsValidAssemblyVersion(/* in */ AssemblyName *pRequestedName,
                                       /* in */ AssemblyName *pFoundName,
                                       /* in */ ApplicationContext *pApplicationContext)
        {
            HRESULT hr = S_OK;
            BINDER_LOG_ENTER(W("IsValidAssemblyVersion"));
            AssemblyVersion *pRequestedVersion = pRequestedName->GetVersion();
            AssemblyVersion *pFoundVersion = pFoundName->GetVersion();

            //
            // If the AssemblyRef has no version, we can treat it as requesting the most accommodating version (0.0.0.0). In
            // that case, skip version checking and allow the bind.
            //
            if (!pRequestedName->HaveAssemblyVersion())
            {
                return hr;
            }

            //
            // This if condition is paired with the one above that checks for pRequestedName
            // not having an assembly version.  If we didn't exit in the above if condition,
            // and satisfy this one's requirements, we're in a situation where the assembly
            // Ref has a version, but the Def doesn't, which cannot succeed a bind
            //
            _ASSERTE(pRequestedName->HaveAssemblyVersion());
            if (!pFoundName->HaveAssemblyVersion())
            {
                hr = FUSION_E_APP_DOMAIN_LOCKED;
            }
            else if (pRequestedVersion->IsEqualFeatureVersion(pFoundVersion))
            {
                // Now service version matters
                if (pRequestedVersion->IsLargerServiceVersion(pFoundVersion))
                {
                    hr = FUSION_E_APP_DOMAIN_LOCKED;
                }
            }
            else if (pRequestedVersion->IsLargerFeatureVersion(pFoundVersion))
            {
                hr = FUSION_E_APP_DOMAIN_LOCKED;
            }

            if (pApplicationContext->IsTpaListProvided() && hr == FUSION_E_APP_DOMAIN_LOCKED)
            {
                // For our new binding models, use a more descriptive error code than APP_DOMAIN_LOCKED for bind
                // failures.
                hr = FUSION_E_REF_DEF_MISMATCH;
            }

            BINDER_LOG_LEAVE_HR(W("IsValidAssemblyVersion"), hr)
            return hr;
        }

        HRESULT URLToFullPath(PathString &assemblyPath)
        {
            HRESULT hr = S_OK;

            SString::Iterator pos = assemblyPath.Begin();
            if (assemblyPath.MatchCaseInsensitive(pos, g_BinderVariables->httpURLPrefix))
            {
                // HTTP downloads are unsupported
                hr = FUSION_E_CODE_DOWNLOAD_DISABLED;
            }
            else
            {
                SString fullAssemblyPath;
                WCHAR *pwzFullAssemblyPath = fullAssemblyPath.OpenUnicodeBuffer(MAX_LONGPATH);
                DWORD dwCCFullAssemblyPath = MAX_LONGPATH + 1; // SString allocates extra byte for null.

                MutateUrlToPath(assemblyPath);

                dwCCFullAssemblyPath = WszGetFullPathName(assemblyPath.GetUnicode(),
                                                          dwCCFullAssemblyPath,
                                                          pwzFullAssemblyPath,
                                                          NULL);
                if (dwCCFullAssemblyPath > MAX_LONGPATH)
                {
                    fullAssemblyPath.CloseBuffer();
                    pwzFullAssemblyPath = fullAssemblyPath.OpenUnicodeBuffer(dwCCFullAssemblyPath - 1);
                    dwCCFullAssemblyPath = WszGetFullPathName(assemblyPath.GetUnicode(),
                                                              dwCCFullAssemblyPath,
                                                              pwzFullAssemblyPath,
                                                              NULL);
                }
                fullAssemblyPath.CloseBuffer(dwCCFullAssemblyPath);

                if (dwCCFullAssemblyPath == 0)
                {
                    hr = HRESULT_FROM_GetLastError();
                }
                else
                {
                    assemblyPath.Set(fullAssemblyPath);
                }
            }

            return hr;
        }


#ifdef FEATURE_VERSIONING_LOG
        //
        // This function outputs the current binding result
        // and flushes the bind log.
        //
        HRESULT LogBindResult(ApplicationContext *pApplicationContext,
                              HRESULT             hrLog,
                              BindResult         *pBindResult)
        {
            HRESULT hr = S_OK;
            BindingLog *pBindingLog = pApplicationContext->GetBindingLog();

            if (!pBindingLog->CanLog())
            {
                // For non-logging, return the bind result
                hr = hrLog;
                goto Exit;
            }

            IF_FAIL_GO(pBindingLog->LogHR(hrLog));

            if ((hrLog == S_OK) && pBindResult->HaveResult())
            {
                IF_FAIL_GO(pBindingLog->LogResult(pBindResult));
            }

            IF_FAIL_GO(pBindingLog->Flush());

            // For failure-free logging, return the bind result
            hr = hrLog;

        Exit:
            // SilverLight does not propagate binding log; therefore kill the information here.
            pApplicationContext->ClearBindingLog();
            return hr;
        }

        inline UINT GetLockedContextEntry(BOOL fInspectionOnly)
        {
            if (fInspectionOnly)
                return ID_FUSLOG_BINDING_LOCKED_ASSEMBLY_INS_CONTEXT;
            else
                return ID_FUSLOG_BINDING_LOCKED_ASSEMBLY_EXE_CONTEXT;
        }

        inline UINT GetLockedEntry(BOOL fInspectionOnly)
        {
            if (fInspectionOnly)
                return ID_FUSLOG_BINDING_LOCKED_MT_INS_LOCKED_ENTRY;
            else
                return ID_FUSLOG_BINDING_LOCKED_MT_EXE_LOCKED_ENTRY;
        }

        inline UINT GetLocalizedEntry(BOOL fInspectionOnly)
        {
            if (fInspectionOnly)
                return ID_FUSLOG_BINDING_LOCKED_MT_INS_LOCALI_ENTRY;
            else
                return ID_FUSLOG_BINDING_LOCKED_MT_EXE_LOCALI_ENTRY;
        }

        inline UINT GetCBaseEntry(BOOL fInspectionOnly)
        {
            if (fInspectionOnly)
                return ID_FUSLOG_BINDING_LOCKED_MT_INS_CBASE_ENTRY;
            else
                return ID_FUSLOG_BINDING_LOCKED_MT_EXE_CBASE_ENTRY;
        }

        HRESULT LogAppDomainLocked(ApplicationContext *pApplicationContext,
                                   DWORD               dwLockedReason,
                                   AssemblyName       *pAssemblyName = NULL)
        {
            HRESULT hr = S_OK;
            BindingLog *pBindingLog = pApplicationContext->GetBindingLog();

            if (pBindingLog->CanLog())
            {
                PathString info;
                PathString format;
                BOOL fInspectionOnly = FALSE;

                if ((dwLockedReason & APP_DOMAIN_LOCKED_INSPECTION_ONLY) != 0)
                {
                    dwLockedReason &= ~APP_DOMAIN_LOCKED_INSPECTION_ONLY;
                    fInspectionOnly = TRUE;
                }

                switch (dwLockedReason)
                {
                case APP_DOMAIN_LOCKED_UNLOCKED:
                {
                    IF_FAIL_GO(info.
                               LoadResourceAndReturnHR(CCompRC::Debugging,
                                                       ID_FUSLOG_BINDING_LOCKED_UNLOCKED));
                }
                break;
                case APP_DOMAIN_LOCKED_CONTEXT:
                {
                    PathString displayName;

                    _ASSERTE(pAssemblyName != NULL);

                    IF_FAIL_GO(format.
                               LoadResourceAndReturnHR(CCompRC::Debugging,
                                                       GetLockedContextEntry(fInspectionOnly)));

                    pAssemblyName->GetDisplayName(displayName,
                                                  AssemblyName::INCLUDE_VERSION |
                                                  AssemblyName::INCLUDE_ARCHITECTURE);

                    info.Printf(format.GetUnicode(), displayName.GetUnicode());
                }
                break;
                default:
                    _ASSERTE(0);
                    IF_FAIL_GO(E_INVALIDARG);
                    break;
                }

                IF_FAIL_GO(pBindingLog->Log(info));
            }

        Exit:
            return hr;
        }

        HRESULT LogBindBehavior(ApplicationContext *pApplicationContext,
                                DWORD               dwBindBehavior)
        {
            HRESULT hr = S_OK;
            BindingLog *pBindingLog = pApplicationContext->GetBindingLog();

            if (pBindingLog->CanLog())
            {
                PathString bindBehavior;
                UINT uiBindBehavior = 0;

                switch (dwBindBehavior)
                {
                case BIND_BEHAVIOR_STATIC:
                    uiBindBehavior = ID_FUSLOG_BINDING_BEHAVIOR_STATIC;
                    break;
                case BIND_BEHAVIOR_ORDER_INDEPENDENT:
                    uiBindBehavior = ID_FUSLOG_BINDING_BEHAVIOR_ORDER_INDEPENDENT;
                    break;
                case BIND_BEHAVIOR_BEST_MATCH:
                    uiBindBehavior = ID_FUSLOG_BINDING_BEHAVIOR_BEST_MATCH;
                    break;
                default:
                    _ASSERTE(0);
                    IF_FAIL_GO(E_INVALIDARG);
                    break;
                }

                IF_FAIL_GO(bindBehavior.LoadResourceAndReturnHR(CCompRC::Debugging, uiBindBehavior));
                IF_FAIL_GO(pBindingLog->Log(bindBehavior.GetUnicode()));
            }

        Exit:
            return hr;
        }

        HRESULT LogAssemblyNameWhereRef(ApplicationContext *pApplicationContext,
                                        Assembly           *pAssembly)
        {
            HRESULT hr = S_OK;
            BindingLog *pBindingLog = pApplicationContext->GetBindingLog();

            if (pBindingLog->CanLog())
            {
                PathString info;

                IF_FAIL_GO(info.
                           LoadResourceAndReturnHR(CCompRC::Debugging, ID_FUSLOG_BINDING_LOG_WHERE_REF_NAME));
                IF_FAIL_GO(pBindingLog->LogAssemblyName(info.GetUnicode(),
                                                        pAssembly->GetAssemblyName()));
            }
            
        Exit:
            return hr;
        }

        HRESULT LogConfigurationError(ApplicationContext *pApplicationContext,
                                      AssemblyName       *pCulturedManifestName,
                                      AssemblyName       *pLocalPathAssemblyName)
        {
            HRESULT hr = S_OK;
            BindingLog *pBindingLog = pApplicationContext->GetBindingLog();

            if (pBindingLog->CanLog())
            {
                PathString tmp;
                PathString culturedManifestDisplayName;
                PathString localPathDisplayName;
                PathString info;

                IF_FAIL_GO(tmp.
                           LoadResourceAndReturnHR(CCompRC::Debugging, ID_FUSLOG_BINDING_LOG_ERRONOUS_MANIFEST_ENTRY));

                pCulturedManifestName->GetDisplayName(culturedManifestDisplayName,
                                                      AssemblyName::INCLUDE_VERSION |
                                                      AssemblyName::INCLUDE_ARCHITECTURE);
                pLocalPathAssemblyName->GetDisplayName(localPathDisplayName,
                                                       AssemblyName::INCLUDE_VERSION |
                                                       AssemblyName::INCLUDE_ARCHITECTURE);
                
                info.Printf(tmp.GetUnicode(),
                            culturedManifestDisplayName.GetUnicode(), 
                            localPathDisplayName.GetUnicode());
                IF_FAIL_GO(pBindingLog->Log(info.GetUnicode()));
            }

        Exit:
            return hr;
        }

        HRESULT LogPathAttempt(ApplicationContext *pApplicationContext,
                               PathString         &assemblyPath)
        {
            HRESULT hr = S_OK;
            BindingLog *pBindingLog = pApplicationContext->GetBindingLog();

            if (pBindingLog->CanLog())
            {
                PathString tmp;
                PathString info;

                IF_FAIL_GO(tmp.LoadResourceAndReturnHR(CCompRC::Debugging,
                                                       ID_FUSLOG_BINDING_LOG_PATH_ATTEMPT));
                info.Printf(tmp.GetUnicode(), assemblyPath.GetUnicode());

                IF_FAIL_GO(pBindingLog->Log(info));
            }

        Exit:
            return hr;
        }
#endif // FEATURE_VERSIONING_LOG

#ifndef CROSSGEN_COMPILE
        HRESULT CreateImageAssembly(IMDInternalImport       *pIMetaDataAssemblyImport,
                                    PEKIND                   PeKind,
                                    PEImage                 *pPEImage,
                                    PEImage                 *pNativePEImage,
                                    BOOL                     fInspectionOnly,
                                    BindResult              *pBindResult)
        {
            HRESULT hr = S_OK;
            ReleaseHolder<Assembly> pAssembly;
            PathString asesmblyPath;

            SAFE_NEW(pAssembly, Assembly);
            IF_FAIL_GO(pAssembly->Init(pIMetaDataAssemblyImport,
                                       PeKind,
                                       pPEImage,
                                       pNativePEImage,
                                       asesmblyPath,
                                       fInspectionOnly,
                                       FALSE /* fIsInGAC */));
            
            pBindResult->SetResult(pAssembly);
            pBindResult->SetIsFirstRequest(TRUE);

        Exit:
            return hr;
        }
#endif // !CROSSGEN_COMPILE
    };

    /* static */
    HRESULT AssemblyBinder::Startup()
    {
        HRESULT hr = S_OK;
 
       if (!BINDER_SPACE::fAssemblyBinderInitialized)
        {
            g_BinderVariables = new Variables();
            IF_FAIL_GO(g_BinderVariables->Init());

            // Setup Debug log
            BINDER_LOG_STARTUP();

            // We're done
            BINDER_SPACE::fAssemblyBinderInitialized = TRUE;
        }

    Exit:
        return hr;
    }


    HRESULT AssemblyBinder::TranslatePEToArchitectureType(DWORD  *pdwPAFlags, PEKIND *PeKind)
    {
        HRESULT hr = S_OK;
        BINDER_LOG_ENTER(W("TranslatePEToArchitectureType"))

        _ASSERTE(pdwPAFlags != NULL);
        _ASSERTE(PeKind != NULL);

        CorPEKind CLRPeKind = (CorPEKind) pdwPAFlags[0];
        DWORD dwImageType = pdwPAFlags[1];

        *PeKind = peNone;

        if(CLRPeKind == peNot) 
        {
            // Not a PE. Shouldn't ever get here.
            BINDER_LOG(W("Not a PE!"));
            IF_FAIL_GO(HRESULT_FROM_WIN32(ERROR_BAD_FORMAT));
        }
        else 
        {
            if ((CLRPeKind & peILonly) && !(CLRPeKind & pe32Plus) &&
                !(CLRPeKind & pe32BitRequired) && dwImageType == IMAGE_FILE_MACHINE_I386) 
            {
                // Processor-agnostic (MSIL)
                BINDER_LOG(W("Processor-agnostic (MSIL)"));
                *PeKind = peMSIL;
            }
            else if (CLRPeKind & pe32Plus) 
            {
                // 64-bit
                if (CLRPeKind & pe32BitRequired) 
                {
                    // Invalid
                    BINDER_LOG(W("CLRPeKind & pe32BitRequired is true"));
                    IF_FAIL_GO(HRESULT_FROM_WIN32(ERROR_BAD_FORMAT));
                }

                // Regardless of whether ILONLY is set or not, the architecture
                // is the machine type.
                if(dwImageType == IMAGE_FILE_MACHINE_ARM64) 
                    *PeKind = peARM64;
                else if (dwImageType == IMAGE_FILE_MACHINE_AMD64) 
                    *PeKind = peAMD64;
                else 
                {
                    // We don't support other architectures
                    BINDER_LOG(W("Unknown architecture"));
                    IF_FAIL_GO(HRESULT_FROM_WIN32(ERROR_BAD_FORMAT));
                }
            }
            else
            {
                // 32-bit, non-agnostic
                if(dwImageType == IMAGE_FILE_MACHINE_I386) 
                    *PeKind = peI386;
                else if(dwImageType == IMAGE_FILE_MACHINE_ARMNT) 
                    *PeKind = peARM;
                else 
                {
                    // Not supported
                    BINDER_LOG(W("32-bit, non-agnostic"));
                    IF_FAIL_GO(HRESULT_FROM_WIN32(ERROR_BAD_FORMAT));
                }
            }
        }

    Exit:
        BINDER_LOG_LEAVE_HR(W("TranslatePEToArchitectureType"), hr);
        return hr;
    }
        
    // See code:BINDER_SPACE::AssemblyBinder::GetAssembly for info on fNgenExplicitBind
    // and fExplicitBindToNativeImage, and see code:CEECompileInfo::LoadAssemblyByPath
    // for an example of how they're used.
    HRESULT AssemblyBinder::BindAssembly(/* in */  ApplicationContext  *pApplicationContext,
                                         /* in */  AssemblyName        *pAssemblyName,
                                         /* in */  LPCWSTR              szCodeBase,
                                         /* in */  PEAssembly          *pParentAssembly,
                                         /* in */  BOOL                 fNgenExplicitBind,
                                         /* in */  BOOL                 fExplicitBindToNativeImage,
                                         /* in */  bool                 excludeAppPaths,
                                         /* out */ Assembly           **ppAssembly)
    {
        HRESULT hr = S_OK;
        LONG kContextVersion = 0;
        BindResult bindResult;
        
        BINDER_LOG_ENTER(W("AssemblyBinder::BindAssembly"));

#ifndef CROSSGEN_COMPILE
    Retry:
       {
            // Lock the binding application context
            CRITSEC_Holder contextLock(pApplicationContext->GetCriticalSectionCookie());
#endif

            if (szCodeBase == NULL)
            {
#ifdef FEATURE_VERSIONING_LOG
                // Log bind
                IF_FAIL_GO(BindingLog::CreateInContext(pApplicationContext,
                                                       pAssemblyName,
                                                       pParentAssembly));
#endif // FEATURE_VERSIONING_LOG


                hr = BindByName(pApplicationContext,
                                      pAssemblyName,
                                      BIND_CACHE_FAILURES,
                                      excludeAppPaths,
                                      &bindResult);
                IF_FAIL_GO(hr);
            }
            else
            {
                PathString assemblyPath(szCodeBase);

#ifdef FEATURE_VERSIONING_LOG
                // Log bind
                IF_FAIL_GO(BindingLog::CreateInContext(pApplicationContext,
                                                       assemblyPath,
                                                       pParentAssembly));
#endif // FEATURE_VERSIONING_LOG

                // Convert URL to full path and block HTTP downloads
                IF_FAIL_GO(URLToFullPath(assemblyPath));
                BOOL fDoNgenExplicitBind = fNgenExplicitBind;
                
                // Only use explicit ngen binding in the new coreclr path-based binding model
                if(!pApplicationContext->IsTpaListProvided())
                {
                    fDoNgenExplicitBind = FALSE;
                }
                
                IF_FAIL_GO(BindWhereRef(pApplicationContext,
                                        assemblyPath,
                                        fDoNgenExplicitBind,
                                        fExplicitBindToNativeImage,
                                        excludeAppPaths,
                                        &bindResult));
            }

            // Remember the post-bind version
            kContextVersion = pApplicationContext->GetVersion();

        Exit:
#ifdef FEATURE_VERSIONING_LOG
            hr = LogBindResult(pApplicationContext, hr, &bindResult);
#else // FEATURE_VERSIONING_LOG
            ;
#endif // FEATURE_VERSIONING_LOG

#ifndef CROSSGEN_COMPILE
        } // lock(pApplicationContext)
#endif

        if (bindResult.HaveResult())
        {

#ifndef CROSSGEN_COMPILE
            BindResult hostBindResult;

            hr = RegisterAndGetHostChosen(pApplicationContext,
                                          kContextVersion,
                                          &bindResult,
                                          &hostBindResult);
            
            if (hr == S_FALSE)
            {
                // Another bind interfered. We need to retry the entire bind.
                // This by design loops as long as needed because by construction we eventually
                // will succeed or fail the bind.
                bindResult.Reset();
                goto Retry;
            }
            else if (hr == S_OK)
            {
                *ppAssembly = hostBindResult.GetAsAssembly(TRUE /* fAddRef */);
            }
#else // CROSSGEN_COMPILE

            *ppAssembly = bindResult.GetAsAssembly(TRUE /* fAddRef */);

#endif // CROSSGEN_COMPILE
        }

        BINDER_LOG_LEAVE_HR(W("AssemblyBinder::BindAssembly"), hr);
        return hr;
    }

    /* static */
    HRESULT AssemblyBinder::BindToSystem(SString   &systemDirectory,
                                         Assembly **ppSystemAssembly,
                                         bool fBindToNativeImage)
    {
        _ASSERTE(BINDER_SPACE::fAssemblyBinderInitialized == TRUE);

        HRESULT hr = S_OK;
        BINDER_LOG_ENTER(W("AssemblyBinder:BindToSystem"));

        _ASSERTE(ppSystemAssembly != NULL);

        StackSString sCoreLibDir(systemDirectory);
        ReleaseHolder<Assembly> pSystemAssembly;

        if(!sCoreLibDir.EndsWith(DIRECTORY_SEPARATOR_CHAR_W))
        {
            sCoreLibDir.Append(DIRECTORY_SEPARATOR_CHAR_W);
        }

        StackSString sCoreLib;

        // At run-time, System.Private.CoreLib.dll is expected to be the NI image.
        sCoreLib = sCoreLibDir;
        sCoreLib.Append(CoreLibName_IL_W);
        BOOL fExplicitBindToNativeImage = (fBindToNativeImage == true)? TRUE:FALSE;
#if defined(FEATURE_PAL) && !defined(_TARGET_AMD64_)      
        // Non-Amd64 platforms on non-Windows do not support generating the NI image
        // as CoreLib.dll. For those, we will bind as IL.
        fExplicitBindToNativeImage = FALSE;
#endif // defined(FEATURE_PAL) && !defined(_TARGET_AMD64_)
        IF_FAIL_GO(AssemblyBinder::GetAssembly(sCoreLib,
                                                   FALSE /* fInspectionOnly */,
                                                   TRUE /* fIsInGAC */,
                                                   fExplicitBindToNativeImage,
                                                   &pSystemAssembly));
        
        *ppSystemAssembly = pSystemAssembly.Extract();

    Exit:
        BINDER_LOG_LEAVE_HR(W("AssemblyBinder::BindToSystem"), hr);
        return hr;
    }


    /* static */
    HRESULT AssemblyBinder::BindToSystemSatellite(SString   &systemDirectory,
                                                  SString   &simpleName,
                                                  SString   &cultureName,
                                                  Assembly **ppSystemAssembly)
    {
        _ASSERTE(BINDER_SPACE::fAssemblyBinderInitialized == TRUE);

        HRESULT hr = S_OK;
        BINDER_LOG_ENTER(W("AssemblyBinder:BindToSystemSatellite"));

        _ASSERTE(ppSystemAssembly != NULL);

        StackSString sMscorlibSatellite(systemDirectory);
        ReleaseHolder<Assembly> pSystemAssembly;

        // append culture name
        if (!cultureName.IsEmpty())
        {
            CombinePath(sMscorlibSatellite, cultureName, sMscorlibSatellite);
        }

        // append satellite assembly's simple name
        CombinePath(sMscorlibSatellite, simpleName, sMscorlibSatellite);

        // append extension
        sMscorlibSatellite.Append(W(".dll"));

        IF_FAIL_GO(AssemblyBinder::GetAssembly(sMscorlibSatellite,
                                               FALSE /* fInspectionOnly */,
                                               TRUE /* fIsInGAC */,
                                               FALSE /* fExplicitBindToNativeImage */,
                                               &pSystemAssembly));

        *ppSystemAssembly = pSystemAssembly.Extract();

    Exit:
        BINDER_LOG_LEAVE_HR(W("AssemblyBinder::BindToSystemSatellite"), hr);
        return hr;
    }

    /* static */
    HRESULT AssemblyBinder::GetAssemblyFromImage(PEImage   *pPEImage,
                                                 PEImage   *pNativePEImage,
                                                 Assembly **ppAssembly)
    {
        _ASSERTE(BINDER_SPACE::fAssemblyBinderInitialized == TRUE);

        HRESULT hr = S_OK;
        BINDER_LOG_ENTER(W("AssemblyBinder::GetAssemblyFromImage"));
        
        _ASSERTE(pPEImage != NULL);
        _ASSERTE(ppAssembly != NULL);

        ReleaseHolder<Assembly> pAssembly;
        ReleaseHolder<IMDInternalImport> pIMetaDataAssemblyImport;
        DWORD dwPAFlags[2];
        PEKIND PeKind = peNone;

        SAFE_NEW(pAssembly, Assembly);
        if(pNativePEImage)
        {
            IF_FAIL_GO(BinderAcquireImport(pNativePEImage, &pIMetaDataAssemblyImport, dwPAFlags, TRUE));
        }
        else
        {
            IF_FAIL_GO(BinderAcquireImport(pPEImage, &pIMetaDataAssemblyImport, dwPAFlags, FALSE));
        }
        IF_FAIL_GO(TranslatePEToArchitectureType(dwPAFlags, &PeKind));
        IF_FAIL_GO(pAssembly->Init(pIMetaDataAssemblyImport,
                                   PeKind,
                                   pPEImage,
                                   pNativePEImage,
                                   g_BinderVariables->emptyString,
                                   FALSE /* fInspectionOnly */,
                                   FALSE /* fIsInGAC */));

        // TODO: Is this correct?
        pAssembly->SetIsByteArray(TRUE);

        *ppAssembly = pAssembly.Extract();

    Exit:
        BINDER_LOG_LEAVE_HR(W("AssemblyBinder::GetAssemblyFromImage"), hr);
        return hr;
    }

#ifndef CROSSGEN_COMPILE
    /* static */
    HRESULT AssemblyBinder::PreBindByteArray(ApplicationContext *pApplicationContext,
                                             PEImage            *pPEImage,
                                             BOOL                fInspectionOnly)
    {
        _ASSERTE(BINDER_SPACE::fAssemblyBinderInitialized == TRUE);

        HRESULT hr = S_OK;
        BINDER_LOG_ENTER(W("AssemblyBinder::PreBindByteArray"));

        ReleaseHolder<AssemblyName> pAssemblyName;
        BOOL fNeedHostRegister = FALSE;
        LONG kContextVersion = 0;
        ReleaseHolder<IMDInternalImport> pIMetaDataAssemblyImport;
        DWORD dwPAFlags[2];
        PEKIND PeKind = peNone;
        BindResult bindResult;

        // Prepare binding data
        SAFE_NEW(pAssemblyName, AssemblyName);
        IF_FAIL_GO(BinderAcquireImport(pPEImage, &pIMetaDataAssemblyImport, dwPAFlags, FALSE));
        IF_FAIL_GO(TranslatePEToArchitectureType(dwPAFlags, &PeKind));
        IF_FAIL_GO(pAssemblyName->Init(pIMetaDataAssemblyImport, PeKind));
        pAssemblyName->SetIsDefinition(TRUE);

        // Validate architecture
        if (!fInspectionOnly && !Assembly::IsValidArchitecture(pAssemblyName->GetArchitecture()))
        {
            IF_FAIL_GO(HRESULT_FROM_WIN32(ERROR_BAD_FORMAT));
        }

        // Attempt the actual bind (eventually more than once)
    Retry:
        {
            // Lock the application context
            CRITSEC_Holder contextLock(pApplicationContext->GetCriticalSectionCookie());

            // Attempt uncached bind and register stream if possible
            if (!fInspectionOnly &&
                 ((hr = BindByName(pApplicationContext,
                                   pAssemblyName,
                                   BIND_CACHE_FAILURES | BIND_CACHE_RERUN_BIND,
                                   false, // excludeAppPaths
                                   &bindResult)) == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND))
                )
            {
                if ((fInspectionOnly && !bindResult.HaveResult()) ||
                    (bindResult.GetRetargetedAssemblyName() == NULL))
                {
                    IF_FAIL_GO(CreateImageAssembly(pIMetaDataAssemblyImport,
                                                   PeKind,
                                                   pPEImage,
                                                   NULL,
                                                   fInspectionOnly,
                                                   &bindResult));
                    if (fInspectionOnly)
                    {
                        // For inspection-only, we do not share the map.
                        IF_FAIL_GO(Register(pApplicationContext, fInspectionOnly, &bindResult));
                    }
                    else
                    {
                        // Remember the post-bind version of the context
                        kContextVersion = pApplicationContext->GetVersion();
                        fNeedHostRegister = TRUE;
                    }
                }
            }
        } // lock(pApplicationContext)

        if (fNeedHostRegister)
        {
            BindResult hostBindResult;

            // This has to happen outside the binder lock as it can cause new binds
            IF_FAIL_GO(RegisterAndGetHostChosen(pApplicationContext,
                                                kContextVersion,
                                                &bindResult,
                                                &hostBindResult));

            if (hr == S_FALSE)
            {
                // Another bind interfered. We need to retry entire bind.
                // This by design loops as long as needed because by construction we eventually
                // will succeed or fail the bind.
                bindResult.Reset();
                goto Retry;
            }
        }
    
        // Ignore bind errors here because we need to attempt by-name load to get log entry.
        GO_WITH_HRESULT(S_OK);

    Exit:
        BINDER_LOG_LEAVE_HR(W("AssemblyBinder::PreBindByteArray"), hr);
        return hr;
    }

#endif //CROSSGEN_COMPILE

    /* static */
    HRESULT AssemblyBinder::BindByName(ApplicationContext *pApplicationContext,
                                       AssemblyName       *pAssemblyName,
                                       DWORD               dwBindFlags,
                                       bool                excludeAppPaths,
                                       BindResult         *pBindResult)
    {
        HRESULT hr = S_OK;
        BINDER_LOG_ENTER(W("AssemblyBinder::BindByName"));
        PathString assemblyDisplayName;

        // Look for already cached binding failure (ignore PA, every PA will lock the context)
        pAssemblyName->GetDisplayName(assemblyDisplayName,
                                      AssemblyName::INCLUDE_VERSION);

        hr = pApplicationContext->GetFailureCache()->Lookup(assemblyDisplayName);
        if (FAILED(hr))
        {
            if ((hr == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND)) && RerunBind(dwBindFlags))
            {
                // Ignore pre-existing transient bind error (re-bind will succeed)
                pApplicationContext->GetFailureCache()->Remove(assemblyDisplayName);
            }

            goto LogExit;
        }
        else if (hr == S_FALSE)
        {
            // workaround: Special case for byte arrays. Rerun the bind to create binding log.
            pAssemblyName->SetIsDefinition(TRUE);
            hr = S_OK;
        }

        if (!Assembly::IsValidArchitecture(pAssemblyName->GetArchitecture()))
        {
            // Assembly reference contains wrong architecture
            IF_FAIL_GO(FUSION_E_INVALID_NAME);
        }

       IF_FAIL_GO(BindLocked(pApplicationContext,
                              pAssemblyName,
                              dwBindFlags,
                              excludeAppPaths,
                              pBindResult));

        if (!pBindResult->HaveResult())
        {
            // Behavior rules are clueless now
            IF_FAIL_GO(HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND));
        }

    Exit:
        if (FAILED(hr) && CacheBindFailures(dwBindFlags))
        {
            if (RerunBind(dwBindFlags))
            {
                if (hr != HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND))
                {
                    // Cache non-transient bind error for byte-array
                    hr = S_FALSE;
                }
                else
                {
                    // Ignore transient bind error (re-bind will succeed)
                    goto LogExit;
                }
            }
            hr = pApplicationContext->AddToFailureCache(assemblyDisplayName, hr);
        }
    LogExit:

        BINDER_LOG_LEAVE_HR(W("AssemblyBinder::BindByName"), hr);
        return hr;
    }

    /* static */
    // See code:BINDER_SPACE::AssemblyBinder::GetAssembly for info on fNgenExplicitBind
    // and fExplicitBindToNativeImage, and see code:CEECompileInfo::LoadAssemblyByPath
    // for an example of how they're used.
    HRESULT AssemblyBinder::BindWhereRef(ApplicationContext *pApplicationContext,
                                         PathString         &assemblyPath,
                                         BOOL                fNgenExplicitBind,
                                         BOOL                fExplicitBindToNativeImage,
                                         bool                excludeAppPaths,
                                         BindResult         *pBindResult)
    {
        HRESULT hr = S_OK;
        BINDER_LOG_ENTER(W("AssemblyBinder::BindWhereRef"));

        ReleaseHolder<Assembly> pAssembly;
        BindResult lockedBindResult;

        // Look for already cached binding failure
        hr = pApplicationContext->GetFailureCache()->Lookup(assemblyPath);
        if (FAILED(hr))
        {
            goto LogExit;
        }

        // If we return this assembly, then it is guaranteed to be not in GAC
        // Design decision. For now, keep the V2 model of Fusion being oblivious of the strong name.
        // Security team did not see any security concern with interpreting the version information.
        IF_FAIL_GO(GetAssembly(assemblyPath,
                               FALSE /* fInspectionOnly */,
                               FALSE /* fIsInGAC */,
                               
                               // Pass through caller's intent of whether to bind to the
                               // NI using an explicit path to the NI that was
                               // specified.  Generally only NGEN PDB generation has
                               // this TRUE.
                               fExplicitBindToNativeImage,
                               &pAssembly));
#ifdef FEATURE_VERSIONING_LOG
        IF_FAIL_GO(LogAssemblyNameWhereRef(pApplicationContext, pAssembly));
#endif // FEATURE_VERSIONING_LOG

        AssemblyName *pAssemblyName;
        pAssemblyName = pAssembly->GetAssemblyName();

        if (!fNgenExplicitBind)
        {
            IF_FAIL_GO(BindLockedOrService(pApplicationContext,
                                           pAssemblyName,
                                           excludeAppPaths,
                                           &lockedBindResult));
            if (lockedBindResult.HaveResult())
            {
                pBindResult->SetResult(&lockedBindResult);
                GO_WITH_HRESULT(S_OK);
            }
        }

        hr = S_OK;
        pAssembly->SetIsDynamicBind(TRUE);
        pBindResult->SetResult(pAssembly);

    Exit:

        if (FAILED(hr))
        {
            // Always cache binding failures
            hr = pApplicationContext->AddToFailureCache(assemblyPath, hr);
        }

    LogExit:

        BINDER_LOG_LEAVE_HR(W("AssemblyBinder::BindWhereRef"), hr);
        return hr;
    }

    /* static */
    HRESULT AssemblyBinder::BindLocked(ApplicationContext *pApplicationContext,
                                       AssemblyName       *pAssemblyName,
                                       DWORD               dwBindFlags,
                                       bool                excludeAppPaths,
                                       BindResult         *pBindResult)
    {
        HRESULT hr = S_OK;
        BINDER_LOG_ENTER(W("AssemblyBinder::BindLocked"));
        
        BOOL fIgnoreDynamicBinds = IgnoreDynamicBinds(dwBindFlags);
        
#ifndef CROSSGEN_COMPILE
        ContextEntry *pContextEntry = NULL;
        IF_FAIL_GO(FindInExecutionContext(pApplicationContext, pAssemblyName, &pContextEntry));
        if (pContextEntry != NULL)
        {
            if (fIgnoreDynamicBinds && pContextEntry->GetIsDynamicBind())
            {
                // Dynamic binds need to be always considered a failure for binding closures
                IF_FAIL_GO(FUSION_E_APP_DOMAIN_LOCKED);
            }
#if !defined(DACCESS_COMPILE) && !defined(CROSSGEN_COMPILE)
            else if (IgnoreRefDefMatch(dwBindFlags))
            {
                // Skip RefDef matching if we have been asked to.
            }
#endif // !defined(DACCESS_COMPILE) && !defined(CROSSGEN_COMPILE)
            else
            {
                // Can't give higher serciving than already bound
                IF_FAIL_GO(IsValidAssemblyVersion(pAssemblyName, pContextEntry->GetAssemblyName(), pApplicationContext));
            }
            
            pBindResult->SetResult(pContextEntry);
        }
        else
#endif // !CROSSGEN_COMPILE
        if (pApplicationContext->IsTpaListProvided())
        {
            IF_FAIL_GO(BindByTpaList(pApplicationContext,
                                     pAssemblyName,
                                     FALSE /*fInspectionOnly*/,
                                     excludeAppPaths,
                                     pBindResult));
            if (pBindResult->HaveResult())
            {
                hr = IsValidAssemblyVersion(pAssemblyName, pBindResult->GetAssemblyName(), pApplicationContext);
                if (FAILED(hr))
                {
                    pBindResult->SetNoResult();                    
                }
            }
        }
    Exit:
        BINDER_LOG_LEAVE_HR(W("AssemblyBinder::BindLocked"), hr);
        return hr;
    }

    /* static */
    HRESULT AssemblyBinder::BindLockedOrService(ApplicationContext *pApplicationContext,
                                                AssemblyName       *pAssemblyName,
                                                bool                excludeAppPaths,
                                                BindResult         *pBindResult)
    {
        HRESULT hr = S_OK;
        BINDER_LOG_ENTER(W("AssemblyBinder::BindLockedOrService"));

        BindResult lockedBindResult;

        IF_FAIL_GO(BindLocked(pApplicationContext,
                              pAssemblyName,
                              0 /*  Do not IgnoreDynamicBinds */,
                              excludeAppPaths,
                              &lockedBindResult));

        if (lockedBindResult.HaveResult())
        {
            // Locked Bind succeeded
            pBindResult->SetResult(&lockedBindResult);
        }
        else
        {
            pBindResult->SetNoResult();
        }

    Exit:
        BINDER_LOG_LEAVE_HR(W("AssemblyBinder::BindLockedOrService"), hr);
        return hr;
    }

#ifndef CROSSGEN_COMPILE
    /* static */
    HRESULT AssemblyBinder::FindInExecutionContext(ApplicationContext  *pApplicationContext,
                                                   AssemblyName        *pAssemblyName,
                                                   ContextEntry       **ppContextEntry)
    {
        HRESULT hr = S_OK;
        BINDER_LOG_ENTER(W("AssemblyBinder::FindInExecutionContext"));

        _ASSERTE(pApplicationContext != NULL);
        _ASSERTE(pAssemblyName != NULL);
        _ASSERTE(ppContextEntry != NULL);

        ExecutionContext *pExecutionContext = pApplicationContext->GetExecutionContext();
        ContextEntry *pContextEntry = pExecutionContext->Lookup(pAssemblyName);

        if (pContextEntry != NULL)
        {
            AssemblyName *pContextName = pContextEntry->GetAssemblyName();

#ifdef FEATURE_VERSIONING_LOG
            // First-time requests are considered unlocked, everything else is locked
            DWORD dwLockedReason = (pContextEntry->GetIsFirstRequest() ?
                                    APP_DOMAIN_LOCKED_UNLOCKED : APP_DOMAIN_LOCKED_CONTEXT);

            IF_FAIL_GO(LogAppDomainLocked(pApplicationContext, dwLockedReason, pContextName));
            pContextEntry->SetIsFirstRequest(FALSE);
#endif // FEATURE_VERSIONING_LOG

            if (pAssemblyName->GetIsDefinition() &&
                (pContextName->GetArchitecture() != pAssemblyName->GetArchitecture()))
            {
                IF_FAIL_GO(FUSION_E_APP_DOMAIN_LOCKED);
            }
        }

        *ppContextEntry = pContextEntry;

    Exit:
        BINDER_LOG_LEAVE_HR(W("AssemblyBinder::FindInExecutionContext"), hr);
        return hr;
    }

#endif //CROSSGEN_COMPILE

    //
    // Tests whether a candidate assembly's name matches the requested.
    // This does not do a version check.  The binder applies version policy
    // further up the stack once it gets a successful bind.
    //
    BOOL TestCandidateRefMatchesDef(ApplicationContext *pApplicationContext,
                                    AssemblyName *pRequestedAssemblyName,
                                    AssemblyName *pBoundAssemblyName,
                                    BOOL tpaListAssembly)
    {
        DWORD dwIncludeFlags = AssemblyName::INCLUDE_DEFAULT;

        if (!tpaListAssembly)
        {
            SString &culture = pRequestedAssemblyName->GetCulture();
            if (culture.IsEmpty() || culture.EqualsCaseInsensitive(g_BinderVariables->cultureNeutral))
            {
                dwIncludeFlags |= AssemblyName::EXCLUDE_CULTURE;
            }
        }
        
        if (pRequestedAssemblyName->GetArchitecture() != peNone)
        {
            dwIncludeFlags |= AssemblyName::INCLUDE_ARCHITECTURE;
        }

        BINDER_LOG_ASSEMBLY_NAME(W("pBoundAssemblyName"), pBoundAssemblyName);

        return pBoundAssemblyName->Equals(pRequestedAssemblyName, dwIncludeFlags);
    }
    
    HRESULT BindSatelliteResourceByResourceRoots(ApplicationContext  *pApplicationContext,
                                          StringArrayList     *pResourceRoots,
                                          AssemblyName        *pRequestedAssemblyName,
                                          BOOL                 fInspectionOnly,
                                          BindResult          *pBindResult)
    {
        HRESULT hr = S_OK;

        SString &simpleNameRef = pRequestedAssemblyName->GetSimpleName();
        SString &cultureRef = pRequestedAssemblyName->GetCulture();
        
        _ASSERTE(!cultureRef.IsEmpty() && !cultureRef.EqualsCaseInsensitive(g_BinderVariables->cultureNeutral));
        
        for (UINT i = 0; i < pResourceRoots->GetCount(); i++)
        {
            ReleaseHolder<Assembly> pAssembly;
            SString &wszBindingPath = (*pResourceRoots)[i];
            SString fileName(wszBindingPath);

            CombinePath(fileName, cultureRef, fileName);
            CombinePath(fileName, simpleNameRef, fileName);
            fileName.Append(W(".dll"));

            hr = AssemblyBinder::GetAssembly(fileName,
                                             fInspectionOnly,
                                             FALSE /* fIsInGAC */,
                                             FALSE /* fExplicitBindToNativeImage */,
                                             &pAssembly);

            // Missing files are okay and expected when probing
            if (hr == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND))
            {
                continue;
            }
            
            IF_FAIL_GO(hr);

            AssemblyName *pBoundAssemblyName = pAssembly->GetAssemblyName();
            if (TestCandidateRefMatchesDef(pApplicationContext, pRequestedAssemblyName, pBoundAssemblyName, false /*tpaListAssembly*/))
            {
                pBindResult->SetResult(pAssembly);
                GO_WITH_HRESULT(S_OK);
            }

#ifdef FEATURE_VERSIONING_LOG
            // Log the candidates we throw out for diagnostics
            IF_FAIL_GO(LogConfigurationError(pApplicationContext,
                                             pRequestedAssemblyName,
                                             pBoundAssemblyName));
#endif // FEATURE_VERSIONING_LOG
            
            IF_FAIL_GO(FUSION_E_REF_DEF_MISMATCH);
        }

        // Up-stack expects S_OK when we don't find any candidate assemblies and no fatal error occurred (ie, no S_FALSE)
        hr = S_OK;
    Exit:
        return hr;
    }
    
    /*
     * BindByTpaList is the entry-point for the custom binding algorithm on the Phone.
     * Platform assemblies are specified as a list of files.  This list is the only set of
     * assemblies that we will load as platform.  They can be specified as IL or NIs.
     *
     * Resources for platform assemblies are located by probing starting at the Platform Resource Roots,
     * a set of folders configured by the host.
     *
     * If a requested assembly identity cannot be found in the TPA list or the resource roots,
     * it is considered an application assembly.  We probe for application assemblies in one of two
     * sets of paths: the AppNiPaths, a list of paths containing native images, and the AppPaths, a
     * list of paths containing IL files and satellite resource folders.
     *
     */
    /* static */
    HRESULT AssemblyBinder::BindByTpaList(ApplicationContext  *pApplicationContext,
                                          AssemblyName        *pRequestedAssemblyName,
                                          BOOL                 fInspectionOnly,
                                          bool                 excludeAppPaths,
                                          BindResult          *pBindResult)
    {
        HRESULT hr = S_OK;
        BINDER_LOG_ENTER(W("AssemblyBinder::BindByTpaList"));

        SString &culture = pRequestedAssemblyName->GetCulture();
        bool fPartialMatchOnTpa = false;
        
        if (!culture.IsEmpty() && !culture.EqualsCaseInsensitive(g_BinderVariables->cultureNeutral))
        {
            //
            // Satellite resource probing strategy is to look under each of the Platform Resource Roots
            // followed by App Paths.
            //
            
            hr = BindSatelliteResourceByResourceRoots(pApplicationContext, 
                                                            pApplicationContext->GetPlatformResourceRoots(), 
                                                            pRequestedAssemblyName, 
                                                            fInspectionOnly, 
                                                            pBindResult);
            
            // We found a platform resource file with matching file name, but whose ref-def didn't match.  Fall
            // back to application resource lookup to handle case where a user creates resources with the same
            // names as platform ones.
            if (hr != FUSION_E_CONFIGURATION_ERROR)
            {
                IF_FAIL_GO(hr);
            }
            
            if (!pBindResult->HaveResult())
            {
                IF_FAIL_GO(BindSatelliteResourceByResourceRoots(pApplicationContext, 
                                                                pApplicationContext->GetAppPaths(), 
                                                                pRequestedAssemblyName, 
                                                                fInspectionOnly, 
                                                                pBindResult));
            }
        }
        else
        {
            // Is assembly on TPA list?
            SString &simpleName = pRequestedAssemblyName->GetSimpleName();
            SimpleNameToFileNameMap * tpaMap = pApplicationContext->GetTpaList();
            const SimpleNameToFileNameMapEntry *pTpaEntry = tpaMap->LookupPtr(simpleName.GetUnicode());
            ReleaseHolder<Assembly> pTPAAssembly;
            if (pTpaEntry != nullptr)
            {
                if (pTpaEntry->m_wszNIFileName != nullptr)
                {
                    SString fileName(pTpaEntry->m_wszNIFileName);

                    // A GetAssembly overload perhaps, or just another parameter to the existing method
                    hr = GetAssembly(fileName,
                                        fInspectionOnly,
                                        TRUE, /* fIsInGAC */
                                        TRUE /* fExplicitBindToNativeImage */,
                                        &pTPAAssembly
                                        );
                }
                else
                {
                    _ASSERTE(pTpaEntry->m_wszILFileName != nullptr);
                    SString fileName(pTpaEntry->m_wszILFileName);
                    
                    hr = GetAssembly(fileName,
                                        fInspectionOnly,
                                        TRUE, /* fIsInGAC */
                                        FALSE /* fExplicitBindToNativeImage */,
                                        &pTPAAssembly);
                }

                // On file not found, simply fall back to app path probing
                if (hr != HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND))
                {
                    // Any other error is fatal
                    IF_FAIL_GO(hr);
                    
                    if (TestCandidateRefMatchesDef(pApplicationContext, pRequestedAssemblyName, pTPAAssembly->GetAssemblyName(), true /*tpaListAssembly*/))
                    {
                        // We have found the requested assembly match on TPA with validation of the full-qualified name. Bind to it.
                        pBindResult->SetResult(pTPAAssembly);
                        GO_WITH_HRESULT(S_OK);
                    }
                    else
                    {
                        // We found the assembly on TPA but it didnt match the RequestedAssembly assembly-name. In this case, lets proceed to see if we find the requested
                        // assembly in the App paths.
                        fPartialMatchOnTpa = true;
                    }
                }
                
                // We either didn't find a candidate, or the ref-def failed.  Either way; fall back to app path probing.
            }

            bool fUseAppPathsBasedResolver = !excludeAppPaths;
            
#if !defined(DACCESS_COMPILE) && !defined(CROSSGEN_COMPILE)
            // If Host Assembly Resolver is specified, then we will use that as the override for the default resolution mechanism (that uses AppPath probing).
            if (fUseAppPathsBasedResolver && !RuntimeCanUseAppPathAssemblyResolver(pApplicationContext->GetAppDomainId()))
            {
                fUseAppPathsBasedResolver = false;
            }
#endif // !defined(DACCESS_COMPILE) && !defined(CROSSGEN_COMPILE)
             
            // This loop executes twice max.  First time through we probe AppNiPaths, the second time we probe AppPaths
            bool parseNiPaths = true;
            while (fUseAppPathsBasedResolver)
            {
                StringArrayList *pBindingPaths = parseNiPaths ? pApplicationContext->GetAppNiPaths() : pApplicationContext->GetAppPaths();
                
                // Loop through the binding paths looking for a matching assembly
                for (DWORD i = 0; i < pBindingPaths->GetCount(); i++)
                {
                    ReleaseHolder<Assembly> pAssembly;
                    LPCWSTR wszBindingPath = (*pBindingPaths)[i];
                    
                    SString &simpleName = pRequestedAssemblyName->GetSimpleName();

                    // Look for a matching dll first
                    hr = HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND);
                    
                    {
                        SString fileName(wszBindingPath);
                        CombinePath(fileName, simpleName, fileName);
                        if (parseNiPaths)
                        {
                            fileName.Append(W(".ni.dll"));
                            hr = GetAssembly(fileName,
                                            fInspectionOnly,
                                            FALSE, /* fIsInGAC */
                                            TRUE /* fExplicitBindToNativeImage */,
                                            &pAssembly);
                        }
                        else
                        {
                            if (FAILED(hr))
                            {
                                fileName.Append(W(".dll"));

                                hr = GetAssembly(fileName,
                                                fInspectionOnly,
                                                FALSE, /* fIsInGAC */
                                                FALSE /* fExplicitBindToNativeImage */,
                                                &pAssembly);
                            }
                        }
                    }

                    if (FAILED(hr))
                    {
                        SString fileName(wszBindingPath);
                        CombinePath(fileName, simpleName, fileName);

                        if (parseNiPaths)
                        {
                            fileName.Append(W(".ni.exe"));
                            hr = GetAssembly(fileName,
                                            fInspectionOnly,
                                            FALSE, /* fIsInGAC */
                                            TRUE /* fExplicitBindToNativeImage */,
                                            &pAssembly);
                        }
                        else
                        {
                            if (FAILED(hr))
                            {
                                fileName.Append(W(".exe"));

                                hr = GetAssembly(fileName,
                                                fInspectionOnly,
                                                FALSE, /* fIsInGAC */
                                                FALSE /* fExplicitBindToNativeImage */,
                                                &pAssembly);
                            }
                        }
                    }
                    
                    // Since we're probing, file not founds are ok and we should just try another
                    // probing path
                    if (hr == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND))
                    {
                        continue;
                    }
                    IF_FAIL_GO(hr);

                    // We found a candidate.  
                    //
                    // Below this point, we either establish that the ref-def matches, or
                    // we fail the bind.

                    // Compare requested AssemblyName with that from the candidate assembly 
                    if (TestCandidateRefMatchesDef(pApplicationContext, pRequestedAssemblyName, pAssembly->GetAssemblyName(), false /*tpaListAssembly*/))
                    {
                        // At this point, we have found an assembly with the expected name in the App paths. If this was also found on TPA,
                        // make sure that the app assembly has the same fullname (excluding version) as the TPA version. If it does, then
                        // we should bind to the TPA assembly. If it does not, then bind to the app assembly since it has a different fullname than the 
                        // TPA assembly.
                        if (fPartialMatchOnTpa)
                        {
                            if (TestCandidateRefMatchesDef(pApplicationContext, pAssembly->GetAssemblyName(), pTPAAssembly->GetAssemblyName(), true /*tpaListAssembly*/))
                            {
                                // Fullname (SimpleName+Culture+PKT) matched for TPA and app assembly - so bind to TPA instance.
                                pBindResult->SetResult(pTPAAssembly);
                                GO_WITH_HRESULT(S_OK);
                            }
                            else
                            {
                                // Fullname (SimpleName+Culture+PKT) did not match for TPA and app assembly - so bind to app instance.
                                pBindResult->SetResult(pAssembly);
                                GO_WITH_HRESULT(S_OK);
                            }
                        }
                        else
                        {
                            // We didnt see this assembly on TPA - so simply bind to the app instance.
                            pBindResult->SetResult(pAssembly);
                            GO_WITH_HRESULT(S_OK);
                        }
                    }

        #ifdef FEATURE_VERSIONING_LOG
                    // Log the candidates we throw out for diagnostics
                    IF_FAIL_GO(LogConfigurationError(pApplicationContext,
                                                     pRequestedAssemblyName,
                                                     pAssembly->GetAssemblyName()));
        #endif // FEATURE_VERSIONING_LOG
        
                    IF_FAIL_GO(FUSION_E_REF_DEF_MISMATCH);

                }
                
                if (!parseNiPaths)
                {
                    break;
                }
                
                parseNiPaths = false;
            }
        }
        
        // Couldn't find a matching assembly in any of the probing paths
        // Return S_OK here.  BindByName will interpret a lack of BindResult
        // as a failure to find a matching assembly.  Other callers of this
        // function, such as BindLockedOrService will interpret as deciding
        // not to override an explicit bind with a probed assembly
        hr = S_OK;
        
    Exit:
        BINDER_LOG_LEAVE_HR(W("AssemblyBinder::BindByTpaList"), hr);
        return hr;  
    }
    
    /* static */
    HRESULT AssemblyBinder::GetAssembly(SString     &assemblyPath,
                                        BOOL         fInspectionOnly,
                                        BOOL         fIsInGAC,
                                        
                                        // When binding to the native image, should we
                                        // assume assemblyPath explicitly specifies that
                                        // NI?  (If not, infer the path to the NI
                                        // implicitly.)
                                        BOOL         fExplicitBindToNativeImage,
                                        
                                        Assembly   **ppAssembly,

                                        // If assemblyPath refers to a native image without metadata,
                                        // szMDAssemblyPath gives the alternative file to get metadata.
                                        LPCTSTR      szMDAssemblyPath)
    {
        HRESULT hr = S_OK;

        BINDER_LOG_ENTER(W("Assembly::GetAssembly"));
        BINDER_LOG_STRING(W("assemblyPath"), assemblyPath);

        _ASSERTE(ppAssembly != NULL);

        ReleaseHolder<Assembly> pAssembly;
        ReleaseHolder<IMDInternalImport> pIMetaDataAssemblyImport;
        DWORD dwPAFlags[2];
        PEKIND PeKind = peNone;
        PEImage *pPEImage = NULL;
        PEImage *pNativePEImage = NULL;

        // Allocate assembly object
        SAFE_NEW(pAssembly, Assembly);

        // Obtain assembly meta data
        {
            LPCTSTR szAssemblyPath = const_cast<LPCTSTR>(assemblyPath.GetUnicode());

            BINDER_LOG_ENTER(W("BinderAcquirePEImage"));
            hr = BinderAcquirePEImage(szAssemblyPath, &pPEImage, &pNativePEImage, fExplicitBindToNativeImage);
            BINDER_LOG_LEAVE_HR(W("BinderAcquirePEImage"), hr);
            IF_FAIL_GO(hr);

            // If we found a native image, it might be an MSIL assembly masquerading as an native image
            // as a fallback mechanism for when the Triton tool chain wasn't able to generate a native image.
            // In that case it will not have a native header, so just treat it like the MSIL assembly it is.
            if (pNativePEImage)
            {
                BOOL hasHeader = TRUE;
                IF_FAIL_GO(BinderHasNativeHeader(pNativePEImage, &hasHeader));
                if (!hasHeader)
                {
                     pPEImage = pNativePEImage;
                     pNativePEImage = NULL;
                }
            }

            BINDER_LOG_ENTER(W("BinderAcquireImport"));
            if(pNativePEImage)
                hr = BinderAcquireImport(pNativePEImage, &pIMetaDataAssemblyImport, dwPAFlags, TRUE);
            else
                hr = BinderAcquireImport(pPEImage, &pIMetaDataAssemblyImport, dwPAFlags, FALSE);

            BINDER_LOG_LEAVE_HR(W("BinderAcquireImport"), hr);
            IF_FAIL_GO(hr);

            if (pIMetaDataAssemblyImport == NULL && pNativePEImage != NULL)
            {
                // The native image doesn't contain metadata. Currently this is only supported for Windows.ni.winmd.
                // While loading Windows.winmd, CLRPrivBinderWinRT::GetAssemblyAndTryFindNativeImage should have passed
                // in a non-NULL szMDAssemblyPath, where we can load metadata from. If szMDAssemblyPath is NULL,
                // it indicates that the app is trying to load a non-WinMD assembly named Windows (it's possible
                // that the app happens to contain an assembly Windows.dll). To handle this case properly, we
                // return a file-not-found error, so the caller can continues it's search.
                if (szMDAssemblyPath == NULL)
                {
                    IF_FAIL_GO(HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND));
                }
                else
                {
                    BINDER_LOG_ENTER(W("BinderAcquirePEImage"));
                    hr = BinderAcquirePEImage(szMDAssemblyPath, &pPEImage, NULL, FALSE);
                    BINDER_LOG_LEAVE_HR(W("BinderAcquirePEImage"), hr);
                    IF_FAIL_GO(hr);

                    BINDER_LOG_ENTER(W("BinderAcquireImport"));
                    hr = BinderAcquireImport(pPEImage, &pIMetaDataAssemblyImport, dwPAFlags, FALSE);
                    BINDER_LOG_LEAVE_HR(W("BinderAcquireImport"), hr);
                    IF_FAIL_GO(hr);
                }
            }

            IF_FAIL_GO(TranslatePEToArchitectureType(dwPAFlags, &PeKind));
        }

       // Initialize assembly object
        IF_FAIL_GO(pAssembly->Init(pIMetaDataAssemblyImport,
                                   PeKind,
                                   pPEImage,
                                   pNativePEImage,
                                   assemblyPath,
                                   fInspectionOnly,
                                   fIsInGAC));

        // We're done
        *ppAssembly = pAssembly.Extract();

    Exit:

        BinderReleasePEImage(pPEImage);
        BinderReleasePEImage(pNativePEImage);
        
        BINDER_LOG_LEAVE_HR(W("AssemblyBinder::GetAssembly"), hr);

        // Normalize file not found
        if ((FAILED(hr)) && IsFileNotFound(hr))
        {
            hr = HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND);
        }

        return hr;
    }

#ifndef CROSSGEN_COMPILE

    /* static */
    HRESULT AssemblyBinder::Register(ApplicationContext *pApplicationContext,
                                     BOOL                fInspectionOnly,
                                     BindResult         *pBindResult)
    {
        HRESULT hr = S_OK;
        BINDER_LOG_ENTER(W("AssemblyBinder::Register"));

        if (!pBindResult->GetIsContextBound())
        {
            pApplicationContext->IncrementVersion();

            if (fInspectionOnly)
            {
                InspectionContext *pInspectionContext = pApplicationContext->GetInspectionContext();
                IF_FAIL_GO(pInspectionContext->Register(pBindResult));
            }
            else
            {
                // Register the bindResult in the ExecutionContext only if we dont have it already.
                // This method is invoked under a lock (by its caller), so we are thread safe.
                ContextEntry *pContextEntry = NULL;
                hr = FindInExecutionContext(pApplicationContext, pBindResult->GetAssemblyName(), &pContextEntry);
                if (hr == S_OK)
                {
                    if (pContextEntry == NULL)
                    {
                        ExecutionContext *pExecutionContext = pApplicationContext->GetExecutionContext();
                        IF_FAIL_GO(pExecutionContext->Register(pBindResult));
                    }
                    else
                    {
                        // The dynamic binds are compiled in CoreCLR, but they are not supported. They are only reachable by internal API Assembly.Load(byte[]) that nobody should be calling.
                        // This code path does not handle dynamic binds correctly (and is not expected to). We do not expect to come here for dynamic binds.

                        _ASSERTE(!pContextEntry->GetIsDynamicBind());
                        
                        // Update the BindResult with the contents of the ContextEntry we found
                        pBindResult->SetResult(pContextEntry);
                    }
                }
            }
        }

    Exit:
        BINDER_LOG_LEAVE_HR(W("AssemblyBinder::Register"), hr);
        return hr;
    }

    /* static */
    HRESULT AssemblyBinder::RegisterAndGetHostChosen(ApplicationContext *pApplicationContext,
                                                     LONG                kContextVersion,
                                                     BindResult         *pBindResult,
                                                     BindResult         *pHostBindResult)
    {
        HRESULT hr = S_OK;
        BINDER_LOG_ENTER(W("AssemblyBinder::RegisterHostChosen"));

        _ASSERTE(pBindResult != NULL);
        _ASSERTE(pBindResult->HaveResult());
        _ASSERTE(pHostBindResult != NULL);

        if (!pBindResult->GetIsContextBound())
        {
            pHostBindResult->SetResult(pBindResult);

            {
                // Lock the application context
                CRITSEC_Holder contextLock(pApplicationContext->GetCriticalSectionCookie());

                // Only perform costly validation if other binds succeded before us
                if (kContextVersion != pApplicationContext->GetVersion())
                {
                    IF_FAIL_GO(AssemblyBinder::OtherBindInterfered(pApplicationContext,
                                                                   pBindResult));

                    if (hr == S_FALSE)
                    {
                        // Another bind interfered
                        GO_WITH_HRESULT(hr);
                    }
                }

                // No bind interfered, we can now register
                IF_FAIL_GO(Register(pApplicationContext,
                                    FALSE /* fInspectionOnly */,
                                    pHostBindResult));
            }
        }
        else
        {
            // No work required. Return the input
            pHostBindResult->SetResult(pBindResult);
        }

    Exit:
        BINDER_LOG_LEAVE_HR(W("AssemblyBinder::RegisterHostChosen"), hr);
        return hr;
    }

    /* static */
    HRESULT AssemblyBinder::OtherBindInterfered(ApplicationContext *pApplicationContext,
                                                BindResult         *pBindResult)
    {
        HRESULT hr = S_FALSE;
        BINDER_LOG_ENTER(W("AssemblyBinder::OtherBindInterfered"));
        AssemblyName *pAssemblyName = pBindResult->GetAssemblyName();
        PathString assemblyDisplayName;

        _ASSERTE(pAssemblyName != NULL);
        
        // Look for already cached binding failure (ignore PA, every PA will lock the context)
        pAssemblyName->GetDisplayName(assemblyDisplayName, AssemblyName::INCLUDE_VERSION);
        hr = pApplicationContext->GetFailureCache()->Lookup(assemblyDisplayName);

        if (hr == S_OK)
        {
            ContextEntry *pContextEntry = NULL;

            hr = FindInExecutionContext(pApplicationContext, pAssemblyName, &pContextEntry);

            if ((hr == S_OK) && (pContextEntry == NULL))
            {
                // We can accept this bind in the domain
                GO_WITH_HRESULT(S_OK);
            }
        }

        // Some other bind interfered
        GO_WITH_HRESULT(S_FALSE);

    Exit:
        BINDER_LOG_LEAVE_HR(W("AssemblyBinder::OtherBindInterfered"), hr);
        return hr;
    }

#endif //CROSSGEN_COMPILE

#if !defined(DACCESS_COMPILE) && !defined(CROSSGEN_COMPILE)
HRESULT AssemblyBinder::BindUsingHostAssemblyResolver (/* in */ INT_PTR pManagedAssemblyLoadContextToBindWithin,
                                                       /* in */ AssemblyName       *pAssemblyName,
                                                      /* in */ IAssemblyName      *pIAssemblyName,
                                                      /* in */ CLRPrivBinderCoreCLR *pTPABinder,
                                                      /* out */ Assembly           **ppAssembly)
{
    HRESULT hr = E_FAIL;
    BINDER_LOG_ENTER(W("AssemblyBinder::BindUsingHostAssemblyResolver"));
    
    _ASSERTE(pManagedAssemblyLoadContextToBindWithin != NULL);
    
    // RuntimeInvokeHostAssemblyResolver will perform steps 2-4 of CLRPrivBinderAssemblyLoadContext::BindAssemblyByName.
    ICLRPrivAssembly *pLoadedAssembly = NULL;
    hr = RuntimeInvokeHostAssemblyResolver(pManagedAssemblyLoadContextToBindWithin, pIAssemblyName, 
                                           pTPABinder, pAssemblyName, &pLoadedAssembly);
    if (SUCCEEDED(hr))
    {
        _ASSERTE(pLoadedAssembly != NULL);
        *ppAssembly = static_cast<Assembly *>(pLoadedAssembly);
    }

    BINDER_LOG_LEAVE_HR(W("AssemblyBinder::BindUsingHostAssemblyResolver"), hr);
    return hr;
}

/* static */
HRESULT AssemblyBinder::BindUsingPEImage(/* in */  ApplicationContext *pApplicationContext,
                                         /* in */  BINDER_SPACE::AssemblyName *pAssemblyName,
                                         /* in */  PEImage            *pPEImage,
                                         /* in */  PEKIND              peKind,
                                         /* in */  IMDInternalImport  *pIMetaDataAssemblyImport, 
                                         /* [retval] [out] */  Assembly **ppAssembly)
{
    HRESULT hr = E_FAIL;
    BINDER_LOG_ENTER(W("AssemblyBinder::BindUsingPEImage"));
    
    _ASSERTE(BINDER_SPACE::fAssemblyBinderInitialized == TRUE);

    LONG kContextVersion = 0;
    BindResult bindResult;

    // Prepare binding data
    *ppAssembly = NULL;
    
    // Attempt the actual bind (eventually more than once)
Retry:
    {
        // Lock the application context
        CRITSEC_Holder contextLock(pApplicationContext->GetCriticalSectionCookie());
        
        // Attempt uncached bind and register stream if possible
        hr = BindByName(pApplicationContext,
                               pAssemblyName,
                               BIND_CACHE_FAILURES|BIND_CACHE_RERUN_BIND|BIND_IGNORE_REFDEF_MATCH,
                               false, // excludeAppPaths
                               &bindResult);
        
        if (hr == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND))
        {
            IF_FAIL_GO(CreateImageAssembly(pIMetaDataAssemblyImport,
                                           peKind,
                                           pPEImage,
                                           NULL,
                                           FALSE,
                                           &bindResult));

        }
        else if (hr == S_OK)
        {
            if (bindResult.HaveResult())
            {
                // Attempt was made to load an assembly that has the same name as a previously loaded one. Since same name
                // does not imply the same assembly, we will need to check the MVID to confirm it is the same assembly as being
                // requested.
                //
                GUID incomingMVID;
                ZeroMemory(&incomingMVID, sizeof(GUID));
                
                // If we cannot get MVID, then err on side of caution and fail the
                // load.
                IF_FAIL_GO(pIMetaDataAssemblyImport->GetScopeProps(NULL, &incomingMVID));
                
                GUID boundMVID;
                ZeroMemory(&boundMVID, sizeof(GUID));
                
                // If we cannot get MVID, then err on side of caution and fail the
                // load.
                IF_FAIL_GO(bindResult.GetAsAssembly()->GetMVID(&boundMVID));
                
                if (incomingMVID != boundMVID)
                {
                    // MVIDs do not match, so fail the load.
                    IF_FAIL_GO(COR_E_FILELOAD);
                }
                
                // MVIDs match - request came in for the same assembly that was previously loaded.
                // Let is through...
            }
        }
        
        // Remember the post-bind version of the context
        kContextVersion = pApplicationContext->GetVersion();

    } // lock(pApplicationContext)

    if (bindResult.HaveResult())
    {
        BindResult hostBindResult;

        // This has to happen outside the binder lock as it can cause new binds
        IF_FAIL_GO(RegisterAndGetHostChosen(pApplicationContext,
                                            kContextVersion,
                                            &bindResult,
                                            &hostBindResult));

        if (hr == S_FALSE)
        {
            // Another bind interfered. We need to retry entire bind.
            // This by design loops as long as needed because by construction we eventually
            // will succeed or fail the bind.
            bindResult.Reset();
            goto Retry;
        }
        else if (hr == S_OK)
        {
            *ppAssembly = hostBindResult.GetAsAssembly(TRUE /* fAddRef */);
        }
    }

Exit:
        
    BINDER_LOG_LEAVE_HR(W("AssemblyBinder::BindUsingPEImage"), hr);
    return hr;
}
#endif // !defined(DACCESS_COMPILE) && !defined(CROSSGEN_COMPILE)
};