summaryrefslogtreecommitdiff
path: root/src/vm/assemblyspec.cpp
blob: 8c23f23be2f0f8daa294e03839664b9c9cadbadc (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
// 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.

/*============================================================
**
** Header: AssemblySpec.cpp
**
** Purpose: Implements Assembly binding class
**
**


**
===========================================================*/

#include "common.h"

#include <stdlib.h>

#include "assemblyspec.hpp"
#include "eeconfig.h"
#include "strongname.h"
#include "strongnameholders.h"
#include "eventtrace.h"

#ifdef FEATURE_COMINTEROP
#include "clrprivbinderutil.h"
#include "winrthelpers.h"
#endif


extern "C" int dprintf(int fd, const char *format, ...);

#ifdef _DEBUG
// This debug-only wrapper for LookupAssembly is solely for the use of postconditions and
// assertions. The problem is that the real LookupAssembly can throw an OOM
// simply because it can't allocate scratch space. For the sake of asserting,
// we can treat those as successful lookups.  
BOOL UnsafeVerifyLookupAssembly(AssemblySpecBindingCache *pCache, AssemblySpec *pSpec, DomainAssembly *pComparator)
{
    STATIC_CONTRACT_NOTHROW;
    STATIC_CONTRACT_GC_TRIGGERS;
    STATIC_CONTRACT_FORBID_FAULT;

    BOOL result = FALSE;

    EX_TRY
    {
        SCAN_IGNORE_FAULT; // Won't go away: This wrapper exists precisely to turn an OOM here into something our postconditions can deal with.
        result = (pComparator == pCache->LookupAssembly(pSpec));
    }
    EX_CATCH
    {
        Exception *ex = GET_EXCEPTION();

        result = ex->IsTransient();
    }
    EX_END_CATCH(SwallowAllExceptions)

    return result;

}
#endif

#ifdef _DEBUG
// This debug-only wrapper for LookupFile is solely for the use of postconditions and
// assertions. The problem is that the real LookupFile can throw an OOM
// simply because it can't allocate scratch space. For the sake of asserting,
// we can treat those as successful lookups.  
BOOL UnsafeVerifyLookupFile(AssemblySpecBindingCache *pCache, AssemblySpec *pSpec, PEAssembly *pComparator)
{
    STATIC_CONTRACT_NOTHROW;
    STATIC_CONTRACT_GC_TRIGGERS;
    STATIC_CONTRACT_FORBID_FAULT;

    BOOL result = FALSE;

    EX_TRY
    {
        SCAN_IGNORE_FAULT; // Won't go away: This wrapper exists precisely to turn an OOM here into something our postconditions can deal with.
        result = pCache->LookupFile(pSpec)->Equals(pComparator);
    }
    EX_CATCH
    {
        Exception *ex = GET_EXCEPTION();

        result = ex->IsTransient();
    }
    EX_END_CATCH(SwallowAllExceptions)

    return result;

}

#endif

#ifdef _DEBUG

// This debug-only wrapper for Contains is solely for the use of postconditions and
// assertions. The problem is that the real Contains can throw an OOM
// simply because it can't allocate scratch space. For the sake of asserting,
// we can treat those as successful lookups.  
BOOL UnsafeContains(AssemblySpecBindingCache *pCache, AssemblySpec *pSpec)
{
    STATIC_CONTRACT_NOTHROW;
    STATIC_CONTRACT_GC_TRIGGERS;
    STATIC_CONTRACT_FORBID_FAULT;

    BOOL result = FALSE;

    EX_TRY
    {
        SCAN_IGNORE_FAULT; // Won't go away: This wrapper exists precisely to turn an OOM here into something our postconditions can deal with.
        result = pCache->Contains(pSpec);
    }
    EX_CATCH
    {
        Exception *ex = GET_EXCEPTION();

        result = ex->IsTransient();
    }
    EX_END_CATCH(SwallowAllExceptions)

    return result;

}
#endif



AssemblySpecHash::~AssemblySpecHash()
{
    CONTRACTL
    {
        DESTRUCTOR_CHECK;
        NOTHROW;
        GC_TRIGGERS;
        MODE_ANY;
    }
    CONTRACTL_END;

    PtrHashMap::PtrIterator i = m_map.begin();
    while (!i.end())
    {
        AssemblySpec *s = (AssemblySpec*) i.GetValue();
        if (m_pHeap != NULL)
            s->~AssemblySpec();            
        else
            delete s;

        ++i;
    }
}

// Check assembly name for invalid characters
// Return value:
//      TRUE: If no invalid characters were found, or if the assembly name isn't set
//      FALSE: If invalid characters were found
// This is needed to prevent security loopholes with ':', '/' and '\' in the assembly name
BOOL AssemblySpec::IsValidAssemblyName()
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
    }
    CONTRACTL_END;

    if (GetName())
    {
        SString ssAssemblyName(SString::Utf8, GetName());
        for (SString::Iterator i = ssAssemblyName.Begin(); i[0] != W('\0'); i++) {
            switch (i[0]) {
                case W(':'):
                case W('\\'):
                case W('/'):
                    return FALSE;

                default:
                    break;
            }
        }
    }
    return TRUE;
}

HRESULT AssemblySpec::InitializeSpecInternal(mdToken kAssemblyToken,
                                  IMDInternalImport *pImport,
                                  DomainAssembly *pStaticParent,
                                  BOOL fAllowAllocation)
{
    CONTRACTL
    {
        INSTANCE_CHECK;
        if (fAllowAllocation) {GC_TRIGGERS;} else {GC_NOTRIGGER;};
        if (fAllowAllocation) {INJECT_FAULT(COMPlusThrowOM());} else {FORBID_FAULT;};
        NOTHROW;
        MODE_ANY;
        PRECONDITION(pImport->IsValidToken(kAssemblyToken));
        PRECONDITION(TypeFromToken(kAssemblyToken) == mdtAssembly
                     || TypeFromToken(kAssemblyToken) == mdtAssemblyRef);
    }
    CONTRACTL_END;
    
    HRESULT hr = S_OK;
    
    EX_TRY
    {
        IfFailThrow(BaseAssemblySpec::Init(kAssemblyToken,pImport));

        if (IsContentType_WindowsRuntime())
        {
            if (!fAllowAllocation)
            {   // We don't support this because we must be able to allocate in order to
                // extract embedded type names for the native image scenario. Currently,
                // the only caller of this method with fAllowAllocation == FALSE is
                // Module::GetAssemblyIfLoaded, and since this method will only check the
                // assembly spec cache, and since we can't cache WinRT assemblies, this
                // limitation should have no negative impact.
                IfFailThrow(E_FAIL);
            }

            // Extract embedded content, if present (currently used for embedded WinRT type names).
            ParseEncodedName();
        }

        // For static binds, we cannot reference a weakly named assembly from a strong named one.
        // (Note that this constraint doesn't apply to dynamic binds which is why this check is
        // not farther down the stack.)
        if (pStaticParent != NULL)
        {
            // We dont validate this for CoreCLR as there is no good use-case for this scenario.
            
            SetParentAssembly(pStaticParent);
        }
    }
    EX_CATCH_HRESULT(hr);
    
    return hr;
} // AssemblySpec::InitializeSpecInternal



void AssemblySpec::InitializeSpec(PEAssembly * pFile)
{
    CONTRACTL
    {
        INSTANCE_CHECK;
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
        PRECONDITION(CheckPointer(pFile));
        INJECT_FAULT(COMPlusThrowOM(););
    }
    CONTRACTL_END;
    ReleaseHolder<IMDInternalImport> pImport(pFile->GetMDImportWithRef());
    mdAssembly a;
    IfFailThrow(pImport->GetAssemblyFromScope(&a));

    InitializeSpec(a, pImport, NULL);
    
#ifdef FEATURE_COMINTEROP
    if (IsContentType_WindowsRuntime())
    {
        LPCSTR  szNamespace;
        LPCSTR  szTypeName;
        SString ssFakeNameSpaceAllocationBuffer;
        IfFailThrow(::GetFirstWinRTTypeDef(pImport, &szNamespace, &szTypeName, pFile->GetPath(), &ssFakeNameSpaceAllocationBuffer));
        
        SetWindowsRuntimeType(szNamespace, szTypeName);

        // pFile is not guaranteed to stay around (it might be unloaded with the AppDomain), we have to copy the type name
        CloneFields(WINRT_TYPE_NAME_OWNED);
    }
#endif //FEATURE_COMINTEROP

    // Set the binding context for the AssemblySpec
    ICLRPrivBinder* pCurrentBinder = GetBindingContext();
    ICLRPrivBinder* pExpectedBinder = pFile->GetBindingContext();
    if (pCurrentBinder == NULL)
    {
        // We should aways having the binding context in the PEAssembly. The only exception to this are the following:
        //
        // 1) when we are here during EEStartup and loading mscorlib.dll.
        // 2) We are dealing with dynamic assemblies
        _ASSERTE((pExpectedBinder != NULL) || pFile->IsSystem() || pFile->IsDynamic());
        SetBindingContext(pExpectedBinder);
    }
}

