summaryrefslogtreecommitdiff
path: root/src/vm/instmethhash.cpp
blob: 560e9554be358dfa451f425ab53d0934af06034e (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
// 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.
//
// File: instmethhash.cpp
//


//

//
// ============================================================================

#include "common.h"
#include "excep.h"
#include "instmethhash.h"
#include "eeconfig.h"
#include "generics.h"
#include "typestring.h"
#ifdef FEATURE_PREJIT
#include "zapsig.h"
#include "compile.h"
#endif
#include "ngenhash.inl"

PTR_MethodDesc InstMethodHashEntry::GetMethod()
{
    LIMITED_METHOD_DAC_CONTRACT;

    return dac_cast<PTR_MethodDesc>(dac_cast<TADDR>(data) & ~0x3);
}

DWORD InstMethodHashEntry::GetFlags()
{
    LIMITED_METHOD_DAC_CONTRACT;

    return (DWORD)(dac_cast<TADDR>(data) & 0x3);
}

#ifndef DACCESS_COMPILE

void InstMethodHashEntry::SetMethodAndFlags(MethodDesc *pMethod, DWORD dwFlags)
{
    LIMITED_METHOD_CONTRACT;

    _ASSERTE(dwFlags <= 0x3);
    _ASSERTE(((TADDR)pMethod & 0x3) == 0);

    data = (MethodDesc*)((TADDR)pMethod | dwFlags);
}

// ============================================================================
// Instantiated method hash table methods
// ============================================================================
/* static */ InstMethodHashTable *InstMethodHashTable::Create(LoaderAllocator *pAllocator, Module *pModule, DWORD dwNumBuckets, AllocMemTracker *pamTracker)
{
    CONTRACTL
    {
        THROWS;
        GC_NOTRIGGER;
        INJECT_FAULT(COMPlusThrowOM(););
    }
    CONTRACTL_END

    LoaderHeap *pHeap = pAllocator->GetLowFrequencyHeap();
    InstMethodHashTable *pThis = (InstMethodHashTable*)pamTracker->Track(pHeap->AllocMem((S_SIZE_T)sizeof(InstMethodHashTable)));

    new (pThis) InstMethodHashTable(pModule, pHeap, dwNumBuckets);

#ifdef _DEBUG
    pThis->InitUnseal();
#endif

    pThis->m_pLoaderAllocator = pAllocator;

    return pThis;
}

PTR_LoaderAllocator InstMethodHashTable::GetLoaderAllocator()
{
    WRAPPER_NO_CONTRACT;

    if (m_pLoaderAllocator)
    {
        return m_pLoaderAllocator;
    }
    else
    {
        _ASSERTE(!m_pModule.IsNull());
        return GetModule()->GetLoaderAllocator();
    }
}


// Calculate a hash value for a method-desc key
static DWORD Hash(TypeHandle declaringType, mdMethodDef token, Instantiation inst)
{
    STATIC_CONTRACT_NOTHROW;
    STATIC_CONTRACT_GC_NOTRIGGER;
    STATIC_CONTRACT_FORBID_FAULT;

    DWORD dwHash = 0x87654321;
#define INST_HASH_ADD(_value) dwHash = ((dwHash << 5) + dwHash) ^ (_value)

    INST_HASH_ADD(declaringType.GetCl());
    INST_HASH_ADD(token);

    for (DWORD i = 0; i < inst.GetNumArgs(); i++)
    {
        TypeHandle thArg = inst[i];

        if (thArg.GetMethodTable())
        {
            INST_HASH_ADD(thArg.GetCl());

            Instantiation sArgInst = thArg.GetInstantiation();
            for (DWORD j = 0; j < sArgInst.GetNumArgs(); j++)
            {
                TypeHandle thSubArg = sArgInst[j];
                if (thSubArg.GetMethodTable())
                    INST_HASH_ADD(thSubArg.GetCl());
                else
                    INST_HASH_ADD(thSubArg.GetSignatureCorElementType());
            }
        }
        else
            INST_HASH_ADD(thArg.GetSignatureCorElementType());
    }

    return dwHash;
}

MethodDesc* InstMethodHashTable::FindMethodDesc(TypeHandle declaringType, 
                                                mdMethodDef token, 
                                                BOOL unboxingStub, 
                                                Instantiation inst,
                                                BOOL getSharedNotStub)
{ 
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        FORBID_FAULT;
        PRECONDITION(CheckPointer(declaringType));
    }
    CONTRACTL_END

        // We temporarily disable IBC logging here
        // because the pMD that we search through may not be restored
        // and ComputePrefferedZapModule will assert on finding an
        // encode fixup pointer
        // 
        IBCLoggingDisabler disableIbcLogging;

    MethodDesc *pMDResult = NULL;

    DWORD dwHash = Hash(declaringType, token, inst);
    InstMethodHashEntry_t* pSearch;
    LookupContext sContext;

    for (pSearch = BaseFindFirstEntryByHash(dwHash, &sContext);
         pSearch != NULL;
         pSearch = BaseFindNextEntryByHash(&sContext))
    {
#ifdef FEATURE_PREJIT
        // This ensures that GetAssemblyIfLoaded operations that may be triggered by signature walks will succeed if at all possible.
        ClrFlsThreadTypeSwitch genericInstantionCompareHolder(ThreadType_GenericInstantiationCompare); 
#endif

        MethodDesc *pMD = pSearch->GetMethod();

        if (pMD->GetMemberDef() != token)
            continue;  // Next iteration of the for loop

        if (pMD->GetNumGenericMethodArgs() != inst.GetNumArgs())
            continue;  // Next iteration of the for loop

        DWORD dwKeyFlags = pSearch->GetFlags();

        if ( ((dwKeyFlags & InstMethodHashEntry::RequiresInstArg) == 0) != (getSharedNotStub == 0) )
            continue;

        if ( ((dwKeyFlags & InstMethodHashEntry::UnboxingStub)    == 0) != (unboxingStub == 0) )
            continue;

        // Note pMD->GetMethodTable() might not be restored at this point. 

        RelativeFixupPointer<PTR_MethodTable> * ppMT = pMD->GetMethodTablePtr();
        TADDR pMT = ppMT->GetValueMaybeTagged((TADDR)ppMT);

        if (!ZapSig::CompareTaggedPointerToTypeHandle(GetModule(), pMT, declaringType))
        {
            continue;  // Next iteration of the for loop
        }
          
        if (!inst.IsEmpty())
        {
            Instantiation candidateInst = pMD->GetMethodInstantiation();

            // We have matched the method already, thus the number of arguments in the instantiation should match too.
            _ASSERTE(inst.GetNumArgs() == candidateInst.GetNumArgs());

            bool match = true;   // This is true when all instantiation arguments match

            for (DWORD i = 0; i < inst.GetNumArgs(); i++)
            {
                // Fetch the type handle as TADDR. It may be may be encoded fixup - TypeHandle debug-only validation 
                // asserts on encoded fixups.
                TADDR candidateArg = ((FixupPointer<TADDR> *)candidateInst.GetRawArgs())[i].GetValue();
                    
                if (!ZapSig::CompareTaggedPointerToTypeHandle(GetModule(), candidateArg, inst[i]))
                {
                    match = false;
                    break;
                }
            }
            if (!match)
                continue;  // Next iteration of the pSearch for loop;
        }
        //
        // Success, we found a pMD that matches

        pMDResult = pMD;
        break;  // Exit the for loop and jump to the return pMDResult
    }

    return pMDResult;
}

