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

InteropExtensions.cs « InteropServices « Runtime « System « src « System.Private.CoreLib « src - github.com/mono/corert.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 10092bcf7b51d55f15985b04a63d53557fc680aa (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
// 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 System.Runtime.CompilerServices;
using System.Collections.Generic;
using System.Diagnostics;

using Internal.Runtime.Augments;
using Internal.Runtime.CompilerServices;

namespace System.Runtime.InteropServices
{
    /// <summary>
    ///     Hooks for System.Private.Interop.dll code to access internal functionality in System.Private.CoreLib.dll.
    ///     
    ///     Methods added to InteropExtensions should also be added to the System.Private.CoreLib.InteropServices contract
    ///     in order to be accessible from System.Private.Interop.dll.
    /// </summary>
    [CLSCompliant(false)]
    [ReflectionBlocked]
    public static class InteropExtensions
    {
        // Converts a managed DateTime to native OLE datetime
        // Used by MCG marshalling code
        public static double ToNativeOleDate(DateTime dateTime)
        {
            return dateTime.ToOADate();
        }

        // Converts native OLE datetime to managed DateTime
        // Used by MCG marshalling code
        public static DateTime FromNativeOleDate(double nativeOleDate)
        {
            return new DateTime(DateTime.DoubleDateToTicks(nativeOleDate));
        }

        // Used by MCG's SafeHandle marshalling code to initialize a handle
        public static void InitializeHandle(SafeHandle safeHandle, IntPtr win32Handle)
        {
            safeHandle.InitializeHandle(win32Handle);
        }

        // Used for methods in System.Private.Interop.dll that need to work from offsets on boxed structs
        public static unsafe void PinObjectAndCall(object obj, Action<IntPtr> del)
        {
            fixed (IntPtr* pEEType = &obj.m_pEEType)
            {
                del((IntPtr)pEEType);
            }
        }

        public static int GetElementSize(this Array array)
        {
            return array.EETypePtr.ComponentSize;
        }

        internal static bool MightBeBlittable(this EETypePtr eeType)
        {
            //
            // This is used as the approximate implementation of MethodTable::IsBlittable(). It  will err in the direction of declaring
            // things blittable since it is used for argument validation only.
            //
            return !eeType.HasPointers;
        }

        public static bool IsBlittable(this RuntimeTypeHandle handle)
        {
            return handle.ToEETypePtr().MightBeBlittable();
        }

        public static bool IsBlittable(this object obj)
        {
            return obj.EETypePtr.MightBeBlittable();
        }

        public static bool IsGenericType(this RuntimeTypeHandle handle)
        {
            EETypePtr eeType = handle.ToEETypePtr();
            return eeType.IsGeneric;
        }

        public static bool IsGenericTypeDefinition(this RuntimeTypeHandle handle)
        {
            EETypePtr eeType = handle.ToEETypePtr();
            return eeType.IsGenericTypeDefinition;
        }

        public static unsafe int GetGenericArgumentCount(this RuntimeTypeHandle genericTypeDefinitionHandle)
        {
            Debug.Assert(IsGenericTypeDefinition(genericTypeDefinitionHandle));
            return genericTypeDefinitionHandle.ToEETypePtr().ToPointer()->GenericArgumentCount;
        }

        //TODO:Remove Delegate.GetNativeFunctionPointer
        public static IntPtr GetNativeFunctionPointer(this Delegate del)
        {
            return del.GetNativeFunctionPointer();
        }
        public static IntPtr GetFunctionPointer(this Delegate del, out RuntimeTypeHandle typeOfFirstParameterIfInstanceDelegate)
        {
            return del.GetFunctionPointer(out typeOfFirstParameterIfInstanceDelegate, out bool _, out bool _);
        }

        //
        // Returns the raw function pointer for a open static delegate - if the function has a jump stub 
        // it returns the jump target. Therefore the function pointer returned
        // by two delegates may NOT be unique
        //
        public static IntPtr GetRawFunctionPointerForOpenStaticDelegate(this Delegate del)
        {
            //If it is not open static then return IntPtr.Zero
            if (!del.IsOpenStatic)
                return IntPtr.Zero;

            RuntimeTypeHandle typeOfFirstParameterIfInstanceDelegate;

            IntPtr funcPtr = del.GetFunctionPointer(out typeOfFirstParameterIfInstanceDelegate, out bool _, out bool _);

            // if the function pointer points to a jump stub return the target
            return RuntimeImports.RhGetJmpStubCodeTarget(funcPtr);
        }

        public static IntPtr GetRawValue(this RuntimeTypeHandle handle)
        {
            return handle.RawValue;
        }

        /// <summary>
        /// Comparing RuntimeTypeHandle with an object's RuntimeTypeHandle, avoiding going through expensive Object.GetType().TypeHandle path
        /// </summary>
        public static bool IsOfType(this object obj, RuntimeTypeHandle handle)
        {
            RuntimeTypeHandle objType = new RuntimeTypeHandle(obj.EETypePtr);

            return handle.Equals(objType);
        }

        public static bool IsNull(this RuntimeTypeHandle handle)
        {
            return handle.IsNull;
        }

        public static Type GetTypeFromHandle(IntPtr typeHandle)
        {
            return Type.GetTypeFromHandle(new RuntimeTypeHandle(new EETypePtr(typeHandle)));
        }

        public static Type GetTypeFromHandle(RuntimeTypeHandle typeHandle)
        {
            return Type.GetTypeFromHandle(typeHandle);
        }

        public static int GetValueTypeSize(this RuntimeTypeHandle handle)
        {
            return (int)handle.ToEETypePtr().ValueTypeSize;
        }

        public static bool IsValueType(this RuntimeTypeHandle handle)
        {
            return handle.ToEETypePtr().IsValueType;
        }

        public static bool IsClass(this RuntimeTypeHandle handle)
        {
            return handle.ToEETypePtr().IsDefType && !handle.ToEETypePtr().IsInterface && !handle.ToEETypePtr().IsValueType && !handle.IsDelegate();
        }

        public static bool IsEnum(this RuntimeTypeHandle handle)
        {
            return handle.ToEETypePtr().IsEnum;
        }

        public static bool IsInterface(this RuntimeTypeHandle handle)
        {
            return handle.ToEETypePtr().IsInterface;
        }

        public static bool IsPrimitive(this RuntimeTypeHandle handle)
        {
            return handle.ToEETypePtr().IsPrimitive;
        }

        public static bool IsDelegate(this RuntimeTypeHandle handle)
        {
            return InteropExtensions.AreTypesAssignable(handle, typeof(Delegate).TypeHandle);
        }

        public static bool AreTypesAssignable(RuntimeTypeHandle sourceType, RuntimeTypeHandle targetType)
        {
            return RuntimeImports.AreTypesAssignable(sourceType.ToEETypePtr(), targetType.ToEETypePtr());
        }

        public static unsafe void Memcpy(IntPtr destination, IntPtr source, int bytesToCopy)
        {
            Buffer.Memmove((byte*)destination, (byte*)source, (uint)bytesToCopy);
        }

        public static bool RuntimeRegisterGcCalloutForGCStart(IntPtr pCalloutMethod)
        {
            return RuntimeImports.RhRegisterGcCallout(RuntimeImports.GcRestrictedCalloutKind.StartCollection, pCalloutMethod);
        }

        public static bool RuntimeRegisterGcCalloutForGCEnd(IntPtr pCalloutMethod)
        {
            return RuntimeImports.RhRegisterGcCallout(RuntimeImports.GcRestrictedCalloutKind.EndCollection, pCalloutMethod);
        }

        public static bool RuntimeRegisterGcCalloutForAfterMarkPhase(IntPtr pCalloutMethod)
        {
            return RuntimeImports.RhRegisterGcCallout(RuntimeImports.GcRestrictedCalloutKind.AfterMarkPhase, pCalloutMethod);
        }

        public static bool RuntimeRegisterRefCountedHandleCallback(IntPtr pCalloutMethod, RuntimeTypeHandle pTypeFilter)
        {
            return RuntimeImports.RhRegisterRefCountedHandleCallback(pCalloutMethod, pTypeFilter.ToEETypePtr());
        }

        public static void RuntimeUnregisterRefCountedHandleCallback(IntPtr pCalloutMethod, RuntimeTypeHandle pTypeFilter)
        {
            RuntimeImports.RhUnregisterRefCountedHandleCallback(pCalloutMethod, pTypeFilter.ToEETypePtr());
        }

        /// <summary>
        /// The type of a RefCounted handle
        /// A ref-counted handle is a handle that acts as strong if the callback returns true, and acts as 
        /// weak handle if the callback returns false, which is perfect for controlling lifetime of a CCW
        /// </summary>
        internal const int RefCountedHandleType = 5;
        public static IntPtr RuntimeHandleAllocRefCounted(object value)
        {
            return RuntimeImports.RhHandleAlloc(value, (GCHandleType)RefCountedHandleType);
        }

        public static void RuntimeHandleSet(IntPtr handle, object value)
        {
            RuntimeImports.RhHandleSet(handle, value);
        }

        public static void RuntimeHandleFree(IntPtr handle)
        {
            RuntimeImports.RhHandleFree(handle);
        }

        public static IntPtr RuntimeHandleAllocDependent(object primary, object secondary)
        {
            return RuntimeImports.RhHandleAllocDependent(primary, secondary);
        }

        public static bool RuntimeIsPromoted(object obj)
        {
            return RuntimeImports.RhIsPromoted(obj);
        }

        public static void RuntimeHandleSetDependentSecondary(IntPtr handle, object secondary)
        {
            RuntimeImports.RhHandleSetDependentSecondary(handle, secondary);
        }

        public static T UncheckedCast<T>(object obj) where T : class
        {
            return Unsafe.As<T>(obj);
        }

        public static bool IsArray(RuntimeTypeHandle type)
        {
            return type.ToEETypePtr().IsArray;
        }

        public static RuntimeTypeHandle GetArrayElementType(RuntimeTypeHandle arrayType)
        {
            return new RuntimeTypeHandle(arrayType.ToEETypePtr().ArrayElementType);
        }

        /// <summary>
        /// Whether the type is a single dimension zero lower bound array
        /// </summary>
        /// <param name="type">specified type</param>
        /// <returns>true iff it is a single dimension zeo lower bound array</returns>
        public static bool IsSzArray(RuntimeTypeHandle type)
        {
            return type.ToEETypePtr().IsSzArray;
        }

        public static RuntimeTypeHandle GetTypeHandle(this object target)
        {
            return new RuntimeTypeHandle(target.EETypePtr);
        }

        public static bool IsInstanceOf(object obj, RuntimeTypeHandle typeHandle)
        {
            return (null != RuntimeImports.IsInstanceOf(obj, typeHandle.ToEETypePtr()));
        }

        public static bool IsInstanceOfClass(object obj, RuntimeTypeHandle classTypeHandle)
        {
            return (null != RuntimeImports.IsInstanceOfClass(obj, classTypeHandle.ToEETypePtr()));
        }

        public static bool IsInstanceOfInterface(object obj, RuntimeTypeHandle interfaceTypeHandle)
        {
            return (null != RuntimeImports.IsInstanceOfInterface(obj, interfaceTypeHandle.ToEETypePtr()));
        }

        public static bool GuidEquals(ref Guid left, ref Guid right)
        {
            return left.Equals(ref right);
        }

        public static bool ComparerEquals<T>(T left, T right)
        {
            return EqualOnlyComparer<T>.Equals(left, right);
        }

        public static object RuntimeNewObject(RuntimeTypeHandle typeHnd)
        {
            return RuntimeImports.RhNewObject(typeHnd.ToEETypePtr());
        }

        public static unsafe void UnsafeCopyTo(this System.Text.StringBuilder stringBuilder, char* destination)
        {
            stringBuilder.UnsafeCopyTo(destination);
        }

        public static unsafe void ReplaceBuffer(this System.Text.StringBuilder stringBuilder, char* newBuffer)
        {
            stringBuilder.ReplaceBuffer(newBuffer);
        }

        public static void ReplaceBuffer(this System.Text.StringBuilder stringBuilder, char[] newBuffer)
        {
            stringBuilder.ReplaceBuffer(newBuffer);
        }

        public static char[] GetBuffer(this System.Text.StringBuilder stringBuilder, out int len)
        {
            return stringBuilder.GetBuffer(out len);
        }

        public static IntPtr RuntimeHandleAllocVariable(object value, uint type)
        {
            return RuntimeImports.RhHandleAllocVariable(value, type);
        }

        public static uint RuntimeHandleGetVariableType(IntPtr handle)
        {
            return RuntimeImports.RhHandleGetVariableType(handle);
        }

        public static void RuntimeHandleSetVariableType(IntPtr handle, uint type)
        {
            RuntimeImports.RhHandleSetVariableType(handle, type);
        }

        public static uint RuntimeHandleCompareExchangeVariableType(IntPtr handle, uint oldType, uint newType)
        {
            return RuntimeImports.RhHandleCompareExchangeVariableType(handle, oldType, newType);
        }
        
        public static void SetExceptionErrorCode(Exception exception, int hr)
        {
            exception.HResult = hr;
        }
        
        public static void SetExceptionMessage(Exception exception, string message)
        {
            exception.SetMessage(message);
        }

        public static Exception CreateDataMisalignedException(string message)
        {
            return new DataMisalignedException(message);
        }

        public static Delegate CreateDelegate(RuntimeTypeHandle typeHandleForDelegate, IntPtr ldftnResult, object thisObject, bool isStatic, bool isVirtual, bool isOpen)
        {
            return Delegate.CreateDelegate(typeHandleForDelegate.ToEETypePtr(), ldftnResult, thisObject, isStatic, isOpen);
        }

        public enum VariableHandleType
        {
            WeakShort = 0x00000100,
            WeakLong = 0x00000200,
            Strong = 0x00000400,
            Pinned = 0x00000800,
        }

        public static void AddExceptionDataForRestrictedErrorInfo(Exception ex, string restrictedError, string restrictedErrorReference, string restrictedCapabilitySid, object restrictedErrorObject)
        {
            ex.AddExceptionDataForRestrictedErrorInfo(restrictedError, restrictedErrorReference, restrictedCapabilitySid, restrictedErrorObject);
        }

        public static bool TryGetRestrictedErrorObject(Exception ex, out object restrictedErrorObject)
        {
            return ex.TryGetRestrictedErrorObject(out restrictedErrorObject);
        }

        public static bool TryGetRestrictedErrorDetails(Exception ex, out string restrictedError, out string restrictedErrorReference, out string restrictedCapabilitySid)
        {
            return ex.TryGetRestrictedErrorDetails(out restrictedError, out restrictedErrorReference, out restrictedCapabilitySid);
        }

        public static IntPtr[] ExceptionGetStackIPs(Exception ex)
        {
            return ex.GetStackIPs();
        }

        public static TypeInitializationException CreateTypeInitializationException(string message)
        {
            return new TypeInitializationException(message);
        }

        public static unsafe IntPtr GetObjectID(object obj)
        {
            fixed (void* p = &obj.m_pEEType)
            {
                return (IntPtr)p;
            }
        }

        public static bool RhpETWShouldWalkCom()
        {
            return RuntimeImports.RhpETWShouldWalkCom();
        }

        public static void RhpETWLogLiveCom(int eventType, IntPtr CCWHandle, IntPtr objectID, IntPtr typeRawValue, IntPtr IUnknown, IntPtr VTable, int comRefCount, int jupiterRefCount, int flags)
        {
            RuntimeImports.RhpETWLogLiveCom(eventType, CCWHandle, objectID, typeRawValue, IUnknown, VTable, comRefCount, jupiterRefCount, flags);
        }

        public static bool SupportsReflection(this Type type)
        {
            return RuntimeAugments.Callbacks.SupportsReflection(type);
        }

        public static void SuppressReentrantWaits()
        {
            RuntimeThread.SuppressReentrantWaits();
        }

        public static void RestoreReentrantWaits()
        {
            RuntimeThread.RestoreReentrantWaits();
        }

        public static IntPtr GetCriticalHandle(CriticalHandle criticalHandle)
        {
            return criticalHandle.GetHandleInternal();
        }

        public static void SetCriticalHandle(CriticalHandle criticalHandle, IntPtr handle)
        {
            criticalHandle.SetHandleInternal(handle);
        }
    }
}