#ifndef CROSSGEN_COMPILE

// This uses thread storage to allocate space. Please use Checkpoint and release it.
HRESULT AssemblySpec::InitializeSpec(StackingAllocator* alloc, ASSEMBLYNAMEREF* pName, 
                                  BOOL fParse /*=TRUE*/)
{
    CONTRACTL
    {
        INSTANCE_CHECK;
        THROWS;
        MODE_COOPERATIVE;
        GC_TRIGGERS;
        PRECONDITION(CheckPointer(alloc));
        PRECONDITION(CheckPointer(pName));
        PRECONDITION(IsProtectedByGCFrame(pName));
        INJECT_FAULT(COMPlusThrowOM(););
    }
    CONTRACTL_END;

    // Simple name
    if ((*pName)->GetSimpleName() != NULL) {
        WCHAR* pString;
        int    iString;
        ((STRINGREF) (*pName)->GetSimpleName())->RefInterpretGetStringValuesDangerousForGC(&pString, &iString);
        DWORD lgth = WszWideCharToMultiByte(CP_UTF8, 0, pString, iString, NULL, 0, NULL, NULL);
        if (lgth + 1 < lgth)
            ThrowHR(E_INVALIDARG);
        LPSTR lpName = (LPSTR) alloc->Alloc(S_UINT32(lgth) + S_UINT32(1));
        WszWideCharToMultiByte(CP_UTF8, 0, pString, iString,
                               lpName, lgth+1, NULL, NULL);
        lpName[lgth] = '\0';
        // Calling Init here will trash the cached lpName in AssemblySpec, but lpName is still needed by ParseName
        // call below.
        SetName(lpName);
    }
    else
    {
        // Ensure we always have an assembly simple name.
        LPSTR lpName = (LPSTR) alloc->Alloc(S_UINT32(1));
        lpName[0] = '\0';
        SetName(lpName);
    }

    if (fParse) {
        HRESULT hr = ParseName();
        // Sometimes Fusion flags invalid characters in the name, sometimes it doesn't
        // depending on where the invalid characters are
        // We want to Raise the assembly resolve event on all invalid characters
        // but calling ParseName before checking for invalid characters gives Fusion a chance to
        // parse the rest of the name (to get a public key token, etc.)
        if ((hr == FUSION_E_INVALID_NAME) || (!IsValidAssemblyName())) {
            // This is the only case where we do not throw on an error
            // We don't want to throw so as to give the caller a chance to call RaiseAssemblyResolveEvent
            // The only caller that cares is System.Reflection.Assembly.InternalLoad which calls us through
            // AssemblyNameNative::Init
            return FUSION_E_INVALID_NAME;
        }
        else
            IfFailThrow(hr);
    }
    else {
        AssemblyMetaDataInternal asmInfo;
        // Flags
        DWORD dwFlags = (*pName)->GetFlags();
    
        // Version
        VERSIONREF version = (VERSIONREF) (*pName)->GetVersion();
        if(version == NULL) {
            asmInfo.usMajorVersion = (USHORT)-1;
            asmInfo.usMinorVersion = (USHORT)-1;
            asmInfo.usBuildNumber = (USHORT)-1;
            asmInfo.usRevisionNumber = (USHORT)-1;
        }
        else {
            asmInfo.usMajorVersion = (USHORT)version->GetMajor();
            asmInfo.usMinorVersion = (USHORT)version->GetMinor();
            asmInfo.usBuildNumber = (USHORT)version->GetBuild();
            asmInfo.usRevisionNumber = (USHORT)version->GetRevision();
        }

        asmInfo.szLocale = 0;
        asmInfo.ulOS = 0;
        asmInfo.rOS = 0;
        asmInfo.ulProcessor = 0;
        asmInfo.rProcessor = 0;

        if ((*pName)->GetCultureInfo() != NULL) 
        {
            struct _gc {
                OBJECTREF   cultureinfo;
                STRINGREF   pString;
            } gc;

            gc.cultureinfo = (*pName)->GetCultureInfo();
            gc.pString = NULL;
            
            GCPROTECT_BEGIN(gc);

            MethodDescCallSite getName(METHOD__CULTURE_INFO__GET_NAME, &gc.cultureinfo);
            
            ARG_SLOT args[] = {
                ObjToArgSlot(gc.cultureinfo)
            };
            gc.pString = getName.Call_RetSTRINGREF(args);
            if (gc.pString != NULL) {
                WCHAR* pString;
                int    iString;
                gc.pString->RefInterpretGetStringValuesDangerousForGC(&pString, &iString);
                DWORD lgth = WszWideCharToMultiByte(CP_UTF8, 0, pString, iString, NULL, 0, NULL, NULL);
                S_UINT32 lengthWillNull = S_UINT32(lgth) + S_UINT32(1);
                LPSTR lpLocale = (LPSTR) alloc->Alloc(lengthWillNull);
                if (lengthWillNull.IsOverflow())
                {
                    COMPlusThrowHR(COR_E_OVERFLOW);
                }
                WszWideCharToMultiByte(CP_UTF8, 0, pString, iString,
                                       lpLocale, lengthWillNull.Value(), NULL, NULL);
                lpLocale[lgth] = '\0';
                asmInfo.szLocale = lpLocale;
            }
            GCPROTECT_END();
        }

        // Strong name
        DWORD cbPublicKeyOrToken=0;
        BYTE* pbPublicKeyOrToken=NULL;
        // Note that we prefer to take a public key token if present,
        // even if flags indicate a full public key
        if ((*pName)->GetPublicKeyToken() != NULL) {
            dwFlags &= ~afPublicKey;
            PBYTE  pArray = NULL;
            pArray = (*pName)->GetPublicKeyToken()->GetDirectPointerToNonObjectElements();
            cbPublicKeyOrToken = (*pName)->GetPublicKeyToken()->GetNumComponents();
            pbPublicKeyOrToken = pArray;
        }
        else if ((*pName)->GetPublicKey() != NULL) {
            dwFlags |= afPublicKey;
            PBYTE  pArray = NULL;
            pArray = (*pName)->GetPublicKey()->GetDirectPointerToNonObjectElements();
            cbPublicKeyOrToken = (*pName)->GetPublicKey()->GetNumComponents();
            pbPublicKeyOrToken = pArray;
        }
        BaseAssemblySpec::Init(GetName(),&asmInfo,pbPublicKeyOrToken,cbPublicKeyOrToken,dwFlags);
    }

    CloneFieldsToStackingAllocator(alloc);

    // Extract embedded WinRT name, if present.
    ParseEncodedName();

    return S_OK;
}

