forked from dotnet/runtime
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenericdict.cpp
More file actions
1347 lines (1131 loc) · 53.6 KB
/
genericdict.cpp
File metadata and controls
1347 lines (1131 loc) · 53.6 KB
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//
// File: genericdict.cpp
//
//
// WARNING: Do NOT turn try to save dictionary slots except in the
// hardbind case. Saving further dictionary slots can lead
// to ComputeNeedsRestore returning TRUE for the dictionary and
// the associated method table (though of course only if some
// entries in the dictionary are prepopulated). However at
// earlier stages in the NGEN, code may have been compiled
// under the assumption that ComputeNeedsRestore was
// FALSE for the associated method table, and indeed this result
// may have been cached in the ComputeNeedsRestore
// for the MethodTable. Thus the combination of populating
// the dictionary and saving further dictionary slots could lead
// to inconsistencies and unsoundnesses in compilation.
//
//
// ============================================================================
#include "common.h"
#include "genericdict.h"
#include "typestring.h"
#include "field.h"
#include "typectxt.h"
#include "virtualcallstub.h"
#include "sigbuilder.h"
#include "dllimport.h"
#ifndef DACCESS_COMPILE
//---------------------------------------------------------------------------------------
//
//static
DictionaryLayout* DictionaryLayout::Allocate(WORD numSlots,
LoaderAllocator * pAllocator,
AllocMemTracker * pamTracker)
{
CONTRACT(DictionaryLayout*)
{
THROWS;
GC_NOTRIGGER;
INJECT_FAULT(COMPlusThrowOM(););
PRECONDITION(CheckPointer(pAllocator));
PRECONDITION(numSlots > 0);
POSTCONDITION(CheckPointer(RETVAL));
}
CONTRACT_END
S_SIZE_T bytes = S_SIZE_T(sizeof(DictionaryLayout)) + S_SIZE_T(sizeof(DictionaryEntryLayout)) * S_SIZE_T(numSlots-1);
TaggedMemAllocPtr ptr = pAllocator->GetLowFrequencyHeap()->AllocMem(bytes);
if (pamTracker != NULL)
pamTracker->Track(ptr);
DictionaryLayout * pD = (DictionaryLayout *)(void *)ptr;
// This is the number of slots excluding the type parameters
pD->m_numSlots = numSlots;
pD->m_numInitialSlots = numSlots;
RETURN pD;
}
#endif //!DACCESS_COMPILE
//---------------------------------------------------------------------------------------
//
// Total number of bytes for a dictionary with the specified layout (including optional back pointer
// used by expanded dictionaries). The pSlotSize argument is used to return the size
// to be stored in the size slot of the dictionary (not including the optional back pointer).
//
//static
DWORD
DictionaryLayout::GetDictionarySizeFromLayout(
DWORD numGenericArgs,
PTR_DictionaryLayout pDictLayout,
DWORD* pSlotSize)
{
LIMITED_METHOD_DAC_CONTRACT;
PRECONDITION(numGenericArgs > 0);
PRECONDITION(CheckPointer(pDictLayout, NULL_OK));
PRECONDITION(CheckPointer(pSlotSize));
DWORD slotBytes = numGenericArgs * sizeof(TypeHandle); // Slots for instantiation arguments
DWORD extraAllocBytes = 0;
if (pDictLayout != NULL)
{
DWORD numSlots = VolatileLoadWithoutBarrier(&pDictLayout->m_numSlots);
slotBytes += sizeof(TADDR); // Slot for dictionary size
slotBytes += numSlots * sizeof(TADDR); // Slots for dictionary slots based on a dictionary layout
if (numSlots > pDictLayout->m_numInitialSlots)
{
extraAllocBytes = sizeof(PTR_Dictionary); // Slot for the back-pointer in expanded dictionaries
}
}
*pSlotSize = slotBytes;
return slotBytes + extraAllocBytes;
}
#ifndef DACCESS_COMPILE
//---------------------------------------------------------------------------------------
//
// Find a token in the dictionary layout and return the offsets of indirections
// required to get to its slot in the actual dictionary
//
// NOTE: We will currently never return more than one indirection. We don't
// cascade dictionaries but we will record overflows in the dictionary layout
// (and cascade that accordingly) so we can prepopulate the overflow hash in
// reliability scenarios.
//
// Optimize the case of a token being !i (for class dictionaries) or !!i (for method dictionaries)
//
/* static */
BOOL DictionaryLayout::FindTokenWorker(LoaderAllocator* pAllocator,
DWORD numGenericArgs,
DictionaryLayout* pDictLayout,
SigBuilder* pSigBuilder,
BYTE* pSig,
DWORD cbSig,
int nFirstOffset,
DictionaryEntrySignatureSource signatureSource,
CORINFO_RUNTIME_LOOKUP* pResult,
WORD* pSlotOut,
DWORD scanFromSlot /* = 0 */,
BOOL useEmptySlotIfFound /* = FALSE */)
{
CONTRACTL
{
STANDARD_VM_CHECK;
PRECONDITION(numGenericArgs > 0);
PRECONDITION(scanFromSlot >= 0 && scanFromSlot <= pDictLayout->m_numSlots);
PRECONDITION(CheckPointer(pDictLayout));
PRECONDITION(CheckPointer(pResult) && CheckPointer(pSlotOut));
PRECONDITION(CheckPointer(pSig));
PRECONDITION((pSigBuilder == NULL && cbSig == -1) || (CheckPointer(pSigBuilder) && cbSig > 0));
}
CONTRACTL_END
// First slots contain the type parameters
_ASSERTE(FitsIn<WORD>(numGenericArgs + 1 + scanFromSlot));
WORD slot = static_cast<WORD>(numGenericArgs + 1 + scanFromSlot);
#if _DEBUG
if (scanFromSlot > 0)
{
_ASSERT(useEmptySlotIfFound);
for (DWORD iSlot = 0; iSlot < scanFromSlot; iSlot++)
{
// Verify that no entry before scanFromSlot matches the entry we're searching for
BYTE* pCandidate = (BYTE*)pDictLayout->m_slots[iSlot].m_signature;
if (pSigBuilder != NULL)
{
if (pDictLayout->m_slots[iSlot].m_signatureSource != FromReadyToRunImage)
{
DWORD j;
for (j = 0; j < cbSig; j++)
{
if (pCandidate[j] != pSig[j])
break;
}
_ASSERT(j != cbSig);
}
}
else
{
_ASSERT(pCandidate != pSig);
}
}
}
#endif
for (DWORD iSlot = scanFromSlot; iSlot < pDictLayout->m_numSlots; iSlot++)
{
BYTE* pCandidate = (BYTE*)pDictLayout->m_slots[iSlot].m_signature;
if (pCandidate != NULL)
{
bool signaturesMatch = false;
if (pSigBuilder != NULL)
{
// JIT case: compare signatures by comparing the bytes in them. We exclude
// any ReadyToRun signatures from the JIT case.
if (pDictLayout->m_slots[iSlot].m_signatureSource != FromReadyToRunImage)
{
// Compare the signatures. We do not need to worry about the size of pCandidate.
// As long as we are comparing one byte at a time we are guaranteed to not overrun.
DWORD j;
for (j = 0; j < cbSig; j++)
{
if (pCandidate[j] != pSig[j])
break;
}
signaturesMatch = (j == cbSig);
}
}
else
{
// ReadyToRun case: compare signatures by comparing their pointer values
signaturesMatch = (pCandidate == pSig);
}
// We've found it
if (signaturesMatch)
{
pResult->signature = pDictLayout->m_slots[iSlot].m_signature;
_ASSERTE(FitsIn<WORD>(nFirstOffset + 1));
pResult->indirections = static_cast<WORD>(nFirstOffset + 1);
pResult->offsets[nFirstOffset] = slot * sizeof(DictionaryEntry);
*pSlotOut = slot;
return TRUE;
}
}
// If we hit an empty slot then there's no more so use it
else
{
if (!useEmptySlotIfFound)
{
*pSlotOut = static_cast<WORD>(iSlot);
return FALSE;
}
// A lock should be taken by FindToken before being allowed to use an empty slot in the layout
_ASSERT(GetAppDomain()->GetGenericDictionaryExpansionLock()->OwnedByCurrentThread());
PVOID pResultSignature = pSigBuilder == NULL ? pSig : CreateSignatureWithSlotData(pSigBuilder, pAllocator, slot);
pDictLayout->m_slots[iSlot].m_signature = pResultSignature;
pDictLayout->m_slots[iSlot].m_signatureSource = signatureSource;
pResult->signature = pDictLayout->m_slots[iSlot].m_signature;
_ASSERTE(FitsIn<WORD>(nFirstOffset + 1));
pResult->indirections = static_cast<WORD>(nFirstOffset + 1);
pResult->offsets[nFirstOffset] = slot * sizeof(DictionaryEntry);
*pSlotOut = slot;
return TRUE;
}
slot++;
}
*pSlotOut = pDictLayout->m_numSlots;
return FALSE;
}
/* static */
DictionaryLayout* DictionaryLayout::ExpandDictionaryLayout(LoaderAllocator* pAllocator,
DictionaryLayout* pCurrentDictLayout,
DWORD numGenericArgs,
SigBuilder* pSigBuilder,
BYTE* pSig,
int nFirstOffset,
DictionaryEntrySignatureSource signatureSource,
CORINFO_RUNTIME_LOOKUP* pResult,
WORD* pSlotOut)
{
CONTRACTL
{
STANDARD_VM_CHECK;
INJECT_FAULT(ThrowOutOfMemory(););
PRECONDITION(GetAppDomain()->GetGenericDictionaryExpansionLock()->OwnedByCurrentThread());
PRECONDITION(CheckPointer(pResult) && CheckPointer(pSlotOut));
}
CONTRACTL_END
// There shouldn't be any empty slots remaining in the current dictionary.
_ASSERTE(pCurrentDictLayout->m_slots[pCurrentDictLayout->m_numSlots - 1].m_signature != NULL);
#ifdef _DEBUG
// Stress debug mode by increasing size by only 1 slot for the first 10 slots.
DWORD newSize = pCurrentDictLayout->m_numSlots > 10 ? ((DWORD)pCurrentDictLayout->m_numSlots) * 2 : pCurrentDictLayout->m_numSlots + 1;
#else
DWORD newSize = ((DWORD)pCurrentDictLayout->m_numSlots) * 2;
#endif
if (!FitsIn<WORD>(newSize + static_cast<WORD>(numGenericArgs)))
return NULL;
DictionaryLayout* pNewDictionaryLayout = Allocate((WORD)newSize, pAllocator, NULL);
pNewDictionaryLayout->m_numInitialSlots = pCurrentDictLayout->m_numInitialSlots;
for (DWORD iSlot = 0; iSlot < pCurrentDictLayout->m_numSlots; iSlot++)
pNewDictionaryLayout->m_slots[iSlot] = pCurrentDictLayout->m_slots[iSlot];
WORD layoutSlotIndex = pCurrentDictLayout->m_numSlots;
WORD slot = static_cast<WORD>(numGenericArgs) + 1 + layoutSlotIndex;
PVOID pResultSignature = pSigBuilder == NULL ? pSig : CreateSignatureWithSlotData(pSigBuilder, pAllocator, slot);
pNewDictionaryLayout->m_slots[layoutSlotIndex].m_signature = pResultSignature;
pNewDictionaryLayout->m_slots[layoutSlotIndex].m_signatureSource = signatureSource;
pResult->signature = pNewDictionaryLayout->m_slots[layoutSlotIndex].m_signature;
_ASSERTE(FitsIn<WORD>(nFirstOffset + 1));
pResult->indirections = static_cast<WORD>(nFirstOffset + 1);
pResult->offsets[nFirstOffset] = slot * sizeof(DictionaryEntry);
*pSlotOut = slot;
return pNewDictionaryLayout;
}
/* static */
BOOL DictionaryLayout::FindToken(MethodTable* pMT,
LoaderAllocator* pAllocator,
int nFirstOffset,
SigBuilder* pSigBuilder,
BYTE* pSig,
DictionaryEntrySignatureSource signatureSource,
CORINFO_RUNTIME_LOOKUP* pResult,
WORD* pSlotOut)
{
CONTRACTL
{
STANDARD_VM_CHECK;
PRECONDITION(CheckPointer(pMT));
PRECONDITION(CheckPointer(pAllocator));
PRECONDITION(CheckPointer(pResult));
PRECONDITION(pMT->HasInstantiation());
}
CONTRACTL_END;
DWORD cbSig = -1;
pSig = pSigBuilder != NULL ? (BYTE*)pSigBuilder->GetSignature(&cbSig) : pSig;
if (FindTokenWorker(pAllocator, pMT->GetNumGenericArgs(), pMT->GetClass()->GetDictionaryLayout(), pSigBuilder, pSig, cbSig, nFirstOffset, signatureSource, pResult, pSlotOut, 0, FALSE))
return TRUE;
CrstHolder ch(GetAppDomain()->GetGenericDictionaryExpansionLock());
{
// Try again under lock in case another thread already expanded the dictionaries or filled an empty slot
if (FindTokenWorker(pMT->GetLoaderAllocator(), pMT->GetNumGenericArgs(), pMT->GetClass()->GetDictionaryLayout(), pSigBuilder, pSig, cbSig, nFirstOffset, signatureSource, pResult, pSlotOut, *pSlotOut, TRUE))
return TRUE;
DictionaryLayout* pOldLayout = pMT->GetClass()->GetDictionaryLayout();
DictionaryLayout* pNewLayout = ExpandDictionaryLayout(pAllocator, pOldLayout, pMT->GetNumGenericArgs(), pSigBuilder, pSig, nFirstOffset, signatureSource, pResult, pSlotOut);
if (pNewLayout == NULL)
{
pResult->signature = pSigBuilder == NULL ? pSig : CreateSignatureWithSlotData(pSigBuilder, pAllocator, 0);
return FALSE;
}
// Update the dictionary layout pointer. Note that the expansion of the dictionaries of all instantiated types using this layout
// is done lazily, whenever we attempt to access a slot that is beyond the size of the existing dictionary on that type.
pMT->GetClass()->SetDictionaryLayout(pNewLayout);
return TRUE;
}
}
/* static */
BOOL DictionaryLayout::FindToken(MethodDesc* pMD,
LoaderAllocator* pAllocator,
int nFirstOffset,
SigBuilder* pSigBuilder,
BYTE* pSig,
DictionaryEntrySignatureSource signatureSource,
CORINFO_RUNTIME_LOOKUP* pResult,
WORD* pSlotOut)
{
CONTRACTL
{
STANDARD_VM_CHECK;
PRECONDITION(CheckPointer(pMD));
PRECONDITION(CheckPointer(pAllocator));
PRECONDITION(CheckPointer(pResult));
PRECONDITION(pMD->HasMethodInstantiation());
}
CONTRACTL_END;
DWORD cbSig = -1;
pSig = pSigBuilder != NULL ? (BYTE*)pSigBuilder->GetSignature(&cbSig) : pSig;
if (FindTokenWorker(pAllocator, pMD->GetNumGenericMethodArgs(), pMD->GetDictionaryLayout(), pSigBuilder, pSig, cbSig, nFirstOffset, signatureSource, pResult, pSlotOut, 0, FALSE))
return TRUE;
CrstHolder ch(GetAppDomain()->GetGenericDictionaryExpansionLock());
{
// Try again under lock in case another thread already expanded the dictionaries or filled an empty slot
if (FindTokenWorker(pAllocator, pMD->GetNumGenericMethodArgs(), pMD->GetDictionaryLayout(), pSigBuilder, pSig, cbSig, nFirstOffset, signatureSource, pResult, pSlotOut, *pSlotOut, TRUE))
return TRUE;
DictionaryLayout* pOldLayout = pMD->GetDictionaryLayout();
DictionaryLayout* pNewLayout = ExpandDictionaryLayout(pAllocator, pOldLayout, pMD->GetNumGenericMethodArgs(), pSigBuilder, pSig, nFirstOffset, signatureSource, pResult, pSlotOut);
if (pNewLayout == NULL)
{
pResult->signature = pSigBuilder == NULL ? pSig : CreateSignatureWithSlotData(pSigBuilder, pAllocator, 0);
return FALSE;
}
// Update the dictionary layout pointer. Note that the expansion of the dictionaries of all instantiated methods using this layout
// is done lazily, whenever we attempt to access a slot that is beyond the size of the existing dictionary on that method.
pMD->AsInstantiatedMethodDesc()->IMD_SetDictionaryLayout(pNewLayout);
return TRUE;
}
}
/* static */
PVOID DictionaryLayout::CreateSignatureWithSlotData(SigBuilder* pSigBuilder, LoaderAllocator* pAllocator, WORD slot)
{
CONTRACTL
{
STANDARD_VM_CHECK;
PRECONDITION(CheckPointer(pSigBuilder) && CheckPointer(pAllocator));
}
CONTRACTL_END
pSigBuilder->AppendData(slot);
DWORD cbNewSig;
PVOID pNewSig = pSigBuilder->GetSignature(&cbNewSig);
PVOID pResultSignature = pAllocator->GetLowFrequencyHeap()->AllocMem(S_SIZE_T(cbNewSig));
_ASSERT(pResultSignature != NULL);
memcpy(pResultSignature, pNewSig, cbNewSig);
return pResultSignature;
}
#endif //!DACCESS_COMPILE
//---------------------------------------------------------------------------------------
//
DWORD DictionaryLayout::GetMaxSlots()
{
LIMITED_METHOD_CONTRACT;
return m_numSlots;
}
DWORD DictionaryLayout::GetNumInitialSlots()
{
LIMITED_METHOD_CONTRACT;
return m_numInitialSlots;
}
//---------------------------------------------------------------------------------------
//
DWORD
DictionaryLayout::GetNumUsedSlots()
{
LIMITED_METHOD_CONTRACT;
DWORD numUsedSlots = 0;
for (DWORD i = 0; i < m_numSlots; i++)
{
if (GetEntryLayout(i)->m_signature != NULL)
numUsedSlots++;
}
return numUsedSlots;
}
//---------------------------------------------------------------------------------------
//
DictionaryEntryKind
DictionaryEntryLayout::GetKind()
{
STANDARD_VM_CONTRACT;
if (m_signature == NULL)
return EmptySlot;
SigPointer ptr((PCCOR_SIGNATURE)dac_cast<TADDR>(m_signature));
uint32_t kind; // DictionaryEntryKind
IfFailThrow(ptr.GetData(&kind));
return (DictionaryEntryKind)kind;
}
#ifndef DACCESS_COMPILE
Dictionary* Dictionary::GetMethodDictionaryWithSizeCheck(MethodDesc* pMD, ULONG slotIndex)
{
CONTRACT(Dictionary*)
{
THROWS;
GC_TRIGGERS;
POSTCONDITION(CheckPointer(RETVAL));
}
CONTRACT_END;
DWORD numGenericArgs = pMD->GetNumGenericMethodArgs();
Dictionary* pDictionary = pMD->GetMethodDictionary();
DWORD currentDictionarySize = pDictionary->GetDictionarySlotsSize(numGenericArgs);
if (currentDictionarySize <= (slotIndex * sizeof(DictionaryEntry)))
{
// Only expand the dictionary if the current slot we're trying to use is beyond the size of the dictionary
// Take lock and check for size again, just in case another thread already resized the dictionary
CrstHolder ch(GetAppDomain()->GetGenericDictionaryExpansionLock());
pDictionary = pMD->GetMethodDictionary();
currentDictionarySize = pDictionary->GetDictionarySlotsSize(numGenericArgs);
if (currentDictionarySize <= (slotIndex * sizeof(DictionaryEntry)))
{
DictionaryLayout* pDictLayout = pMD->GetDictionaryLayout();
InstantiatedMethodDesc* pIMD = pMD->AsInstantiatedMethodDesc();
_ASSERTE(pDictLayout != NULL && pDictLayout->GetMaxSlots() > 0);
DWORD expectedDictionarySlotSize;
DWORD expectedDictionaryAllocSize = DictionaryLayout::GetDictionarySizeFromLayout(numGenericArgs, pDictLayout, &expectedDictionarySlotSize);
_ASSERT(currentDictionarySize < expectedDictionarySlotSize);
Dictionary* pNewDictionary = (Dictionary*)(void*)pIMD->GetLoaderAllocator()->GetHighFrequencyHeap()->AllocMem(S_SIZE_T(expectedDictionaryAllocSize));
// Copy old dictionary entry contents
for (DWORD i = 0; i < currentDictionarySize / sizeof(DictionaryEntry); i++)
{
// Use VolatileLoadWithoutBarrier to ensure that the compiler won't turn this into memcpy that is not guaranteed to copy pointers atomically
*((DictionaryEntry*)pNewDictionary + i) = VolatileLoadWithoutBarrier((DictionaryEntry*)pDictionary + i);
}
DWORD* pSizeSlot = (DWORD*)(pNewDictionary + numGenericArgs);
*pSizeSlot = expectedDictionarySlotSize;
*pNewDictionary->GetBackPointerSlot(numGenericArgs) = pDictionary;
// Publish the new dictionary slots to the type.
InterlockedExchangeT(&pIMD->m_pPerInstInfo, pNewDictionary);
pDictionary = pNewDictionary;
}
}
RETURN pDictionary;
}
Dictionary* Dictionary::GetTypeDictionaryWithSizeCheck(MethodTable* pMT, ULONG slotIndex)
{
CONTRACT(Dictionary*)
{
THROWS;
GC_TRIGGERS;
POSTCONDITION(CheckPointer(RETVAL));
}
CONTRACT_END;
DWORD numGenericArgs = pMT->GetNumGenericArgs();
Dictionary* pDictionary = pMT->GetDictionary();
DWORD currentDictionarySize = pDictionary->GetDictionarySlotsSize(numGenericArgs);
if (currentDictionarySize <= (slotIndex * sizeof(DictionaryEntry)))
{
// Only expand the dictionary if the current slot we're trying to use is beyond the size of the dictionary
// Take lock and check for size again, just in case another thread already resized the dictionary
CrstHolder ch(GetAppDomain()->GetGenericDictionaryExpansionLock());
pDictionary = pMT->GetDictionary();
currentDictionarySize = pDictionary->GetDictionarySlotsSize(numGenericArgs);
if (currentDictionarySize <= (slotIndex * sizeof(DictionaryEntry)))
{
DictionaryLayout* pDictLayout = pMT->GetClass()->GetDictionaryLayout();
_ASSERTE(pDictLayout != NULL && pDictLayout->GetMaxSlots() > 0);
DWORD expectedDictionarySlotSize;
DWORD expectedDictionaryAllocSize = DictionaryLayout::GetDictionarySizeFromLayout(numGenericArgs, pDictLayout, &expectedDictionarySlotSize);
_ASSERT(currentDictionarySize < expectedDictionarySlotSize);
// Expand type dictionary
Dictionary* pNewDictionary = (Dictionary*)(void*)pMT->GetLoaderAllocator()->GetHighFrequencyHeap()->AllocMem(S_SIZE_T(expectedDictionaryAllocSize));
// Copy old dictionary entry contents
for (DWORD i = 0; i < currentDictionarySize / sizeof(DictionaryEntry); i++)
{
// Use VolatileLoadWithoutBarrier to ensure that the compiler won't turn this into memcpy that is not guaranteed to copy pointers atomically
*((DictionaryEntry*)pNewDictionary + i) = VolatileLoadWithoutBarrier((DictionaryEntry*)pDictionary + i);
}
DWORD* pSizeSlot = (DWORD*)(pNewDictionary + numGenericArgs);
*pSizeSlot = expectedDictionarySlotSize;
*pNewDictionary->GetBackPointerSlot(numGenericArgs) = pDictionary;
// Publish the new dictionary slots to the type.
ULONG dictionaryIndex = pMT->GetNumDicts() - 1;
Dictionary** pPerInstInfo = pMT->GetPerInstInfo();
InterlockedExchangeT(pPerInstInfo + dictionaryIndex, pNewDictionary);
pDictionary = pNewDictionary;
}
}
RETURN pDictionary;
}
struct StaticVirtualDispatchHashBlob : public ILStubHashBlobBase
{
MethodDesc *pExactInterfaceMethod;
MethodTable *pTargetMT;
};
PCODE CreateStubForStaticVirtualDispatch(MethodTable* pTargetMT, MethodTable* pInterfaceMT, MethodDesc *pInterfaceMD)
{
GCX_PREEMP();
Module* pLoaderModule = ClassLoader::ComputeLoaderModule(pTargetMT, 0, pInterfaceMD->GetMethodInstantiation());
MethodDesc *pExactMD = MethodDesc::FindOrCreateAssociatedMethodDesc(
pInterfaceMD,
pInterfaceMT,
FALSE, // forceBoxedEntryPoint
pInterfaceMD->GetMethodInstantiation(), // methodInst
FALSE, // allowInstParam
TRUE); // forceRemotableMethod
StaticVirtualDispatchHashBlob hashBlob;
memset(&hashBlob, 0, sizeof(hashBlob));
hashBlob.pExactInterfaceMethod = pExactMD;
hashBlob.pTargetMT = pTargetMT;
hashBlob.m_cbSizeOfBlob = sizeof(hashBlob);
ILStubHashBlob *pHashBlob = (ILStubHashBlob*)&hashBlob;
MethodDesc *pStubMD = pLoaderModule->GetILStubCache()->LookupStubMethodDesc(pHashBlob);
if (pStubMD == NULL)
{
SigTypeContext context(pExactMD);
ILStubLinker sl(pExactMD->GetModule(), pExactMD->GetSignature(), &context, pExactMD, ILSTUB_LINKER_FLAG_NONE);
MetaSig sig(pInterfaceMD);
ILCodeStream *pCode = sl.NewCodeStream(ILStubLinker::kDispatch);
UINT paramCount = 0;
BOOL fReturnVal = !sig.IsReturnTypeVoid();
while(paramCount < sig.NumFixedArgs())
pCode->EmitLDARG(paramCount++);
pCode->EmitCONSTRAINED(pCode->GetToken(pTargetMT));
pCode->EmitCALL(pCode->GetToken(pInterfaceMD), sig.NumFixedArgs(), fReturnVal);
pCode->EmitRET();
PCCOR_SIGNATURE pSig;
DWORD cbSig;
pInterfaceMD->GetSig(&pSig,&cbSig);
pStubMD = ILStubCache::CreateAndLinkNewILStubMethodDesc(pLoaderModule->GetLoaderAllocator(),
pLoaderModule->GetILStubCache()->GetOrCreateStubMethodTable(pLoaderModule),
ILSTUB_STATIC_VIRTUAL_DISPATCH_STUB,
pInterfaceMD->GetModule(),
pSig, cbSig,
&context,
&sl);
pStubMD = pLoaderModule->GetILStubCache()->InsertStubMethodDesc(pStubMD, pHashBlob);
}
return JitILStub(pStubMD);
}
//---------------------------------------------------------------------------------------
//
DictionaryEntry
Dictionary::PopulateEntry(
MethodDesc * pMD,
MethodTable * pMT,
LPVOID signature,
BOOL nonExpansive,
DictionaryEntry ** ppSlot,
DWORD dictionaryIndexAndSlot, /* = -1 */
Module * pModule /* = NULL */)
{
CONTRACTL {
THROWS;
GC_TRIGGERS;
} CONTRACTL_END;
CORINFO_GENERIC_HANDLE result = NULL;
*ppSlot = NULL;
bool isReadyToRunModule = (pModule != NULL && pModule->IsReadyToRun());
ZapSig::Context zapSigContext(NULL, NULL, ZapSig::NormalTokens);
ZapSig::Context * pZapSigContext = NULL;
uint32_t kind = DictionaryEntryKind::EmptySlot;
SigPointer ptr((PCCOR_SIGNATURE)signature);
if (isReadyToRunModule)
{
PCCOR_SIGNATURE pBlob = (PCCOR_SIGNATURE)signature;
BYTE fixupKind = *pBlob++;
ModuleBase * pInfoModule = pModule;
if (fixupKind & READYTORUN_FIXUP_ModuleOverride)
{
DWORD moduleIndex = CorSigUncompressData(pBlob);
pInfoModule = pModule->GetModuleFromIndex(moduleIndex);
fixupKind &= ~READYTORUN_FIXUP_ModuleOverride;
}
_ASSERTE(fixupKind == READYTORUN_FIXUP_ThisObjDictionaryLookup ||
fixupKind == READYTORUN_FIXUP_TypeDictionaryLookup ||
fixupKind == READYTORUN_FIXUP_MethodDictionaryLookup);
if (fixupKind == READYTORUN_FIXUP_ThisObjDictionaryLookup)
{
SigPointer p(pBlob);
p.SkipExactlyOne();
pBlob = p.GetPtr();
}
ReadyToRunFixupKind signatureKind = (ReadyToRunFixupKind)*pBlob++;
if (signatureKind & READYTORUN_FIXUP_ModuleOverride)
{
DWORD moduleIndex = CorSigUncompressData(pBlob);
ModuleBase * pSignatureModule = pModule->GetModuleFromIndex(moduleIndex);
if (pInfoModule == pModule)
{
pInfoModule = pSignatureModule;
}
_ASSERTE(pInfoModule == pSignatureModule);
signatureKind = (ReadyToRunFixupKind)(signatureKind & ~READYTORUN_FIXUP_ModuleOverride);
}
switch (signatureKind)
{
case READYTORUN_FIXUP_DeclaringTypeHandle: kind = DeclaringTypeHandleSlot; break;
case READYTORUN_FIXUP_TypeHandle: kind = TypeHandleSlot; break;
case READYTORUN_FIXUP_FieldHandle: kind = FieldDescSlot; break;
case READYTORUN_FIXUP_MethodHandle: kind = MethodDescSlot; break;
case READYTORUN_FIXUP_MethodEntry: kind = MethodEntrySlot; break;
case READYTORUN_FIXUP_VirtualEntry: kind = DispatchStubAddrSlot; break;
default:
_ASSERTE(!"Unexpected ReadyToRunFixupKind");
ThrowHR(COR_E_BADIMAGEFORMAT);
}
ptr = SigPointer(pBlob);
zapSigContext = ZapSig::Context(pInfoModule, pModule, ZapSig::NormalTokens);
pZapSigContext = &zapSigContext;
}
else
{
ptr = SigPointer((PCCOR_SIGNATURE)signature);
IfFailThrow(ptr.GetData(&kind));
pZapSigContext = NULL;
}
ModuleBase * pLookupModule = (isReadyToRunModule) ? pZapSigContext->pInfoModule : CoreLibBinder::GetModule();
if (pMT != NULL)
{
// We need to normalize the class passed in (if any) for reliability purposes. That's because preparation of a code region that
// contains these handle lookups depends on being able to predict exactly which lookups are required (so we can pre-cache the
// answers and remove any possibility of failure at runtime). This is hard to do if the lookup (in this case the lookup of the
// dictionary overflow cache) is keyed off the somewhat arbitrary type of the instance on which the call is made (we'd need to
// prepare for every possible derived type of the type containing the method). So instead we have to locate the exactly
// instantiated (non-shared) super-type of the class passed in.
uint32_t dictionaryIndex = 0;
if (isReadyToRunModule)
{
dictionaryIndex = dictionaryIndexAndSlot >> 16;
}
else
{
IfFailThrow(ptr.GetData(&dictionaryIndex));
}
#if _DEBUG
// Lock is needed because dictionary pointers can get updated during dictionary size expansion
CrstHolder ch(GetAppDomain()->GetGenericDictionaryExpansionLock());
// MethodTable is expected to be normalized
Dictionary* pDictionary = pMT->GetDictionary();
_ASSERTE(pDictionary == pMT->GetPerInstInfo()[dictionaryIndex]);
#endif
}
{
SigTypeContext typeContext;
if (pMT != NULL)
{
SigTypeContext::InitTypeContext(pMT, &typeContext);
}
else
{
SigTypeContext::InitTypeContext(pMD, &typeContext);
}
TypeHandle constraintType;
TypeHandle declaringType;
switch (kind)
{
case DeclaringTypeHandleSlot:
{
declaringType = ptr.GetTypeHandleThrowing(
pLookupModule,
&typeContext,
(nonExpansive ? ClassLoader::DontLoadTypes : ClassLoader::LoadTypes),
CLASS_LOADED,
FALSE,
NULL,
pZapSigContext);
if (declaringType.IsNull())
{
_ASSERTE(nonExpansive);
return NULL;
}
IfFailThrow(ptr.SkipExactlyOne());
FALLTHROUGH;
}
case TypeHandleSlot:
{
TypeHandle th = ptr.GetTypeHandleThrowing(
pLookupModule,
&typeContext,
(nonExpansive ? ClassLoader::DontLoadTypes : ClassLoader::LoadTypes),
CLASS_LOADED,
FALSE,
NULL,
pZapSigContext);
if (th.IsNull())
{
_ASSERTE(nonExpansive);
return NULL;
}
IfFailThrow(ptr.SkipExactlyOne());
if (!declaringType.IsNull())
{
th = th.GetMethodTable()->GetMethodTableMatchingParentClass(declaringType.AsMethodTable());
}
PTR_MethodTable pMT = th.IsByRef() ? th.GetTypeParam().GetMethodTable() : th.GetMethodTable();
pMT->EnsureInstanceActive();
result = (CORINFO_GENERIC_HANDLE)th.AsPtr();
break;
}
case ConstrainedMethodEntrySlot:
{
constraintType = ptr.GetTypeHandleThrowing(
pLookupModule,
&typeContext,
(nonExpansive ? ClassLoader::DontLoadTypes : ClassLoader::LoadTypes),
CLASS_LOADED,
FALSE,
NULL,
pZapSigContext);
if (constraintType.IsNull())
{
_ASSERTE(nonExpansive);
return NULL;
}
IfFailThrow(ptr.SkipExactlyOne());
FALLTHROUGH;
}
case MethodDescSlot:
case DispatchStubAddrSlot:
case MethodEntrySlot:
{
TypeHandle ownerType;
MethodTable * pOwnerMT = NULL;
MethodDesc * pMethod = NULL;
uint32_t methodFlags = 0;
BOOL isInstantiatingStub = 0;
BOOL isUnboxingStub = 0;
BOOL fMethodNeedsInstantiation = 0;
uint32_t methodSlot = -1;
BOOL fRequiresDispatchStub = 0;
BOOL isAsyncVariant = 0;
if (isReadyToRunModule)
{
IfFailThrow(ptr.GetData(&methodFlags));
if (methodFlags & ENCODE_METHOD_SIG_Constrained)
kind = ConstrainedMethodEntrySlot;
isInstantiatingStub = ((methodFlags & ENCODE_METHOD_SIG_InstantiatingStub) != 0) || (kind == MethodEntrySlot);
isUnboxingStub = ((methodFlags & ENCODE_METHOD_SIG_UnboxingStub) != 0);
fMethodNeedsInstantiation = ((methodFlags & ENCODE_METHOD_SIG_MethodInstantiation) != 0);
isAsyncVariant = ((methodFlags & ENCODE_METHOD_SIG_AsyncVariant) != 0);
if (methodFlags & ENCODE_METHOD_SIG_OwnerType)
{
ownerType = ptr.GetTypeHandleThrowing(
pZapSigContext->pInfoModule,
&typeContext,
ClassLoader::LoadTypes,
CLASS_LOADED,
FALSE,
NULL,
pZapSigContext);
IfFailThrow(ptr.SkipExactlyOne());
}
if (methodFlags & ENCODE_METHOD_SIG_SlotInsteadOfToken)
{
// get the method desc using slot number
IfFailThrow(ptr.GetData(&methodSlot));
_ASSERTE(!ownerType.IsNull());
pMethod = ownerType.GetMethodTable()->GetMethodDescForSlot(methodSlot);
}
else
{
//
// decode method token
//
RID rid;
IfFailThrow(ptr.GetData(&rid));
if (methodFlags & ENCODE_METHOD_SIG_MemberRefToken)
{
if (ownerType.IsNull())
{
FieldDesc * pFDDummy = NULL;
MemberLoader::GetDescFromMemberRef(pZapSigContext->pInfoModule, TokenFromRid(rid, mdtMemberRef), &pMethod, &pFDDummy, NULL, FALSE, &ownerType);
_ASSERTE(pMethod != NULL && pFDDummy == NULL);
}
else
{
pMethod = MemberLoader::GetMethodDescFromMemberRefAndType(pZapSigContext->pInfoModule, TokenFromRid(rid, mdtMemberRef), ownerType.GetMethodTable());
}
}
else
{
_ASSERTE(pZapSigContext->pInfoModule->IsFullModule());
pMethod = MemberLoader::GetMethodDescFromMethodDef(static_cast<Module*>(pZapSigContext->pInfoModule), TokenFromRid(rid, mdtMethodDef), FALSE);
}
if (isAsyncVariant)
{
pMethod = pMethod->GetAsyncVariant();
}
}
if (ownerType.IsNull())
ownerType = pMethod->GetMethodTable();
_ASSERT(!ownerType.IsNull() && !nonExpansive);
pOwnerMT = ownerType.GetMethodTable();
if (kind == DispatchStubAddrSlot && pMethod->IsVtableMethod())
{
fRequiresDispatchStub = TRUE;
methodSlot = pMethod->GetSlot();
}
}
else
{
ownerType = ptr.GetTypeHandleThrowing(
pLookupModule,
&typeContext,
(nonExpansive ? ClassLoader::DontLoadTypes : ClassLoader::LoadTypes),
CLASS_LOADED,
FALSE,
NULL,
pZapSigContext);
if (ownerType.IsNull())
{
_ASSERTE(nonExpansive);
return NULL;
}
IfFailThrow(ptr.SkipExactlyOne());
// <NICE> wsperf: Create a path that doesn't load types or create new handles if nonExpansive is set </NICE>
if (nonExpansive)
return NULL;
pOwnerMT = ownerType.IsByRef() ? ownerType.GetTypeParam().GetMethodTable() : ownerType.GetMethodTable();
_ASSERTE(pOwnerMT != NULL);
IfFailThrow(ptr.GetData(&methodFlags));