BOOL InstMethodHashTable::ContainsMethodDesc(MethodDesc* pMD)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
    }
    CONTRACTL_END;

    return FindMethodDesc(
        pMD->GetMethodTable(), pMD->GetMemberDef(), pMD->IsUnboxingStub(),
        pMD->GetMethodInstantiation(), pMD->RequiresInstArg()) != NULL;
}

#endif // #ifndef DACCESS_COMPILE

void InstMethodHashTable::Iterator::Reset()
{
    WRAPPER_NO_CONTRACT;

    if (m_pTable)
    {
#ifdef _DEBUG
        m_pTable->Unseal();
#endif
        m_pTable = NULL;
    }

    Init();
}

void InstMethodHashTable::Iterator::Init()
{
    WRAPPER_NO_CONTRACT;

#ifdef _DEBUG
    if (m_pTable)
        m_pTable->Seal(); // The table cannot be changing while it is being iterated
#endif

    m_fIterating = false;
}

InstMethodHashTable::Iterator::Iterator()
{
    WRAPPER_NO_CONTRACT; 
    m_pTable = NULL;
    Init(); 
}

InstMethodHashTable::Iterator::Iterator(InstMethodHashTable * pTable)
{
    WRAPPER_NO_CONTRACT;
    m_pTable = pTable;
    Init();
}

InstMethodHashTable::Iterator::~Iterator()
{
    WRAPPER_NO_CONTRACT;

#ifdef _DEBUG
    if (m_pTable)
        m_pTable->Unseal(); // Done with the iterator so we unseal
#endif
}

BOOL InstMethodHashTable::FindNext(Iterator *it, InstMethodHashEntry **ppEntry)
{
    LIMITED_METHOD_CONTRACT;

    if (!it->m_fIterating)
    {
        BaseInitIterator(&it->m_sIterator);
        it->m_fIterating = true;
    }

    *ppEntry = it->m_sIterator.Next();
    return *ppEntry ? TRUE : FALSE;
}

DWORD InstMethodHashTable::GetCount()
{
    LIMITED_METHOD_CONTRACT;

    return BaseGetElementCount();
}

#ifndef DACCESS_COMPILE