void AssemblySpec::AssemblyNameInit(ASSEMBLYNAMEREF* pAsmName, PEImage* pImageInfo)
{
    CONTRACTL 
    {
        THROWS;
        MODE_COOPERATIVE;
        GC_TRIGGERS;
        PRECONDITION(IsProtectedByGCFrame (pAsmName));
    }
    CONTRACTL_END;
    
    struct _gc {
        OBJECTREF CultureInfo;
        STRINGREF Locale;
        OBJECTREF Version;
        U1ARRAYREF PublicKeyOrToken;
        STRINGREF Name;
        STRINGREF CodeBase;
    } gc;
    ZeroMemory(&gc, sizeof(gc));
    
    GCPROTECT_BEGIN(gc);
    
    if ((m_context.usMajorVersion != (USHORT) -1) &&
        (m_context.usMinorVersion != (USHORT) -1)) {

        MethodTable* pVersion = MscorlibBinder::GetClass(CLASS__VERSION);
    
        // version
        gc.Version = AllocateObject(pVersion);

        // BaseAssemblySpec and AssemblyName properties store uint16 components for the version. Version and AssemblyVersion
        // store int32 or uint32. When the former are initialized from the latter, the components are truncated to uint16 size.
        // When the latter are initialized from the former, they are zero-extended to int32 size. For uint16 components, the max
        // value is used to indicate an unspecified component. For int32 components, -1 is used. Since we're initializing a
        // Version from an assembly version, map the uint16 unspecified value to the int32 size.
        int componentCount = 2;
        if (m_context.usBuildNumber != (USHORT)-1)
        {
            ++componentCount;
            if (m_context.usRevisionNumber != (USHORT)-1)
            {
                ++componentCount;
            }
        }
        switch (componentCount)
        {
            case 2:
            {
                // Call Version(int, int) because Version(int, int, int, int) does not allow passing the unspecified value -1
                MethodDescCallSite ctorMethod(METHOD__VERSION__CTOR_Ix2);
                ARG_SLOT VersionArgs[] =
                {
                    ObjToArgSlot(gc.Version),
                    (ARG_SLOT) m_context.usMajorVersion,
                    (ARG_SLOT) m_context.usMinorVersion
                };
                ctorMethod.Call(VersionArgs);
                break;
            }

            case 3:
            {
                // Call Version(int, int, int) because Version(int, int, int, int) does not allow passing the unspecified value -1
                MethodDescCallSite ctorMethod(METHOD__VERSION__CTOR_Ix3);
                ARG_SLOT VersionArgs[] =
                {
                    ObjToArgSlot(gc.Version),
                    (ARG_SLOT) m_context.usMajorVersion,
                    (ARG_SLOT) m_context.usMinorVersion,
                    (ARG_SLOT) m_context.usBuildNumber
                };
                ctorMethod.Call(VersionArgs);
                break;
            }

            default:
            {
                // Call Version(int, int, int, int)
                _ASSERTE(componentCount == 4);
                MethodDescCallSite ctorMethod(METHOD__VERSION__CTOR_Ix4);
                ARG_SLOT VersionArgs[] =
                {
                    ObjToArgSlot(gc.Version),
                    (ARG_SLOT) m_context.usMajorVersion,
                    (ARG_SLOT) m_context.usMinorVersion,
                    (ARG_SLOT) m_context.usBuildNumber,
                    (ARG_SLOT) m_context.usRevisionNumber
                };
                ctorMethod.Call(VersionArgs);
                break;
            }
        }
    }
    
    // cultureinfo
    if (m_context.szLocale) {
        
        MethodTable* pCI = MscorlibBinder::GetClass(CLASS__CULTURE_INFO);
        gc.CultureInfo = AllocateObject(pCI);
        
        gc.Locale = StringObject::NewString(m_context.szLocale);

        MethodDescCallSite strCtor(METHOD__CULTURE_INFO__STR_CTOR);
        
        ARG_SLOT args[2] = 
        {
            ObjToArgSlot(gc.CultureInfo),
            ObjToArgSlot(gc.Locale)
        };
        
        strCtor.Call(args);
    }

    // public key or token byte array
    if (m_pbPublicKeyOrToken)
    {
        gc.PublicKeyOrToken = (U1ARRAYREF)AllocatePrimitiveArray(ELEMENT_TYPE_U1, m_cbPublicKeyOrToken);
        memcpyNoGCRefs(gc.PublicKeyOrToken->m_Array, m_pbPublicKeyOrToken, m_cbPublicKeyOrToken);
    }

    // simple name
    if(GetName())
        gc.Name = StringObject::NewString(GetName());

    if (GetCodeBase())
        gc.CodeBase = StringObject::NewString(GetCodeBase());
    
    BOOL fPublicKey = m_dwFlags & afPublicKey;

    ULONG hashAlgId=0;
    if (pImageInfo != NULL)
    {
        if(!pImageInfo->GetMDImport()->IsValidToken(TokenFromRid(1, mdtAssembly)))
        {
            ThrowHR(COR_E_BADIMAGEFORMAT);
        }
        IfFailThrow(pImageInfo->GetMDImport()->GetAssemblyProps(TokenFromRid(1, mdtAssembly), NULL, NULL, &hashAlgId, NULL, NULL, NULL));
    }

    MethodDescCallSite init(METHOD__ASSEMBLY_NAME__CTOR);
    
    ARG_SLOT MethodArgs[] =
    {
        ObjToArgSlot(*pAsmName),
        ObjToArgSlot(gc.Name),
        fPublicKey ? ObjToArgSlot(gc.PublicKeyOrToken) :
        (ARG_SLOT) NULL, // public key
        fPublicKey ? (ARG_SLOT) NULL :
        ObjToArgSlot(gc.PublicKeyOrToken), // public key token
        ObjToArgSlot(gc.Version),
        ObjToArgSlot(gc.CultureInfo),
        (ARG_SLOT) hashAlgId,
        (ARG_SLOT) 1, // AssemblyVersionCompatibility.SameMachine
        ObjToArgSlot(gc.CodeBase),
        (ARG_SLOT) m_dwFlags,
        (ARG_SLOT) NULL // key pair
    };
    
    init.Call(MethodArgs);

    // Only set the processor architecture if we're looking at a newer binary that has
    // that information in the PE, and we're not looking at a reference assembly.
    if(pImageInfo && !pImageInfo->HasV1Metadata() && !pImageInfo->IsReferenceAssembly())
    {
        DWORD dwMachine, dwKind;

        pImageInfo->GetPEKindAndMachine(&dwMachine,&dwKind);
        
        MethodDescCallSite setPA(METHOD__ASSEMBLY_NAME__SET_PROC_ARCH_INDEX);
        
        ARG_SLOT PAMethodArgs[] = {
            ObjToArgSlot(*pAsmName),
            (ARG_SLOT)dwMachine,
            (ARG_SLOT)dwKind
        };

        setPA.Call(PAMethodArgs);
    }

    GCPROTECT_END();
}

// This uses thread storage to allocate space. Please use Checkpoint and release it.
void AssemblySpec::SetCodeBase(StackingAllocator* alloc, STRINGREF *pCodeBase)
{
    CONTRACTL
    {
        INSTANCE_CHECK;
        THROWS;
        GC_TRIGGERS;
        MODE_COOPERATIVE;
        PRECONDITION(CheckPointer(pCodeBase));
        INJECT_FAULT(COMPlusThrowOM(););
    }
    CONTRACTL_END;

    // Codebase
    if (pCodeBase != NULL && *pCodeBase != NULL) {
        WCHAR* pString;
        int    iString;
        (*pCodeBase)->RefInterpretGetStringValuesDangerousForGC(&pString, &iString);

        DWORD dwCodeBase = (DWORD) iString+1;
        m_wszCodeBase = new (alloc) WCHAR[dwCodeBase]; 
        memcpy((void*)m_wszCodeBase, pString, dwCodeBase * sizeof(WCHAR));
    }
}

#endif // CROSSGEN_COMPILE


void AssemblySpec::MatchRetargetedPublicKeys(Assembly *pAssembly)
{
    CONTRACTL
    {
        INSTANCE_CHECK;
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
        PRECONDITION(CheckPointer(pAssembly));
    }
    CONTRACTL_END;
    ThrowHR(FUSION_E_REF_DEF_MISMATCH);
}


