Welcome to mirror list, hosted at ThFree Co, Russian Federation.

TypeLoaderExports.cs « Runtime « System « src « System.Private.CoreLib « src - github.com/mono/corert.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 8e08a76daf42272ca9d29e4e6605d885e6264671 (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
// 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.

using System;
using Internal.Runtime.Augments;
using System.Diagnostics;
using System.Threading;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

namespace System.Runtime
{
    [ReflectionBlocked]
    public static class TypeLoaderExports
    {
#if PROJECTN
        [RuntimeExport("GetThreadStaticsForDynamicType")]
#endif
        public static IntPtr GetThreadStaticsForDynamicType(int index)
        {
            IntPtr result = RuntimeImports.RhGetThreadLocalStorageForDynamicType(index, 0, 0);
            if (result != IntPtr.Zero)
                return result;

            int numTlsCells;
            int tlsStorageSize = RuntimeAugments.TypeLoaderCallbacks.GetThreadStaticsSizeForDynamicType(index, out numTlsCells);
            result = RuntimeImports.RhGetThreadLocalStorageForDynamicType(index, tlsStorageSize, numTlsCells);

            if (result == IntPtr.Zero)
                throw new OutOfMemoryException();

            return result;
        }

#if PROJECTN
        [RuntimeExport("ActivatorCreateInstanceAny")]
#endif
        public static unsafe void ActivatorCreateInstanceAny(ref object ptrToData, IntPtr pEETypePtr)
        {
            EETypePtr pEEType = new EETypePtr(pEETypePtr);

            if (pEEType.IsValueType)
            {
                // Nothing else to do for value types.
                return;
            }

            // For reference types, we need to:
            //  1- Allocate the new object
            //  2- Call its default ctor
            //  3- Update ptrToData to point to that newly allocated object
            ptrToData = RuntimeImports.RhNewObject(pEEType);

            Entry entry = LookupInCache(s_cache, pEETypePtr, pEETypePtr);
            if (entry == null)
            {
                entry = CacheMiss(pEETypePtr, pEETypePtr,
                    (IntPtr context, IntPtr signature, object contextObject, ref IntPtr auxResult) =>
                    {
                        IntPtr result = RuntimeAugments.TypeLoaderCallbacks.TryGetDefaultConstructorForType(new RuntimeTypeHandle(new EETypePtr(context)));
                        if (result == IntPtr.Zero)
                            result = RuntimeAugments.GetFallbackDefaultConstructor();
                        return result;
                    });
            }
            RawCalliHelper.Call(entry.Result, ptrToData);
        }

        //
        // Generic lookup cache
        //

        private class Entry
        {
            public IntPtr Context;
            public IntPtr Signature;
            public IntPtr Result;
            public IntPtr AuxResult;
            public Entry Next;
        }

        // Initialize the cache eagerly to avoid null checks.
        // Use array with just single element to make this pay-for-play. The actual cache will be allocated only 
        // once the lazy lookups are actually needed.
        private static Entry[] s_cache;

        private static Lock s_lock;
        private static GCHandle s_previousCache;

        internal static void Initialize()
        {
            s_cache = new Entry[1];
        }

#if PROJECTN
        [RuntimeExport("GenericLookup")]
#endif
        public static IntPtr GenericLookup(IntPtr context, IntPtr signature)
        {
            Entry entry = LookupInCache(s_cache, context, signature);
            if (entry == null)
            {
                entry = CacheMiss(context, signature);
            }
            return entry.Result;
        }

#if PROJECTN
        [RuntimeExport("GenericLookupAndCallCtor")]
#endif
        public static void GenericLookupAndCallCtor(object arg, IntPtr context, IntPtr signature)
        {
            Entry entry = LookupInCache(s_cache, context, signature);
            if (entry == null)
            {
                entry = CacheMiss(context, signature);
            }
            RawCalliHelper.Call(entry.Result, arg);
        }

#if PROJECTN
        [RuntimeExport("GenericLookupAndAllocObject")]
#endif
        public static object GenericLookupAndAllocObject(IntPtr context, IntPtr signature)
        {
            Entry entry = LookupInCache(s_cache, context, signature);
            if (entry == null)
            {
                entry = CacheMiss(context, signature);
            }
            return RawCalliHelper.Call<object>(entry.Result, entry.AuxResult);
        }

#if PROJECTN
        [RuntimeExport("GenericLookupAndAllocArray")]
#endif
        public static object GenericLookupAndAllocArray(IntPtr context, IntPtr arg, IntPtr signature)
        {
            Entry entry = LookupInCache(s_cache, context, signature);
            if (entry == null)
            {
                entry = CacheMiss(context, signature);
            }
            return RawCalliHelper.Call<object>(entry.Result, entry.AuxResult, arg);
        }

#if PROJECTN
        [RuntimeExport("GenericLookupAndCheckArrayElemType")]
#endif
        public static void GenericLookupAndCheckArrayElemType(IntPtr context, object arg, IntPtr signature)
        {
            Entry entry = LookupInCache(s_cache, context, signature);
            if (entry == null)
            {
                entry = CacheMiss(context, signature);
            }
            RawCalliHelper.Call(entry.Result, entry.AuxResult, arg);
        }

#if PROJECTN
        [RuntimeExport("GenericLookupAndCast")]
#endif
        public static object GenericLookupAndCast(object arg, IntPtr context, IntPtr signature)
        {
            Entry entry = LookupInCache(s_cache, context, signature);
            if (entry == null)
            {
                entry = CacheMiss(context, signature);
            }
            return RawCalliHelper.Call<object>(entry.Result, arg, entry.AuxResult);
        }

#if PROJECTN
        [RuntimeExport("UpdateTypeFloatingDictionary")]
#endif
        public static IntPtr UpdateTypeFloatingDictionary(IntPtr eetypePtr, IntPtr dictionaryPtr)
        {
            // No caching needed. Update is in-place, and happens once per dictionary
            return RuntimeAugments.TypeLoaderCallbacks.UpdateFloatingDictionary(eetypePtr, dictionaryPtr);
        }

#if PROJECTN
        [RuntimeExport("UpdateMethodFloatingDictionary")]
#endif
        public static IntPtr UpdateMethodFloatingDictionary(IntPtr dictionaryPtr)
        {
            // No caching needed. Update is in-place, and happens once per dictionary
            return RuntimeAugments.TypeLoaderCallbacks.UpdateFloatingDictionary(dictionaryPtr, dictionaryPtr);
        }

        public static unsafe IntPtr GetDelegateThunk(object delegateObj, int whichThunk)
        {
            Entry entry = LookupInCache(s_cache, delegateObj.m_pEEType, new IntPtr(whichThunk));
            if (entry == null)
            {
                entry = CacheMiss(delegateObj.m_pEEType, new IntPtr(whichThunk),
                    (IntPtr context, IntPtr signature, object contextObject, ref IntPtr auxResult)
                        => RuntimeAugments.TypeLoaderCallbacks.GetDelegateThunk((Delegate)contextObject, (int)signature),
                    delegateObj);
            }
            return entry.Result;
        }

        public static unsafe IntPtr GVMLookupForSlot(object obj, RuntimeMethodHandle slot)
        {
            Entry entry = LookupInCache(s_cache, obj.m_pEEType, *(IntPtr*)&slot);
            if (entry == null)
            {
                entry = CacheMiss(obj.m_pEEType, *(IntPtr*)&slot,
                    (IntPtr context, IntPtr signature, object contextObject, ref IntPtr auxResult)
                        => Internal.Runtime.CompilerServices.GenericVirtualMethodSupport.GVMLookupForSlot(new RuntimeTypeHandle(new EETypePtr(context)), *(RuntimeMethodHandle*)&signature));
            }
            return entry.Result;
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        internal static IntPtr OpenInstanceMethodLookup(IntPtr openResolver, object obj)
        {
            Entry entry = LookupInCache(s_cache, obj.m_pEEType, openResolver);
            if (entry == null)
            {
                entry = CacheMiss(obj.m_pEEType, openResolver,
                    (IntPtr context, IntPtr signature, object contextObject, ref IntPtr auxResult)
                        => Internal.Runtime.CompilerServices.OpenMethodResolver.ResolveMethodWorker(signature, contextObject),
                    obj);
            }
            return entry.Result;
        }

        [MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
        private static Entry LookupInCache(Entry[] cache, IntPtr context, IntPtr signature)
        {
            int key = ((context.GetHashCode() >> 4) ^ signature.GetHashCode()) & (cache.Length - 1);
            Entry entry = cache[key];
            while (entry != null)
            {
                if (entry.Context == context && entry.Signature == signature)
                    break;
                entry = entry.Next;
            }
            return entry;
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        internal static IntPtr RuntimeCacheLookupInCache(IntPtr context, IntPtr signature, RuntimeObjectFactory factory, object contextObject, out IntPtr auxResult)
        {
            Entry entry = LookupInCache(s_cache, context, signature);
            if (entry == null)
            {
                entry = CacheMiss(context, signature, factory, contextObject);
            }
            auxResult = entry.AuxResult;
            return entry.Result;
        }

        private static Entry CacheMiss(IntPtr ctx, IntPtr sig)
        {
            return CacheMiss(ctx, sig,
                (IntPtr context, IntPtr signature, object contextObject, ref IntPtr auxResult) =>
                    RuntimeAugments.TypeLoaderCallbacks.GenericLookupFromContextAndSignature(context, signature, out auxResult)
                );
        }

        private static unsafe Entry CacheMiss(IntPtr context, IntPtr signature, RuntimeObjectFactory factory, object contextObject = null)
        {
            IntPtr result = IntPtr.Zero, auxResult = IntPtr.Zero;
            bool previouslyCached = false;

            //
            // Try to find the entry in the previous version of the cache that is kept alive by weak reference
            //
            if (s_previousCache.IsAllocated)
            {
                Entry[] previousCache = (Entry[])s_previousCache.Target;
                if (previousCache != null)
                {
                    Entry previousEntry = LookupInCache(previousCache, context, signature);
                    if (previousEntry != null)
                    {
                        result = previousEntry.Result;
                        auxResult = previousEntry.AuxResult;
                        previouslyCached = true;
                    }
                }
            }

            //
            // Call into the type loader to compute the target
            //
            if (!previouslyCached)
            {
                result = factory(context, signature, contextObject, ref auxResult);
            }

            //
            // Update the cache under the lock
            //
            if (s_lock == null)
                Interlocked.CompareExchange(ref s_lock, new Lock(), null);

            s_lock.Acquire();
            try
            {
                // Avoid duplicate entries
                Entry existingEntry = LookupInCache(s_cache, context, signature);
                if (existingEntry != null)
                    return existingEntry;

                // Resize cache as necessary
                Entry[] cache = ResizeCacheForNewEntryAsNecessary();

                int key = ((context.GetHashCode() >> 4) ^ signature.GetHashCode()) & (cache.Length - 1);

                Entry newEntry = new Entry() { Context = context, Signature = signature, Result = result, AuxResult = auxResult, Next = cache[key] };
                cache[key] = newEntry;
                return newEntry;
            }
            finally
            {
                s_lock.Release();
            }
        }

        //
        // Parameters and state used by generic lookup cache resizing algorithm
        //

        private const int InitialCacheSize = 128; // MUST BE A POWER OF TWO
        private const int DefaultCacheSize = 1024;
        private const int MaximumCacheSize = 128 * 1024;

        private static long s_tickCountOfLastOverflow;
        private static int s_entries;
        private static bool s_roundRobinFlushing;

        private static Entry[] ResizeCacheForNewEntryAsNecessary()
        {
            Entry[] cache = s_cache;

            if (cache.Length < InitialCacheSize)
            {
                // Start with small cache size so that the cache entries used by startup one-time only initialization will get flushed soon
                return s_cache = new Entry[InitialCacheSize];
            }

            int entries = s_entries++;

            // If the cache has spare space, we are done
            if (2 * entries < cache.Length)
            {
                if (s_roundRobinFlushing)
                {
                    cache[2 * entries] = null;
                    cache[2 * entries + 1] = null;
                }
                return cache;
            }

            //
            // Now, we have cache that is overflowing with the stuff. We need to decide whether to resize it or start flushing the old entries instead
            //

            // Start over counting the entries
            s_entries = 0;

            // See how long it has been since the last time the cache was overflowing
            long tickCount = Environment.TickCount64;
            long tickCountSinceLastOverflow = tickCount - s_tickCountOfLastOverflow;
            s_tickCountOfLastOverflow = tickCount;

            bool shrinkCache = false;
            bool growCache = false;

            if (cache.Length < DefaultCacheSize)
            {
                // If the cache have not reached the default size, just grow it without thinking about it much
                growCache = true;
            }
            else
            {
                if (tickCountSinceLastOverflow < cache.Length / 128)
                {
                    // If the fill rate of the cache is faster than ~0.01ms per entry, grow it
                    if (cache.Length < MaximumCacheSize)
                        growCache = true;
                }
                else
                if (tickCountSinceLastOverflow > cache.Length * 16)
                {
                    // If the fill rate of the cache is slower than 16ms per entry, shrink it
                    if (cache.Length > DefaultCacheSize)
                        shrinkCache = true;
                }
                // Otherwise, keep the current size and just keep flushing the entries round robin
            }

            if (growCache || shrinkCache)
            {
                s_roundRobinFlushing = false;

                // Keep the reference to the old cache in a weak handle. We will try to use to avoid
                // hitting the type loader until GC collects it.
                if (s_previousCache.IsAllocated)
                {
                    s_previousCache.Target = cache;
                }
                else
                {
                    s_previousCache = GCHandle.Alloc(cache, GCHandleType.Weak);
                }

                return s_cache = new Entry[shrinkCache ? (cache.Length / 2) : (cache.Length * 2)];
            }
            else
            {
                s_roundRobinFlushing = true;
                return cache;
            }
        }
    }

    [ReflectionBlocked]
    public delegate IntPtr RuntimeObjectFactory(IntPtr context, IntPtr signature, object contextObject, ref IntPtr auxResult);

    [System.Runtime.InteropServices.McgIntrinsicsAttribute]
    internal class RawCalliHelper
    {
        [MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
        public static T Call<T>(System.IntPtr pfn, IntPtr arg)
        {
            return default(T);
        }

        [MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
        public static void Call(System.IntPtr pfn, object arg)
        {
        }

        [MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
        public static T Call<T>(System.IntPtr pfn, IntPtr arg1, IntPtr arg2)
        {
            return default(T);
        }

        [MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
        public static T Call<T>(System.IntPtr pfn, IntPtr arg1, IntPtr arg2, object arg3, out IntPtr arg4)
        {
            arg4 = IntPtr.Zero;
            return default(T);
        }

        [MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
        public static void Call(System.IntPtr pfn, IntPtr arg1, object arg2)
        {
        }

        [MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
        public static T Call<T>(System.IntPtr pfn, object arg1, IntPtr arg2)
        {
            return default(T);
        }

        [MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
        public static T Call<T>(IntPtr pfn, string[] arg0)
        {
            return default(T);
        }
    }
}