// Add method desc to the hash table; must not be present already
void InstMethodHashTable::InsertMethodDesc(MethodDesc *pMD)
{
    CONTRACTL
    {
        THROWS;
        GC_NOTRIGGER;
        INJECT_FAULT(COMPlusThrowOM(););
        PRECONDITION(IsUnsealed());          // If we are sealed then we should not be adding to this hashtable
        PRECONDITION(CheckPointer(pMD));
        
        // Generic method definitions (e.g. D.m<U> or C<int>.m<U>) belong in method tables, not here
        PRECONDITION(!pMD->IsGenericMethodDefinition());
    }
    CONTRACTL_END
 
    InstMethodHashEntry_t * pNewEntry = (InstMethodHashEntry_t*)BaseAllocateEntry(NULL);

    DWORD dwKeyFlags = 0;
    if (pMD->RequiresInstArg())
        dwKeyFlags |= InstMethodHashEntry::RequiresInstArg;
    if (pMD->IsUnboxingStub())
        dwKeyFlags |= InstMethodHashEntry::UnboxingStub;
    pNewEntry->SetMethodAndFlags(pMD, dwKeyFlags);

    DWORD dwHash = Hash(pMD->GetMethodTable(), pMD->GetMemberDef(), pMD->GetMethodInstantiation());
    BaseInsertEntry(dwHash, pNewEntry);
}

#ifdef FEATURE_NATIVE_IMAGE_GENERATION

#ifdef _DEBUG
void InstMethodHashTableSeal(InstMethodHashTable * pTable) { WRAPPER_NO_CONTRACT; pTable->Seal(); }
void InstMethodHashTableUnseal(InstMethodHashTable * pTable) { WRAPPER_NO_CONTRACT; pTable->Unseal(); }
typedef  Wrapper<InstMethodHashTable *, InstMethodHashTableSeal, InstMethodHashTableUnseal> InstMethodHashTableSealHolder;
#endif

// Save the hash table and any method descriptors referenced by it
void InstMethodHashTable::Save(DataImage *image, CorProfileData *pProfileData)
{
    CONTRACTL
    {
        STANDARD_VM_CHECK;
        PRECONDITION(image->GetModule() == m_pModule);
    }
    CONTRACTL_END;

#ifdef _DEBUG
    // The table should not change while we are walking the buckets
    InstMethodHashTableSealHolder h(this);
#endif

    BaseSave(image, pProfileData);
}

bool InstMethodHashTable::ShouldSave(DataImage *pImage, InstMethodHashEntry_t *pEntry)
{
    STANDARD_VM_CONTRACT;

    return !!pImage->GetPreloader()->IsMethodInTransitiveClosureOfInstantiations(CORINFO_METHOD_HANDLE(pEntry->GetMethod()));
}

bool InstMethodHashTable::IsHotEntry(InstMethodHashEntry_t *pEntry, CorProfileData *pProfileData)
{
    LIMITED_METHOD_CONTRACT;

    return true;
}

bool InstMethodHashTable::SaveEntry(DataImage *pImage, CorProfileData *pProfileData, InstMethodHashEntry_t *pOldEntry, InstMethodHashEntry_t *pNewEntry, EntryMappingTable *pMap)
{
    LIMITED_METHOD_CONTRACT;

    return false;
}

void InstMethodHashTable::Fixup(DataImage *image)
{
    STANDARD_VM_CONTRACT;

    BaseFixup(image);

    image->ZeroPointerField(this, offsetof(InstMethodHashTable, m_pLoaderAllocator));

#ifdef _DEBUG
    // The persisted table should be unsealed.
    InstMethodHashTable *pNewTable = (InstMethodHashTable*) image->GetImagePointer(this);
    pNewTable->InitUnseal();
#endif
}

void InstMethodHashTable::FixupEntry(DataImage *pImage, InstMethodHashEntry_t *pEntry, void *pFixupBase, DWORD cbFixupOffset)
{
    STANDARD_VM_CONTRACT;

    pImage->FixupField(pFixupBase, cbFixupOffset + offsetof(InstMethodHashEntry_t, data), pEntry->GetMethod(), pEntry->GetFlags());

    pEntry->GetMethod()->Fixup(pImage);
}
#endif // FEATURE_PREJIT

#endif // #ifndef DACCESS_COMPILE

#ifdef DACCESS_COMPILE
void
InstMethodHashTable::EnumMemoryRegions(CLRDataEnumMemoryFlags flags)
{
    SUPPORTS_DAC;
    
    BaseEnumMemoryRegions(flags);
}

void InstMethodHashTable::EnumMemoryRegionsForEntry(InstMethodHashEntry_t *pEntry, CLRDataEnumMemoryFlags flags)
{
    SUPPORTS_DAC;

    if (pEntry->GetMethod().IsValid())
        pEntry->GetMethod()->EnumMemoryRegions(flags);
}
#endif // #ifdef DACCESS_COMPILE