// Check if the supplied assembly's public key matches up with the one in the Spec, if any
// Throws an appropriate exception in case of a mismatch
void AssemblySpec::MatchPublicKeys(Assembly *pAssembly)
{
    CONTRACTL
    {
        INSTANCE_CHECK;
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
    }
    CONTRACTL_END;
    // Check that the public keys are the same as in the AR.
    if (IsStrongNamed()) {

        const void *pbPublicKey;
        DWORD cbPublicKey;
        pbPublicKey = pAssembly->GetPublicKey(&cbPublicKey);
        if (cbPublicKey == 0)
            ThrowHR(FUSION_E_PRIVATE_ASM_DISALLOWED);

        if (m_dwFlags & afPublicKey) {
            if ((m_cbPublicKeyOrToken != cbPublicKey) ||
                memcmp(m_pbPublicKeyOrToken, pbPublicKey, m_cbPublicKeyOrToken))
                return MatchRetargetedPublicKeys(pAssembly);
        }

        // Ref has a token
        else {
            StrongNameBufferHolder<BYTE> pbStrongNameToken;
            DWORD cbStrongNameToken;

            if (!StrongNameTokenFromPublicKey((BYTE*) pbPublicKey,
                                              cbPublicKey,
                                              &pbStrongNameToken,
                                              &cbStrongNameToken))
                ThrowHR(StrongNameErrorInfo());
            if ((m_cbPublicKeyOrToken != cbStrongNameToken) ||
                memcmp(m_pbPublicKeyOrToken,
                       pbStrongNameToken,
                       cbStrongNameToken)) {
                return MatchRetargetedPublicKeys(pAssembly);
            }
        }
    }
}


PEAssembly *AssemblySpec::ResolveAssemblyFile(AppDomain *pDomain)
{
    CONTRACT(PEAssembly *)
    {
        INSTANCE_CHECK;
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
        POSTCONDITION(CheckPointer(RETVAL, NULL_OK));
        INJECT_FAULT(COMPlusThrowOM(););
    }
    CONTRACT_END;

    // No assembly resolve on codebase binds
    if (GetName() == NULL)
        RETURN NULL;

    Assembly *pAssembly = pDomain->RaiseAssemblyResolveEvent(this);

    if (pAssembly != NULL) {
        PEAssembly *pFile = pAssembly->GetManifestFile();
        pFile->AddRef();

        RETURN pFile;
    }

    RETURN NULL;
}


Assembly *AssemblySpec::LoadAssembly(FileLoadLevel targetLevel, BOOL fThrowOnFileNotFound)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
    }
    CONTRACTL_END;

    dprintf(1, "AssemblySpec::LoadAssembly B:\n");
    DomainAssembly * pDomainAssembly = LoadDomainAssembly(targetLevel, fThrowOnFileNotFound);
    dprintf(1, "#### AssemblySpec::LoadAssembly == [%s +%d]\n", __FILE__, __LINE__);
    if (pDomainAssembly == NULL) {
    dprintf(1, "#### AssemblySpec::LoadAssembly == [%s +%d]\n", __FILE__, __LINE__);
        _ASSERTE(!fThrowOnFileNotFound);
        return NULL;
    }
    dprintf(1, "#### AssemblySpec::LoadAssembly == [%s +%d]\n", __FILE__, __LINE__);
    Assembly *ret = pDomainAssembly->GetAssembly();

    dprintf(1, "AssemblySpec::LoadAssembly E: ret=%p\n", ret);
    return ret;
}

// Returns a BOOL indicating if the two Binder references point to the same
// binder instance.
BOOL AreSameBinderInstance(ICLRPrivBinder *pBinderA, ICLRPrivBinder *pBinderB)
{
    LIMITED_METHOD_CONTRACT;
    
    BOOL fIsSameInstance = (pBinderA == pBinderB);
    
    if (!fIsSameInstance && (pBinderA != NULL) && (pBinderB != NULL))
    {
        // Get the ID for the first binder
        UINT_PTR binderIDA = 0, binderIDB = 0;
        HRESULT hr = pBinderA->GetBinderID(&binderIDA);
        if (SUCCEEDED(hr))
        {
            // Get the ID for the second binder
            hr = pBinderB->GetBinderID(&binderIDB);
            if (SUCCEEDED(hr))
            {
                fIsSameInstance = (binderIDA == binderIDB);
            }
        }
    }
    
    return fIsSameInstance;
}

ICLRPrivBinder* AssemblySpec::GetBindingContextFromParentAssembly(AppDomain *pDomain)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
        PRECONDITION(pDomain != NULL);
    }
    CONTRACTL_END;
    
    ICLRPrivBinder *pParentAssemblyBinder = NULL;
    DomainAssembly *pParentDomainAssembly = GetParentAssembly();
    
    if(pParentDomainAssembly != NULL)
    {
        // Get the PEAssembly associated with the parent's domain assembly
        PEAssembly *pParentPEAssembly = pParentDomainAssembly->GetFile();
        
        // ICLRPrivAssembly implements ICLRPrivBinder and thus, "is a" binder in a manner of semantics.
        pParentAssemblyBinder = pParentPEAssembly->GetBindingContext();
    }

    if (GetPreferFallbackLoadContextBinder())
    {
        // If we have been asked to use the fallback load context binder (currently only supported for AssemblyLoadContext.LoadFromAssemblyName),
        // then pretend we do not have any binder yet available.
        _ASSERTE(GetFallbackLoadContextBinderForRequestingAssembly() != NULL);
        pParentAssemblyBinder = NULL;
    }

    if (pParentAssemblyBinder == NULL)
    {
        // If the parent assembly binder is not available, then we maybe dealing with one of the following
        // assembly scenarios:
        //
        // 1) Domain Neutral assembly
        // 2) Entrypoint assembly
        // 3) AssemblyLoadContext.LoadFromAssemblyName
        //
        // For (1) and (2), we will need to bind against the DefaultContext binder (aka TPA Binder). This happens
        // below if we do not find the parent assembly binder.
        //
        // For (3), fetch the fallback load context binder reference.
        
        pParentAssemblyBinder = GetFallbackLoadContextBinderForRequestingAssembly();
    }

    if (pParentAssemblyBinder != NULL)
    {
        CLRPrivBinderCoreCLR *pTPABinder = pDomain->GetTPABinderContext();
        if (AreSameBinderInstance(pTPABinder, pParentAssemblyBinder))
        {
            // If the parent assembly is a platform (TPA) assembly, then its binding context will always be the TPABinder context. In 
            // such case, we will return the default context for binding to allow the bind to go
            // via the custom binder context, if it was overridden. If it was not overridden, then we will get the expected
            // TPABinder context anyways.
            //
            // Get the reference to the default binding context (this could be the TPABinder context or custom AssemblyLoadContext)
            pParentAssemblyBinder = static_cast<ICLRPrivBinder*>(pDomain->GetFusionContext());
        }
    }

#if defined(FEATURE_COMINTEROP)
    if (!IsContentType_WindowsRuntime() && (pParentAssemblyBinder != NULL))
    {
        CLRPrivBinderWinRT *pWinRTBinder = pDomain->GetWinRtBinder();
        if (AreSameBinderInstance(pWinRTBinder, pParentAssemblyBinder))
        {
            // We could be here when a non-WinRT assembly load is triggerred by a winmd (e.g. System.Runtime being loaded due to
            // types being referenced from Windows.Foundation.Winmd).
            //
            // If the AssemblySpec does not correspond to WinRT type but our parent assembly binder is a WinRT binder,
            // then such an assembly will not be found by the binder.
            // In such a case, the parent binder should be the fallback binder for the WinRT assembly if one exists.
            ICLRPrivBinder* pParentWinRTBinder = pParentAssemblyBinder;
            pParentAssemblyBinder = NULL;
            ReleaseHolder<ICLRPrivAssemblyID_WinRT> assembly;
            if (SUCCEEDED(pParentWinRTBinder->QueryInterface<ICLRPrivAssemblyID_WinRT>(&assembly)))
            {
                pParentAssemblyBinder = dac_cast<PTR_CLRPrivAssemblyWinRT>(assembly.GetValue())->GetFallbackBinder();

                // The fallback binder should not be a WinRT binder.
                _ASSERTE(!AreSameBinderInstance(pWinRTBinder, pParentAssemblyBinder));
            }
        }
    }
#endif // defined(FEATURE_COMINTEROP)
    
    if (!pParentAssemblyBinder)
    {
        // We can be here when loading assemblies via the host (e.g. ICLRRuntimeHost2::ExecuteAssembly) or dealing with assemblies
        // whose parent is a domain neutral assembly (see comment above for details).
        //
        // In such a case, the parent assembly (semantically) is CoreLibrary and thus, the default binding context should be 
        // used as the parent assembly binder.
        pParentAssemblyBinder = static_cast<ICLRPrivBinder*>(pDomain->GetFusionContext());
    }
    
    return pParentAssemblyBinder;
}

DomainAssembly *AssemblySpec::LoadDomainAssembly(FileLoadLevel targetLevel,
                                                 BOOL fThrowOnFileNotFound)
{
    CONTRACT(DomainAssembly *)
    {
        INSTANCE_CHECK;
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
        POSTCONDITION((!fThrowOnFileNotFound && CheckPointer(RETVAL, NULL_OK))
                      || CheckPointer(RETVAL));
        INJECT_FAULT(COMPlusThrowOM(););
    }
    CONTRACT_END;

    ETWOnStartup (LoaderCatchCall_V1, LoaderCatchCallEnd_V1);
    AppDomain* pDomain = GetAppDomain();


    DomainAssembly *pAssembly = nullptr;

    ICLRPrivBinder * pBinder = GetHostBinder();
    
    // If no binder was explicitly set, check if parent assembly has a binder.
    if (pBinder == nullptr)
    {
        pBinder = GetBindingContextFromParentAssembly(pDomain);
    }

    if ((pAssembly == nullptr) && CanUseWithBindingCache())
    {
        pAssembly = pDomain->FindCachedAssembly(this);
    }

    if (pAssembly)
    {
        pDomain->LoadDomainFile(pAssembly, targetLevel);
        RETURN pAssembly;
    }


    PEAssemblyHolder pFile(pDomain->BindAssemblySpec(this, fThrowOnFileNotFound));
    if (pFile == NULL)
        RETURN NULL;

    pAssembly = pDomain->LoadDomainAssembly(this, pFile, targetLevel);

    RETURN pAssembly;
}

/* static */
Assembly *AssemblySpec::LoadAssembly(LPCSTR pSimpleName, 
                                     AssemblyMetaDataInternal* pContext,
                                     const BYTE * pbPublicKeyOrToken,
                                     DWORD cbPublicKeyOrToken,
                                     DWORD dwFlags)
{
    CONTRACT(Assembly *)
    {
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
        PRECONDITION(CheckPointer(pSimpleName));
        POSTCONDITION(CheckPointer(RETVAL));
        INJECT_FAULT(COMPlusThrowOM(););
    }
    CONTRACT_END;

    AssemblySpec spec;
    IfFailThrow(spec.Init(pSimpleName, pContext,
                          pbPublicKeyOrToken, cbPublicKeyOrToken, dwFlags));
    
    RETURN spec.LoadAssembly(FILE_LOADED);
}

/* static */
Assembly *AssemblySpec::LoadAssembly(LPCWSTR pFilePath)
{
    CONTRACT(Assembly *)
    {
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
        PRECONDITION(CheckPointer(pFilePath));
        POSTCONDITION(CheckPointer(RETVAL));
        INJECT_FAULT(COMPlusThrowOM(););
    }
    CONTRACT_END;

    AssemblySpec spec;
    spec.SetCodeBase(pFilePath);
    RETURN spec.LoadAssembly(FILE_LOADED);
}

HRESULT AssemblySpec::CheckFriendAssemblyName()
{
    WRAPPER_NO_CONTRACT;

    // Version, Culture, Architecture, and publickeytoken are not permitted
    if ((m_context.usMajorVersion != (USHORT) -1) ||
        (m_context.szLocale != NULL) ||
        (IsAfPA_Specified(m_dwFlags)) ||
        (IsStrongNamed() && !HasPublicKey()))
    {
        return META_E_CA_BAD_FRIENDS_ARGS;
    }
    else
    {
        return S_OK;
    }
}

HRESULT AssemblySpec::EmitToken(
    IMetaDataAssemblyEmit *pEmit, 
    mdAssemblyRef *pToken,
    BOOL fUsePublicKeyToken, /*=TRUE*/
    BOOL fMustBeBindable /*=FALSE*/)
{
    CONTRACTL
    {
        INSTANCE_CHECK;
        MODE_ANY;
        NOTHROW;
        GC_NOTRIGGER;
        INJECT_FAULT(return E_OUTOFMEMORY;);
    }
    CONTRACTL_END;

    HRESULT hr = S_OK;

    EX_TRY
    {
        SmallStackSString ssName;
        fMustBeBindable ? GetEncodedName(ssName) : GetName(ssName);

        ASSEMBLYMETADATA AMD;

        AMD.usMajorVersion = m_context.usMajorVersion;
        AMD.usMinorVersion = m_context.usMinorVersion;
        AMD.usBuildNumber = m_context.usBuildNumber;
        AMD.usRevisionNumber = m_context.usRevisionNumber;

        if (m_context.szLocale) {
            AMD.cbLocale = MultiByteToWideChar(CP_UTF8, 0, m_context.szLocale, -1, NULL, 0);
            if(AMD.cbLocale==0)
                IfFailGo(HRESULT_FROM_GetLastError());
            AMD.szLocale = (LPWSTR) alloca(AMD.cbLocale * sizeof(WCHAR) );
            if(MultiByteToWideChar(CP_UTF8, 0, m_context.szLocale, -1, AMD.szLocale, AMD.cbLocale)==0)
                IfFailGo(HRESULT_FROM_GetLastError());
        }
        else {
            AMD.cbLocale = 0;
            AMD.szLocale = NULL;
        }

        // If we've been asked to emit a public key token in the reference but we've
        // been given a public key then we need to generate the token now.
        if (m_cbPublicKeyOrToken && fUsePublicKeyToken && IsAfPublicKey(m_dwFlags)) {
            StrongNameBufferHolder<BYTE> pbPublicKeyToken;
            DWORD cbPublicKeyToken;
            if (!StrongNameTokenFromPublicKey(m_pbPublicKeyOrToken,
                                              m_cbPublicKeyOrToken,
                                              &pbPublicKeyToken,
                                              &cbPublicKeyToken)) {
                IfFailGo(StrongNameErrorInfo());
            }

            hr = pEmit->DefineAssemblyRef(pbPublicKeyToken,
                                          cbPublicKeyToken,
                                          ssName.GetUnicode(),
                                          &AMD,
                                          NULL,
                                          0,
                                          m_dwFlags & ~afPublicKey,
                                          pToken);
        }
        else {
            hr = pEmit->DefineAssemblyRef(m_pbPublicKeyOrToken,
                                          m_cbPublicKeyOrToken,
                                          ssName.GetUnicode(),
                                          &AMD,
                                          NULL,
                                          0,
                                          m_dwFlags,
                                          pToken);
        }

        hr = S_OK;
    ErrExit:
        ;
    }
    EX_CATCH_HRESULT(hr);
    
    return hr;
}

//===========================================================================================
// Constructs an AssemblySpec for the given IAssemblyName. Recognizes IAssemblyName objects
// that were built from WinRT AssemblySpec objects, extracts the encoded type name, and sets
// the type namespace and class name properties appropriately.

void AssemblySpec::ParseEncodedName()
{
    CONTRACTL {
        THROWS;
        GC_NOTRIGGER;
        MODE_ANY;
    } CONTRACTL_END

#ifdef FEATURE_COMINTEROP
    if (IsContentType_WindowsRuntime())
    {
        StackSString ssEncodedName(SString::Utf8, m_pAssemblyName);
        ssEncodedName.Normalize();

        SString::Iterator itBang = ssEncodedName.Begin();
        if (ssEncodedName.Find(itBang, SL(W("!"))))
        {
            StackSString ssAssemblyName(ssEncodedName, ssEncodedName.Begin(), itBang - ssEncodedName.Begin());
            StackSString ssTypeName(ssEncodedName, ++itBang, ssEncodedName.End() - itBang);
            SetName(ssAssemblyName);
            SetWindowsRuntimeType(ssTypeName);
        }
    }
#endif
}

void AssemblySpec::SetWindowsRuntimeType(
    LPCUTF8 szNamespace, 
    LPCUTF8 szClassName)
{
    CONTRACTL
    {
        THROWS;
        GC_NOTRIGGER;
        MODE_ANY;
    }
    CONTRACTL_END;
#ifdef FEATURE_COMINTEROP    
    // Release already allocated string
    if (m_ownedFlags & WINRT_TYPE_NAME_OWNED)
    {
        if (m_szWinRtTypeNamespace != nullptr)
            delete [] m_szWinRtTypeNamespace;
        if (m_szWinRtTypeClassName != nullptr)
            delete [] m_szWinRtTypeClassName;
    }
    m_szWinRtTypeNamespace = szNamespace;
    m_szWinRtTypeClassName = szClassName;
    
    m_ownedFlags &= ~WINRT_TYPE_NAME_OWNED;
#else
    // Classic (non-phone) CoreCLR does not support WinRT interop; this should never be called with a non-empty type name
    _ASSERTE((szNamespace == NULL) && (szClassName == NULL));
#endif
}

void AssemblySpec::SetWindowsRuntimeType(
    SString const & _ssTypeName)
{
    CONTRACTL
    {
        THROWS;
        GC_NOTRIGGER;
        MODE_ANY;
    }
    CONTRACTL_END;

    // Release already allocated string
    if (m_ownedFlags & WINRT_TYPE_NAME_OWNED)
    {
        if (m_szWinRtTypeNamespace != nullptr)
            delete[] m_szWinRtTypeNamespace;
        if (m_szWinRtTypeClassName != nullptr)
            delete[] m_szWinRtTypeClassName;
        m_ownedFlags &= ~WINRT_TYPE_NAME_OWNED;
    }

    SString ssTypeName;
    _ssTypeName.ConvertToUTF8(ssTypeName);
    
    LPUTF8 szTypeName = (LPUTF8)ssTypeName.GetUTF8NoConvert();
    ns::SplitInline(szTypeName, m_szWinRtTypeNamespace, m_szWinRtTypeClassName);
    m_ownedFlags &= ~WINRT_TYPE_NAME_OWNED;
    // Make a copy of the type name strings
    CloneFields(WINRT_TYPE_NAME_OWNED);
}


AssemblySpecBindingCache::AssemblySpecBindingCache()
{
    LIMITED_METHOD_CONTRACT;
}

AssemblySpecBindingCache::~AssemblySpecBindingCache()
{
    CONTRACTL
    {
        DESTRUCTOR_CHECK;
        NOTHROW;
        GC_TRIGGERS;
        MODE_ANY;
    }
    CONTRACTL_END;

    Clear();
}

void AssemblySpecBindingCache::Clear()
{
    CONTRACTL
    {
        DESTRUCTOR_CHECK;
        NOTHROW;
        GC_TRIGGERS;
        MODE_ANY;
    }
    CONTRACTL_END;

    PtrHashMap::PtrIterator i = m_map.begin();
    while (!i.end())
    {
        AssemblyBinding *b = (AssemblyBinding*) i.GetValue();
        if (m_pHeap == NULL)
            delete b;
        else
            b->~AssemblyBinding();
    
        ++i;
    }
        
    m_map.Clear();
}

void AssemblySpecBindingCache::Init(CrstBase *pCrst, LoaderHeap *pHeap)
{
    WRAPPER_NO_CONTRACT;

    LockOwner lock = {pCrst, IsOwnerOfCrst};
    m_map.Init(INITIAL_ASM_SPEC_HASH_SIZE, CompareSpecs, TRUE, &lock);
    m_pHeap = pHeap;
}

AssemblySpecBindingCache::AssemblyBinding* AssemblySpecBindingCache::LookupInternal(AssemblySpec* pSpec, BOOL fThrow)
{
    CONTRACTL
    {
        if (fThrow)
        {
            THROWS;
            GC_TRIGGERS;
            INJECT_FAULT(COMPlusThrowOM(););
        }
        else
        {
            GC_NOTRIGGER;
            NOTHROW;
            FORBID_FAULT;
        }
        MODE_ANY;
        PRECONDITION(pSpec != NULL);
    }
    CONTRACTL_END;

    UPTR key = (UPTR)pSpec->Hash();
    UPTR lookupKey = key;

    // On CoreCLR, we will use the BinderID as the key 
    ICLRPrivBinder *pBinderContextForLookup = NULL;
    AppDomain *pSpecDomain = pSpec->GetAppDomain();
    bool fGetBindingContextFromParent = true;
    
    // Check if the AssemblySpec already has specified its binding context. This will be set for assemblies that are
    // attempted to be explicitly bound using AssemblyLoadContext LoadFrom* methods.
    if(!pSpec->IsAssemblySpecForMscorlib())
        pBinderContextForLookup = pSpec->GetBindingContext();
    else
    {
        // For System.Private.Corelib Binding context is either not set or if set then it should be TPA
        _ASSERTE(pSpec->GetBindingContext() == NULL || pSpec->GetBindingContext() == pSpecDomain->GetFusionContext());
    }

    if (pBinderContextForLookup != NULL)
    {
        // We are working with the actual binding context in which the assembly was expected to be loaded.
        // Thus, we don't need to get it from the parent assembly.
        fGetBindingContextFromParent = false;
    }

    if (fGetBindingContextFromParent)
    {
        // MScorlib does not have a binding context associated with it and its lookup will only be done
        // using its AssemblySpec hash.
        if (!pSpec->IsAssemblySpecForMscorlib())
        {
            pBinderContextForLookup = pSpec->GetBindingContextFromParentAssembly(pSpecDomain);
            pSpec->SetBindingContext(pBinderContextForLookup);
        }
    }

    if (pBinderContextForLookup)
    {
        UINT_PTR binderID = 0;
        HRESULT hr = pBinderContextForLookup->GetBinderID(&binderID);
        _ASSERTE(SUCCEEDED(hr));
        lookupKey = key^binderID;
    }

    AssemblyBinding* pEntry = (AssemblyBinding *)m_map.LookupValue(lookupKey, pSpec);

    // Reset the binding context if one was originally never present in the AssemblySpec and we didnt find any entry
    // in the cache.
    if (fGetBindingContextFromParent)
    {
        if (pEntry == (AssemblyBinding *) INVALIDENTRY)
        {
            pSpec->SetBindingContext(NULL);
        }
    }
    
    return pEntry;
}

BOOL AssemblySpecBindingCache::Contains(AssemblySpec *pSpec)
{
    WRAPPER_NO_CONTRACT;
    return (LookupInternal(pSpec, TRUE) != (AssemblyBinding *) INVALIDENTRY);
}

DomainAssembly *AssemblySpecBindingCache::LookupAssembly(AssemblySpec *pSpec,
                                                         BOOL fThrow /*=TRUE*/)
{
    CONTRACT(DomainAssembly *)
    {
        INSTANCE_CHECK;
        if (fThrow) {
            GC_TRIGGERS;
            THROWS;
            INJECT_FAULT(COMPlusThrowOM(););
        }
        else {
            GC_NOTRIGGER;
            NOTHROW;
            FORBID_FAULT;
        }
        MODE_ANY;
        POSTCONDITION(CheckPointer(RETVAL, NULL_OK));
    }
    CONTRACT_END;

    AssemblyBinding *entry = (AssemblyBinding *) INVALIDENTRY;
    
    entry = LookupInternal(pSpec, fThrow);

    if (entry == (AssemblyBinding *) INVALIDENTRY)
        RETURN NULL;
    else
    {
        if ((entry->GetAssembly() == NULL) && fThrow)
        {
            // May be either unloaded, or an exception occurred.
            entry->ThrowIfError();
        }

        RETURN entry->GetAssembly();
    }
}

PEAssembly *AssemblySpecBindingCache::LookupFile(AssemblySpec *pSpec, BOOL fThrow /*=TRUE*/)
{
    CONTRACT(PEAssembly *)
    {
        INSTANCE_CHECK;
        if (fThrow) {
            GC_TRIGGERS;
            THROWS;
            INJECT_FAULT(COMPlusThrowOM(););
        }
        else {
            GC_NOTRIGGER;
            NOTHROW;
            FORBID_FAULT;
        }
        MODE_ANY;
        POSTCONDITION(CheckPointer(RETVAL, NULL_OK));
    }
    CONTRACT_END;

    AssemblyBinding *entry = (AssemblyBinding *) INVALIDENTRY;    
    entry = LookupInternal(pSpec, fThrow);
    
    if (entry == (AssemblyBinding *) INVALIDENTRY)
        RETURN NULL;
    else
    {
        if (fThrow && (entry->GetFile() == NULL))
        {
            CONSISTENCY_CHECK(entry->IsError());
            entry->ThrowIfError();
        }

        RETURN entry->GetFile();
    }
}


class AssemblyBindingHolder
{
public:
    AssemblyBindingHolder()
    {
        LIMITED_METHOD_CONTRACT;
        m_entry = NULL;
        m_pHeap = NULL;
    }

    AssemblySpecBindingCache::AssemblyBinding *CreateAssemblyBinding(LoaderHeap *pHeap)
    {
        CONTRACTL
        {
            THROWS;
            GC_TRIGGERS;
            INJECT_FAULT(COMPlusThrowOM(););
        }
        CONTRACTL_END

        m_pHeap = pHeap;
        if (pHeap)
        {
            m_entry = new (m_amTracker.Track(pHeap->AllocMem(S_SIZE_T(sizeof(AssemblySpecBindingCache::AssemblyBinding))))) AssemblySpecBindingCache::AssemblyBinding;
        }
        else
        {
            m_entry = new AssemblySpecBindingCache::AssemblyBinding;
        }
        return m_entry;
    }

    ~AssemblyBindingHolder()
    {
        CONTRACTL
        {
            NOTHROW;
            GC_TRIGGERS;
            FORBID_FAULT;
        }
        CONTRACTL_END

        if (m_entry)
        {
            if (m_pHeap)
            {
                // just call destructor - m_amTracker will delete the memory for m_entry itself.
                m_entry->~AssemblyBinding();
            }
            else
            {
                delete m_entry;
            }
        }
    }

    void SuppressRelease()
    {
        LIMITED_METHOD_CONTRACT;
        m_entry = NULL;
        m_pHeap = NULL;
        m_amTracker.SuppressRelease();
    }

    AllocMemTracker *GetPamTracker()
    {
        LIMITED_METHOD_CONTRACT;
        return &m_amTracker;
    }



private:
    AssemblySpecBindingCache::AssemblyBinding *m_entry;
    LoaderHeap                                *m_pHeap;
    AllocMemTracker                            m_amTracker;
};

// NOTE ABOUT STATE OF CACHE ENTRIES:
// 
// A cache entry can be in one of 4 states:
// 1. Empty (no entry)
// 2. File (a PEAssembly has been bound, but not yet an Assembly)
// 3. Assembly (Both a PEAssembly & Assembly are available.)
// 4. Error (an error has occurred)
//
// The legal state transitions are:
// 1 -> any
// 2 -> 3
// 2 -> 4


BOOL AssemblySpecBindingCache::StoreAssembly(AssemblySpec *pSpec, DomainAssembly *pAssembly)
{
    CONTRACT(BOOL)
    {
        INSTANCE_CHECK;
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
        // Host binder based assembly spec's cannot currently be safely inserted into caches.
        PRECONDITION(pSpec->GetHostBinder() == nullptr);
        POSTCONDITION(UnsafeContains(this, pSpec));
        POSTCONDITION(UnsafeVerifyLookupAssembly(this, pSpec, pAssembly));
        INJECT_FAULT(COMPlusThrowOM(););
    }
    CONTRACT_END;

    UPTR key = (UPTR)pSpec->Hash();

    // On CoreCLR, we will use the BinderID as the key 
    ICLRPrivBinder* pBinderContextForLookup = pAssembly->GetFile()->GetBindingContext();

    _ASSERTE(pBinderContextForLookup || pAssembly->GetFile()->IsSystem());
    if (pBinderContextForLookup)
    {
        UINT_PTR binderID = 0;
        HRESULT hr = pBinderContextForLookup->GetBinderID(&binderID);
        _ASSERTE(SUCCEEDED(hr));
        key = key^binderID;
        
        if (!pSpec->GetBindingContext())
        {
            pSpec->SetBindingContext(pBinderContextForLookup);
        }
    }

    AssemblyBinding *entry = (AssemblyBinding *) m_map.LookupValue(key, pSpec);

    if (entry == (AssemblyBinding *) INVALIDENTRY)
    {
        AssemblyBindingHolder abHolder;

        LoaderHeap* pHeap = m_pHeap;
        if (pAssembly->IsCollectible())
        {
            pHeap = pAssembly->GetLoaderAllocator()->GetHighFrequencyHeap();
        }

        entry = abHolder.CreateAssemblyBinding(pHeap);
        entry->Init(pSpec,pAssembly->GetFile(),pAssembly,NULL,pHeap, abHolder.GetPamTracker());

        m_map.InsertValue(key, entry);

        abHolder.SuppressRelease();

        STRESS_LOG2(LF_CLASSLOADER,LL_INFO10,"StoreFile (StoreAssembly): Add cached entry (%p) with PEFile %p",entry,pAssembly->GetFile());
        RETURN TRUE;
    }
    else
    {
        if (!entry->IsError())
        {
            if (entry->GetAssembly() != NULL)
            {
                // OK if this is a duplicate
                if (entry->GetAssembly() == pAssembly)
                    RETURN TRUE;
            }
            else
            {
                // OK if we have have a matching PEAssembly
                if (entry->GetFile() != NULL
                    && pAssembly->GetFile()->Equals(entry->GetFile()))
                {
                    entry->SetAssembly(pAssembly);
                    RETURN TRUE;
                }
            }
        }

        // Invalid cache transition (see above note about state transitions)
        RETURN FALSE;
    }
}

// Note that this routine may be called outside a lock, so may be racing with another thread. 
// Returns TRUE if add was successful - if FALSE is returned, caller should honor current
// cached value to ensure consistency.

BOOL AssemblySpecBindingCache::StoreFile(AssemblySpec *pSpec, PEAssembly *pFile)
{
    CONTRACT(BOOL)
    {
        INSTANCE_CHECK;
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
        // Host binder based assembly spec's cannot currently be safely inserted into caches.
        PRECONDITION(pSpec->GetHostBinder() == nullptr);
        POSTCONDITION((!RETVAL) || (UnsafeContains(this, pSpec) && UnsafeVerifyLookupFile(this, pSpec, pFile)));
        INJECT_FAULT(COMPlusThrowOM(););
    }
    CONTRACT_END;

    UPTR key = (UPTR)pSpec->Hash();

    // On CoreCLR, we will use the BinderID as the key 
    ICLRPrivBinder* pBinderContextForLookup = pFile->GetBindingContext();

    _ASSERTE(pBinderContextForLookup || pFile->IsSystem());
    if (pBinderContextForLookup)
    {
        UINT_PTR binderID = 0;
        HRESULT hr = pBinderContextForLookup->GetBinderID(&binderID);
        _ASSERTE(SUCCEEDED(hr));
        key = key^binderID;
        
        if (!pSpec->GetBindingContext())
        {
            pSpec->SetBindingContext(pBinderContextForLookup);
        }
    }

    AssemblyBinding *entry = (AssemblyBinding *) m_map.LookupValue(key, pSpec);

    if (entry == (AssemblyBinding *) INVALIDENTRY)
    {
        AssemblyBindingHolder abHolder;

        LoaderHeap* pHeap = m_pHeap;

#ifndef CROSSGEN_COMPILE
        if (pBinderContextForLookup != NULL)
        {
            LoaderAllocator* pLoaderAllocator = NULL;

            // Assemblies loaded with AssemblyLoadContext need to use a different heap if
            // marked as collectible
            if (SUCCEEDED(pBinderContextForLookup->GetLoaderAllocator((LPVOID*)&pLoaderAllocator)))
            {
                _ASSERTE(pLoaderAllocator != NULL);
                pHeap = pLoaderAllocator->GetHighFrequencyHeap();
            }
        }
#endif // !CROSSGEN_COMPILE

        entry = abHolder.CreateAssemblyBinding(pHeap);

        entry->Init(pSpec,pFile,NULL,NULL,pHeap, abHolder.GetPamTracker());

        m_map.InsertValue(key, entry);
        abHolder.SuppressRelease();

        STRESS_LOG2(LF_CLASSLOADER,LL_INFO10,"StoreFile: Add cached entry (%p) with PEFile %p\n", entry, pFile);

        RETURN TRUE;
    }
    else
    {
        if (!entry->IsError())
        {
            // OK if this is a duplicate
            if (entry->GetFile() != NULL
                && pFile->Equals(entry->GetFile()))
                RETURN TRUE;
        }
        else
        if (entry->IsPostBindError())
        {
            // Another thread has reported what's going to happen later. 
            entry->ThrowIfError();
            
        }
        STRESS_LOG2(LF_CLASSLOADER,LL_INFO10,"Incompatible cached entry found (%p) when adding PEFile %p\n", entry, pFile);
        // Invalid cache transition (see above note about state transitions)
        RETURN FALSE;
    }
}

BOOL AssemblySpecBindingCache::StoreException(AssemblySpec *pSpec, Exception* pEx)
{
    CONTRACT(BOOL)
    {
        INSTANCE_CHECK;
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
        // Host binder based assembly spec's cannot currently be safely inserted into caches.
        PRECONDITION(pSpec->GetHostBinder() == nullptr);
        DISABLED(POSTCONDITION(UnsafeContains(this, pSpec))); //<TODO>@todo: Getting violations here - StoreExceptions could happen anywhere so this is possibly too aggressive.</TODO>
        INJECT_FAULT(COMPlusThrowOM(););
    }
    CONTRACT_END;

    UPTR key = (UPTR)pSpec->Hash();

    AssemblyBinding *entry = LookupInternal(pSpec, TRUE);
    if (entry == (AssemblyBinding *) INVALIDENTRY)
    {
        // TODO: Merge this with the failure lookup in the binder
        //
        // Since no entry was found for this assembly in any binding context, save the failure
        // in the TPABinder context
        ICLRPrivBinder* pBinderToSaveException = NULL;
        pBinderToSaveException = pSpec->GetBindingContext();
        if (pBinderToSaveException == NULL)
        {
            if (!pSpec->IsAssemblySpecForMscorlib())
            {
                pBinderToSaveException = pSpec->GetBindingContextFromParentAssembly(pSpec->GetAppDomain());
                UINT_PTR binderID = 0;
                HRESULT hr = pBinderToSaveException->GetBinderID(&binderID);
                _ASSERTE(SUCCEEDED(hr));
                key = key^binderID;
            }
        }
    }

    if (entry == (AssemblyBinding *) INVALIDENTRY) {
        AssemblyBindingHolder abHolder;
        entry = abHolder.CreateAssemblyBinding(m_pHeap);

        entry->Init(pSpec,NULL,NULL,pEx,m_pHeap, abHolder.GetPamTracker());

        m_map.InsertValue(key, entry);
        abHolder.SuppressRelease();

        STRESS_LOG2(LF_CLASSLOADER,LL_INFO10,"StoreFile (StoreException): Add cached entry (%p) with exception %p",entry,pEx);
        RETURN TRUE;
    }
    else
    {
        // OK if this is a duplicate
        if (entry->IsError())
        {
            if (entry->GetHR() == pEx->GetHR())
                RETURN TRUE;
        }
        else
        {
            // OK to transition to error if we don't have an Assembly yet
            if (entry->GetAssembly() == NULL)
            {
                entry->InitException(pEx);
                RETURN TRUE;
            }
        }

        // Invalid cache transition (see above note about state transitions)
        RETURN FALSE;
    }
}

BOOL AssemblySpecBindingCache::RemoveAssembly(DomainAssembly* pAssembly)
{
    CONTRACT(BOOL)
    {
        INSTANCE_CHECK;
        NOTHROW;
        GC_TRIGGERS;
        MODE_ANY;
        PRECONDITION(pAssembly != NULL);
    }
    CONTRACT_END;
    BOOL result = FALSE;
    PtrHashMap::PtrIterator i = m_map.begin();
    while (!i.end())
    {
        AssemblyBinding* entry = (AssemblyBinding*)i.GetValue();
        if (entry->GetAssembly() == pAssembly)
        {
            UPTR key = i.GetKey();
            m_map.DeleteValue(key, entry);

            if (m_pHeap == NULL)
                delete entry;
            else
                entry->~AssemblyBinding();

            result = TRUE;
        }
        ++i;
    }

    RETURN result;
}

/* static */
BOOL AssemblySpecHash::CompareSpecs(UPTR u1, UPTR u2)
{
    // the same...
    WRAPPER_NO_CONTRACT;
    return AssemblySpecBindingCache::CompareSpecs(u1,u2);  
}

/* static */
BOOL AssemblySpecBindingCache::CompareSpecs(UPTR u1, UPTR u2)
{
    WRAPPER_NO_CONTRACT;
    AssemblySpec *a1 = (AssemblySpec *) (u1 << 1);
    AssemblySpec *a2 = (AssemblySpec *) u2;

    return a1->CompareEx(a2);
}

/* static */
BOOL DomainAssemblyCache::CompareBindingSpec(UPTR spec1, UPTR spec2)
{
    WRAPPER_NO_CONTRACT;

    AssemblySpec* pSpec1 = (AssemblySpec*) (spec1 << 1);
    AssemblyEntry* pEntry2 = (AssemblyEntry*) spec2;

    return pSpec1->CompareEx(&pEntry2->spec);
}

DomainAssemblyCache::AssemblyEntry* DomainAssemblyCache::LookupEntry(AssemblySpec* pSpec)
{
    CONTRACT (DomainAssemblyCache::AssemblyEntry*)
    {
        INSTANCE_CHECK;
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
        POSTCONDITION(CheckPointer(RETVAL, NULL_OK));
        INJECT_FAULT(COMPlusThrowOM(););
    }
    CONTRACT_END

    DWORD hashValue = pSpec->Hash();

    LPVOID pResult = m_Table.LookupValue(hashValue, pSpec);
    if(pResult == (LPVOID) INVALIDENTRY)
        RETURN NULL;
    else
        RETURN (AssemblyEntry*) pResult;
}

VOID DomainAssemblyCache::InsertEntry(AssemblySpec* pSpec, LPVOID pData1, LPVOID pData2/*=NULL*/)
{
    CONTRACTL
    {
        INSTANCE_CHECK;
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
        INJECT_FAULT(COMPlusThrowOM(););
    }
    CONTRACTL_END

    LPVOID ptr = LookupEntry(pSpec);
    if(ptr == NULL) {
        
        BaseDomain::CacheLockHolder lh(m_pDomain);

        ptr = LookupEntry(pSpec);
        if(ptr == NULL) {
            AllocMemTracker amTracker;
            AllocMemTracker *pamTracker = &amTracker;

            AssemblyEntry* pEntry = (AssemblyEntry*) pamTracker->Track( m_pDomain->GetLowFrequencyHeap()->AllocMem(S_SIZE_T(sizeof(AssemblyEntry))) );
            new (&pEntry->spec) AssemblySpec ();

            pEntry->spec.CopyFrom(pSpec);
            pEntry->spec.CloneFieldsToLoaderHeap(AssemblySpec::ALL_OWNED, m_pDomain->GetLowFrequencyHeap(), pamTracker);

            // Clear the parent assembly, it is not needed for the AssemblySpec in the cache entry and it could contain stale
            // pointer when the parent was a collectible assembly that was collected.
            pEntry->spec.SetParentAssembly(NULL);

            pEntry->pData[0] = pData1;
            pEntry->pData[1] = pData2;
            DWORD hashValue = pEntry->Hash();
            m_Table.InsertValue(hashValue, pEntry);

            pamTracker->SuppressRelease();
        }
        // lh goes out of scope here
    }
#ifdef _DEBUG
    else {
        _ASSERTE(pData1 == ((AssemblyEntry*) ptr)->pData[0]);
        _ASSERTE(pData2 == ((AssemblyEntry*) ptr)->pData[1]);
    }
#endif

}




DomainAssembly * AssemblySpec::GetParentAssembly()
{
    LIMITED_METHOD_CONTRACT;
    return m_pParentAssembly;
}