1 // ==++==
2 //
3 //   Copyright (c) Microsoft Corporation.  All rights reserved.
4 //
5 // ==--==
6 /*=============================================================================
7 **
8 ** Class: Marshal
9 **
10 **
11 ** Purpose: This class contains methods that are mainly used to marshal
12 **          between unmanaged and managed types.
13 **
14 **
15 =============================================================================*/
16 
17 namespace System.Runtime.InteropServices
18 {
19     using System;
20     using System.Collections.Generic;
21     using System.Reflection;
22     using System.Reflection.Emit;
23     using System.Security;
24     using System.Security.Permissions;
25     using System.Text;
26     using System.Threading;
27     using System.Runtime.Remoting;
28     using System.Runtime.CompilerServices;
29     using System.Globalization;
30     using System.Runtime.ConstrainedExecution;
31     using System.Runtime.Versioning;
32     using Win32Native = Microsoft.Win32.Win32Native;
33     using Microsoft.Win32.SafeHandles;
34     using System.Diagnostics.Contracts;
35     using System.Runtime.InteropServices.ComTypes;
36 
37     [Serializable]
38     public enum CustomQueryInterfaceMode
39     {
40         Ignore  = 0,
41         Allow = 1
42     }
43 
44     //========================================================================
45     // All public methods, including PInvoke, are protected with linkchecks.
46     // Remove the default demands for all PInvoke methods with this global
47     // declaration on the class.
48     //========================================================================
49 
50     #if FEATURE_CORECLR
51     [System.Security.SecurityCritical] // auto-generated
52     #endif
53     public static partial class Marshal
54     {
55         //====================================================================
56         // Defines used inside the Marshal class.
57         //====================================================================
58         private const int LMEM_FIXED = 0;
59 #if !FEATURE_PAL
60         private const int LMEM_MOVEABLE = 2;
61         private const long HIWORDMASK = unchecked((long)0xffffffffffff0000L);
62 #endif //!FEATURE_PAL
63 #if FEATURE_COMINTEROP
64         private static Guid IID_IUnknown = new Guid("00000000-0000-0000-C000-000000000046");
65 #endif //FEATURE_COMINTEROP
66 
67         // Win32 has the concept of Atoms, where a pointer can either be a pointer
68         // or an int.  If it's less than 64K, this is guaranteed to NOT be a
69         // pointer since the bottom 64K bytes are reserved in a process' page table.
70         // We should be careful about deallocating this stuff.  Extracted to
71         // a function to avoid C# problems with lack of support for IntPtr.
72         // We have 2 of these methods for slightly different semantics for NULL.
IsWin32Atom(IntPtr ptr)73         private static bool IsWin32Atom(IntPtr ptr)
74         {
75 #if FEATURE_PAL
76         return false;
77 #else
78             long lPtr = (long)ptr;
79             return 0 == (lPtr & HIWORDMASK);
80 #endif
81         }
82 
83         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
IsNotWin32Atom(IntPtr ptr)84         private static bool IsNotWin32Atom(IntPtr ptr)
85         {
86 #if FEATURE_PAL
87     return false;
88 #else
89             long lPtr = (long)ptr;
90             return 0 != (lPtr & HIWORDMASK);
91 #endif
92         }
93 
94         //====================================================================
95         // The default character size for the system. This is always 2 because
96         // the framework only runs on UTF-16 systems.
97         //====================================================================
98         public static readonly int SystemDefaultCharSize = 2;
99 
100         //====================================================================
101         // The max DBCS character size for the system.
102         //====================================================================
103         public static readonly int SystemMaxDBCSCharSize = GetSystemMaxDBCSCharSize();
104 
105 
106         //====================================================================
107         // The name, title and description of the assembly that will contain
108         // the dynamically generated interop types.
109         //====================================================================
110         private const String s_strConvertedTypeInfoAssemblyName   = "InteropDynamicTypes";
111         private const String s_strConvertedTypeInfoAssemblyTitle  = "Interop Dynamic Types";
112         private const String s_strConvertedTypeInfoAssemblyDesc   = "Type dynamically generated from ITypeInfo's";
113         private const String s_strConvertedTypeInfoNameSpace      = "InteropDynamicTypes";
114 
115 
116         //====================================================================
117         // Helper method to retrieve the system's maximum DBCS character size.
118         //====================================================================
119         [ResourceExposure(ResourceScope.None)]
120         [MethodImplAttribute(MethodImplOptions.InternalCall)]
GetSystemMaxDBCSCharSize()121         private static extern int GetSystemMaxDBCSCharSize();
122 
123         [System.Security.SecurityCritical]  // auto-generated_required
PtrToStringAnsi(IntPtr ptr)124         unsafe public static String PtrToStringAnsi(IntPtr ptr)
125         {
126             if (IntPtr.Zero == ptr) {
127                 return null;
128             }
129             else if (IsWin32Atom(ptr)) {
130                 return null;
131             }
132             else {
133                 int nb = Win32Native.lstrlenA(ptr);
134                 if( nb == 0) {
135                     return string.Empty;
136                 }
137                 else {
138                     return new String((sbyte *)ptr);
139                 }
140             }
141         }
142 
143         [System.Security.SecurityCritical]  // auto-generated_required
PtrToStringAnsi(IntPtr ptr, int len)144         unsafe public static String PtrToStringAnsi(IntPtr ptr, int len)
145         {
146             if (ptr == IntPtr.Zero)
147                 throw new ArgumentNullException("ptr");
148             if (len < 0)
149                 throw new ArgumentException("len");
150 
151             return new String((sbyte *)ptr, 0, len);
152         }
153 
154         [System.Security.SecurityCritical]  // auto-generated_required
PtrToStringUni(IntPtr ptr, int len)155         unsafe public static String PtrToStringUni(IntPtr ptr, int len)
156         {
157             if (ptr == IntPtr.Zero)
158                 throw new ArgumentNullException("ptr");
159             if (len < 0)
160                 throw new ArgumentException("len");
161 
162             return new String((char *)ptr, 0, len);
163         }
164 
165         [System.Security.SecurityCritical]  // auto-generated_required
PtrToStringAuto(IntPtr ptr, int len)166         public static String PtrToStringAuto(IntPtr ptr, int len)
167         {
168             // Ansi platforms are no longer supported
169             return PtrToStringUni(ptr, len);
170         }
171 
172         [System.Security.SecurityCritical]  // auto-generated_required
PtrToStringUni(IntPtr ptr)173         unsafe public static String PtrToStringUni(IntPtr ptr)
174         {
175             if (IntPtr.Zero == ptr) {
176                 return null;
177             }
178             else if (IsWin32Atom(ptr)) {
179                 return null;
180             }
181             else {
182                 return new String((char *)ptr);
183             }
184         }
185 
186         [System.Security.SecurityCritical]  // auto-generated_required
PtrToStringAuto(IntPtr ptr)187         public static String PtrToStringAuto(IntPtr ptr)
188         {
189             // Ansi platforms are no longer supported
190             return PtrToStringUni(ptr);
191         }
192 
193         //====================================================================
194         // SizeOf()
195         //====================================================================
196         [ResourceExposure(ResourceScope.None)]
197         [System.Runtime.InteropServices.ComVisible(true)]
SizeOf(Object structure)198         public static int SizeOf(Object structure)
199         {
200             if (structure == null)
201                 throw new ArgumentNullException("structure");
202             // we never had a check for generics here
203             Contract.EndContractBlock();
204 
205             return SizeOfHelper(structure.GetType(), true);
206         }
207 
SizeOf(T structure)208         public static int SizeOf<T>(T structure)
209         {
210             return SizeOf((object)structure);
211         }
212 
213         [ResourceExposure(ResourceScope.None)]
214         [Pure]
SizeOf(Type t)215         public static int SizeOf(Type t)
216         {
217             if (t == null)
218                 throw new ArgumentNullException("t");
219             if (!(t is RuntimeType))
220                 throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), "t");
221             if (t.IsGenericType)
222                 throw new ArgumentException(Environment.GetResourceString("Argument_NeedNonGenericType"), "t");
223             Contract.EndContractBlock();
224 
225             return SizeOfHelper(t, true);
226         }
227 
SizeOf()228         public static int SizeOf<T>()
229         {
230             return SizeOf(typeof(T));
231         }
232 
233 #if !FEATURE_CORECLR || FEATURE_CORESYSTEM
234         /// <summary>
235         /// Returns the aligned size of an instance of a value type.
236         /// </summary>
237         /// <typeparam name="T">Provide a value type to figure out its size</typeparam>
238         /// <returns>The aligned size of T in bytes.</returns>
239         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
240         internal static uint AlignedSizeOf<T>() where T : struct
241         {
242             uint size = SizeOfType(typeof(T));
243             if (size == 1 || size == 2)
244             {
245                 return size;
246             }
247             if (IntPtr.Size == 8 && size == 4)
248             {
249                 return size;
250             }
251             return AlignedSizeOfType(typeof(T));
252         }
253 
254         // Type must be a value type with no object reference fields.  We only
255         // assert this, due to the lack of a suitable generic constraint.
256         [MethodImpl(MethodImplOptions.InternalCall)]
257         [ResourceExposure(ResourceScope.None)]
258         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
SizeOfType(Type type)259         internal static extern uint SizeOfType(Type type);
260 
261         // Type must be a value type with no object reference fields.  We only
262         // assert this, due to the lack of a suitable generic constraint.
263         [MethodImpl(MethodImplOptions.InternalCall)]
264         [ResourceExposure(ResourceScope.None)]
265         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
AlignedSizeOfType(Type type)266         private static extern uint AlignedSizeOfType(Type type);
267 #endif // !FEATURE_CORECLR || FEATURE_CORESYSTEM
268 
269 #if !FEATURE_CORECLR // Marshal is critical in CoreCLR, so SafeCritical members trigger Annotator violations
270         [System.Security.SecuritySafeCritical]
271 #endif // !FEATURE_CORECLR
272         [ResourceExposure(ResourceScope.None)]
273         [MethodImplAttribute(MethodImplOptions.InternalCall)]
SizeOfHelper(Type t, bool throwIfNotMarshalable)274         internal static extern int SizeOfHelper(Type t, bool throwIfNotMarshalable);
275 
276         //====================================================================
277         // OffsetOf()
278         //====================================================================
OffsetOf(Type t, String fieldName)279         public static IntPtr OffsetOf(Type t, String fieldName)
280         {
281             if (t == null)
282                 throw new ArgumentNullException("t");
283             Contract.EndContractBlock();
284 
285             FieldInfo f = t.GetField(fieldName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
286             if (f == null)
287                 throw new ArgumentException(Environment.GetResourceString("Argument_OffsetOfFieldNotFound", t.FullName), "fieldName");
288             RtFieldInfo rtField = f as RtFieldInfo;
289             if (rtField == null)
290                 throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeFieldInfo"), "fieldName");
291 
292             return OffsetOfHelper(rtField);
293         }
OffsetOf(string fieldName)294         public static IntPtr OffsetOf<T>(string fieldName)
295         {
296             return OffsetOf(typeof(T), fieldName);
297         }
298 
299         [ResourceExposure(ResourceScope.None)]
300         [MethodImplAttribute(MethodImplOptions.InternalCall)]
OffsetOfHelper(IRuntimeFieldInfo f)301         private static extern IntPtr OffsetOfHelper(IRuntimeFieldInfo f);
302 
303         //====================================================================
304         // UnsafeAddrOfPinnedArrayElement()
305         //
306         // IMPORTANT NOTICE: This method does not do any verification on the
307         // array. It must be used with EXTREME CAUTION since passing in
308         // an array that is not pinned or in the fixed heap can cause
309         // unexpected results !
310         //====================================================================
311         [System.Security.SecurityCritical]  // auto-generated_required
312         [ResourceExposure(ResourceScope.None)]
313         [MethodImplAttribute(MethodImplOptions.InternalCall)]
UnsafeAddrOfPinnedArrayElement(Array arr, int index)314         public static extern IntPtr UnsafeAddrOfPinnedArrayElement(Array arr, int index);
315 
316         [System.Security.SecurityCritical]
UnsafeAddrOfPinnedArrayElement(T[] arr, int index)317         public static IntPtr UnsafeAddrOfPinnedArrayElement<T>(T[] arr, int index)
318         {
319             return UnsafeAddrOfPinnedArrayElement((Array)arr, index);
320         }
321 
322         //====================================================================
323         // Copy blocks from CLR arrays to native memory.
324         //====================================================================
325         [System.Security.SecurityCritical]  // auto-generated_required
Copy(int[] source, int startIndex, IntPtr destination, int length)326         public static void Copy(int[]     source, int startIndex, IntPtr destination, int length)
327         {
328             CopyToNative(source, startIndex, destination, length);
329         }
330         [System.Security.SecurityCritical]  // auto-generated_required
Copy(char[] source, int startIndex, IntPtr destination, int length)331         public static void Copy(char[]    source, int startIndex, IntPtr destination, int length)
332         {
333             CopyToNative(source, startIndex, destination, length);
334         }
335         [System.Security.SecurityCritical]  // auto-generated_required
Copy(short[] source, int startIndex, IntPtr destination, int length)336         public static void Copy(short[]   source, int startIndex, IntPtr destination, int length)
337         {
338             CopyToNative(source, startIndex, destination, length);
339         }
340         [System.Security.SecurityCritical]  // auto-generated_required
Copy(long[] source, int startIndex, IntPtr destination, int length)341         public static void Copy(long[]    source, int startIndex, IntPtr destination, int length)
342         {
343             CopyToNative(source, startIndex, destination, length);
344         }
345         [System.Security.SecurityCritical]  // auto-generated_required
Copy(float[] source, int startIndex, IntPtr destination, int length)346         public static void Copy(float[]   source, int startIndex, IntPtr destination, int length)
347         {
348             CopyToNative(source, startIndex, destination, length);
349         }
350         [System.Security.SecurityCritical]  // auto-generated_required
Copy(double[] source, int startIndex, IntPtr destination, int length)351         public static void Copy(double[]  source, int startIndex, IntPtr destination, int length)
352         {
353             CopyToNative(source, startIndex, destination, length);
354         }
355         [System.Security.SecurityCritical]  // auto-generated_required
Copy(byte[] source, int startIndex, IntPtr destination, int length)356         public static void Copy(byte[] source, int startIndex, IntPtr destination, int length)
357         {
358             CopyToNative(source, startIndex, destination, length);
359         }
360         [System.Security.SecurityCritical]  // auto-generated_required
Copy(IntPtr[] source, int startIndex, IntPtr destination, int length)361         public static void Copy(IntPtr[] source, int startIndex, IntPtr destination, int length)
362         {
363             CopyToNative(source, startIndex, destination, length);
364         }
365         [ResourceExposure(ResourceScope.None)]
366         [MethodImplAttribute(MethodImplOptions.InternalCall)]
CopyToNative(Object source, int startIndex, IntPtr destination, int length)367         private static extern void CopyToNative(Object source, int startIndex, IntPtr destination, int length);
368 
369         //====================================================================
370         // Copy blocks from native memory to CLR arrays
371         //====================================================================
372         [System.Security.SecurityCritical]  // auto-generated_required
Copy(IntPtr source, int[] destination, int startIndex, int length)373         public static void Copy(IntPtr source, int[]     destination, int startIndex, int length)
374         {
375             CopyToManaged(source, destination, startIndex, length);
376         }
377         [System.Security.SecurityCritical]  // auto-generated_required
Copy(IntPtr source, char[] destination, int startIndex, int length)378         public static void Copy(IntPtr source, char[]    destination, int startIndex, int length)
379         {
380             CopyToManaged(source, destination, startIndex, length);
381         }
382         [System.Security.SecurityCritical]  // auto-generated_required
Copy(IntPtr source, short[] destination, int startIndex, int length)383         public static void Copy(IntPtr source, short[]   destination, int startIndex, int length)
384         {
385             CopyToManaged(source, destination, startIndex, length);
386         }
387         [System.Security.SecurityCritical]  // auto-generated_required
Copy(IntPtr source, long[] destination, int startIndex, int length)388         public static void Copy(IntPtr source, long[]    destination, int startIndex, int length)
389         {
390             CopyToManaged(source, destination, startIndex, length);
391         }
392         [System.Security.SecurityCritical]  // auto-generated_required
Copy(IntPtr source, float[] destination, int startIndex, int length)393         public static void Copy(IntPtr source, float[]   destination, int startIndex, int length)
394         {
395             CopyToManaged(source, destination, startIndex, length);
396         }
397         [System.Security.SecurityCritical]  // auto-generated_required
Copy(IntPtr source, double[] destination, int startIndex, int length)398         public static void Copy(IntPtr source, double[]  destination, int startIndex, int length)
399         {
400             CopyToManaged(source, destination, startIndex, length);
401         }
402         [System.Security.SecurityCritical]  // auto-generated_required
Copy(IntPtr source, byte[] destination, int startIndex, int length)403         public static void Copy(IntPtr source, byte[] destination, int startIndex, int length)
404         {
405             CopyToManaged(source, destination, startIndex, length);
406         }
407         [System.Security.SecurityCritical]  // auto-generated_required
Copy(IntPtr source, IntPtr[] destination, int startIndex, int length)408         public static void Copy(IntPtr source, IntPtr[] destination, int startIndex, int length)
409         {
410             CopyToManaged(source, destination, startIndex, length);
411         }
412         [ResourceExposure(ResourceScope.None)]
413         [MethodImplAttribute(MethodImplOptions.InternalCall)]
CopyToManaged(IntPtr source, Object destination, int startIndex, int length)414         private static extern void CopyToManaged(IntPtr source, Object destination, int startIndex, int length);
415 
416         //====================================================================
417         // Read from memory
418         //====================================================================
419         [DllImport(Win32Native.SHIM, EntryPoint="ND_RU1")]
420         [ResourceExposure(ResourceScope.None)]
421         [SuppressUnmanagedCodeSecurity]
422         [System.Security.SecurityCritical]  // auto-generated
ReadByte([MarshalAs(UnmanagedType.AsAny), In] Object ptr, int ofs)423         public static extern byte ReadByte([MarshalAs(UnmanagedType.AsAny), In] Object ptr, int ofs);
424 
425         [System.Security.SecurityCritical]  // auto-generated_required
426         [ResourceExposure(ResourceScope.None)]
ReadByte(IntPtr ptr, int ofs)427         public static unsafe byte ReadByte(IntPtr ptr, int ofs)
428         {
429             try
430             {
431                 byte *addr = (byte *)ptr + ofs;
432                 return *addr;
433             }
434             catch (NullReferenceException)
435             {
436                 // this method is documented to throw AccessViolationException on any AV
437                 throw new AccessViolationException();
438             }
439         }
440 
441         [System.Security.SecurityCritical]  // auto-generated_required
ReadByte(IntPtr ptr)442         public static byte ReadByte(IntPtr ptr)
443         {
444             return ReadByte(ptr,0);
445         }
446 
447         [DllImport(Win32Native.SHIM, EntryPoint="ND_RI2")]
448         [ResourceExposure(ResourceScope.None)]
449         [SuppressUnmanagedCodeSecurity]
450         [System.Security.SecurityCritical]  // auto-generated
ReadInt16([MarshalAs(UnmanagedType.AsAny),In] Object ptr, int ofs)451         public static extern short ReadInt16([MarshalAs(UnmanagedType.AsAny),In] Object ptr, int ofs);
452 
453         [System.Security.SecurityCritical]  // auto-generated_required
454         [ResourceExposure(ResourceScope.None)]
ReadInt16(IntPtr ptr, int ofs)455         public static unsafe short ReadInt16(IntPtr ptr, int ofs)
456         {
457             try
458             {
459                 byte *addr = (byte *)ptr + ofs;
460                 if ((unchecked((int)addr) & 0x1) == 0)
461                 {
462                     // aligned read
463                     return *((short *)addr);
464                 }
465                 else
466                 {
467                     // unaligned read
468                     short val;
469                     byte *valPtr = (byte *)&val;
470                     valPtr[0] = addr[0];
471                     valPtr[1] = addr[1];
472                     return val;
473                 }
474             }
475             catch (NullReferenceException)
476             {
477                 // this method is documented to throw AccessViolationException on any AV
478                 throw new AccessViolationException();
479             }
480         }
481 
482         [System.Security.SecurityCritical]  // auto-generated_required
ReadInt16(IntPtr ptr)483         public static short ReadInt16(IntPtr ptr)
484         {
485             return ReadInt16(ptr, 0);
486         }
487 
488         [DllImport(Win32Native.SHIM, EntryPoint="ND_RI4"), ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
489         [ResourceExposure(ResourceScope.None)]
490         [SuppressUnmanagedCodeSecurity]
491         [System.Security.SecurityCritical]  // auto-generated
ReadInt32([MarshalAs(UnmanagedType.AsAny),In] Object ptr, int ofs)492         public static extern int ReadInt32([MarshalAs(UnmanagedType.AsAny),In] Object ptr, int ofs);
493 
494         [System.Security.SecurityCritical]  // auto-generated_required
495         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
496         [ResourceExposure(ResourceScope.None)]
ReadInt32(IntPtr ptr, int ofs)497         public static unsafe int ReadInt32(IntPtr ptr, int ofs)
498         {
499             try
500             {
501                 byte *addr = (byte *)ptr + ofs;
502                 if ((unchecked((int)addr) & 0x3) == 0)
503                 {
504                     // aligned read
505                     return *((int *)addr);
506                 }
507                 else
508                 {
509                     // unaligned read
510                     int val;
511                     byte *valPtr = (byte *)&val;
512                     valPtr[0] = addr[0];
513                     valPtr[1] = addr[1];
514                     valPtr[2] = addr[2];
515                     valPtr[3] = addr[3];
516                     return val;
517                 }
518             }
519             catch (NullReferenceException)
520             {
521                 // this method is documented to throw AccessViolationException on any AV
522                 throw new AccessViolationException();
523             }
524         }
525 
526         [System.Security.SecurityCritical]  // auto-generated_required
527         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
ReadInt32(IntPtr ptr)528         public static int ReadInt32(IntPtr ptr)
529         {
530             return ReadInt32(ptr,0);
531         }
532 
533         [System.Security.SecurityCritical]  // auto-generated_required
534         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
ReadIntPtr([MarshalAs(UnmanagedType.AsAny),In] Object ptr, int ofs)535         public static IntPtr ReadIntPtr([MarshalAs(UnmanagedType.AsAny),In] Object ptr, int ofs)
536         {
537             #if WIN32
538                 return (IntPtr) ReadInt32(ptr, ofs);
539             #else
540                 return (IntPtr) ReadInt64(ptr, ofs);
541             #endif
542         }
543 
544         [System.Security.SecurityCritical]  // auto-generated_required
545         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
ReadIntPtr(IntPtr ptr, int ofs)546         public static IntPtr ReadIntPtr(IntPtr ptr, int ofs)
547         {
548             #if WIN32
549                 return (IntPtr) ReadInt32(ptr, ofs);
550             #else
551                 return (IntPtr) ReadInt64(ptr, ofs);
552             #endif
553         }
554 
555         [System.Security.SecurityCritical]  // auto-generated_required
556         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
ReadIntPtr(IntPtr ptr)557         public static IntPtr ReadIntPtr(IntPtr ptr)
558         {
559             #if WIN32
560                 return (IntPtr) ReadInt32(ptr, 0);
561             #else
562                 return (IntPtr) ReadInt64(ptr, 0);
563             #endif
564         }
565 
566         [DllImport(Win32Native.SHIM, EntryPoint="ND_RI8"), ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
567         [ResourceExposure(ResourceScope.None)]
568         [SuppressUnmanagedCodeSecurity]
569         [System.Security.SecurityCritical]  // auto-generated
ReadInt64([MarshalAs(UnmanagedType.AsAny),In] Object ptr, int ofs)570         public static extern long ReadInt64([MarshalAs(UnmanagedType.AsAny),In] Object ptr, int ofs);
571 
572         [System.Security.SecurityCritical]  // auto-generated_required
573         [ResourceExposure(ResourceScope.None)]
ReadInt64(IntPtr ptr, int ofs)574         public static unsafe long ReadInt64(IntPtr ptr, int ofs)
575         {
576             try
577             {
578                 byte *addr = (byte *)ptr + ofs;
579                 if ((unchecked((int)addr) & 0x7) == 0)
580                 {
581                     // aligned read
582                     return *((long *)addr);
583                 }
584                 else
585                 {
586                     // unaligned read
587                     long val;
588                     byte *valPtr = (byte *)&val;
589                     valPtr[0] = addr[0];
590                     valPtr[1] = addr[1];
591                     valPtr[2] = addr[2];
592                     valPtr[3] = addr[3];
593                     valPtr[4] = addr[4];
594                     valPtr[5] = addr[5];
595                     valPtr[6] = addr[6];
596                     valPtr[7] = addr[7];
597                     return val;
598                 }
599             }
600             catch (NullReferenceException)
601             {
602                 // this method is documented to throw AccessViolationException on any AV
603                 throw new AccessViolationException();
604             }
605         }
606 
607         [System.Security.SecurityCritical]  // auto-generated_required
608         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
ReadInt64(IntPtr ptr)609         public static long ReadInt64(IntPtr ptr)
610         {
611             return ReadInt64(ptr,0);
612         }
613 
614 
615         //====================================================================
616         // Write to memory
617         //====================================================================
618         [System.Security.SecurityCritical]  // auto-generated_required
619         [ResourceExposure(ResourceScope.None)]
WriteByte(IntPtr ptr, int ofs, byte val)620         public static unsafe void WriteByte(IntPtr ptr, int ofs, byte val)
621         {
622             try
623             {
624                 byte *addr = (byte *)ptr + ofs;
625                 *addr = val;
626             }
627             catch (NullReferenceException)
628             {
629                 // this method is documented to throw AccessViolationException on any AV
630                 throw new AccessViolationException();
631             }
632         }
633 
634         [DllImport(Win32Native.SHIM, EntryPoint="ND_WU1")]
635         [ResourceExposure(ResourceScope.None)]
636         [SuppressUnmanagedCodeSecurity]
637         [System.Security.SecurityCritical]  // auto-generated
WriteByte([MarshalAs(UnmanagedType.AsAny),In,Out] Object ptr, int ofs, byte val)638         public static extern void WriteByte([MarshalAs(UnmanagedType.AsAny),In,Out] Object ptr, int ofs, byte val);
639 
640         [System.Security.SecurityCritical]  // auto-generated_required
WriteByte(IntPtr ptr, byte val)641         public static void WriteByte(IntPtr ptr, byte val)
642         {
643             WriteByte(ptr, 0, val);
644         }
645 
646         [System.Security.SecurityCritical]  // auto-generated_required
647         [ResourceExposure(ResourceScope.None)]
WriteInt16(IntPtr ptr, int ofs, short val)648         public static unsafe void WriteInt16(IntPtr ptr, int ofs, short val)
649         {
650             try
651             {
652                 byte *addr = (byte *)ptr + ofs;
653                 if ((unchecked((int)addr) & 0x1) == 0)
654                 {
655                     // aligned write
656                     *((short *)addr) = val;
657                 }
658                 else
659                 {
660                     // unaligned write
661                     byte *valPtr = (byte *)&val;
662                     addr[0] = valPtr[0];
663                     addr[1] = valPtr[1];
664                 }
665             }
666             catch (NullReferenceException)
667             {
668                 // this method is documented to throw AccessViolationException on any AV
669                 throw new AccessViolationException();
670             }
671         }
672 
673         [DllImport(Win32Native.SHIM, EntryPoint="ND_WI2")]
674         [ResourceExposure(ResourceScope.None)]
675         [SuppressUnmanagedCodeSecurity]
676         [System.Security.SecurityCritical]  // auto-generated
WriteInt16([MarshalAs(UnmanagedType.AsAny),In,Out] Object ptr, int ofs, short val)677         public static extern void WriteInt16([MarshalAs(UnmanagedType.AsAny),In,Out] Object ptr, int ofs, short val);
678 
679         [System.Security.SecurityCritical]  // auto-generated_required
WriteInt16(IntPtr ptr, short val)680         public static void WriteInt16(IntPtr ptr, short val)
681         {
682             WriteInt16(ptr, 0, val);
683         }
684 
685         [System.Security.SecurityCritical]  // auto-generated_required
WriteInt16(IntPtr ptr, int ofs, char val)686         public static void WriteInt16(IntPtr ptr, int ofs, char val)
687         {
688             WriteInt16(ptr, ofs, (short)val);
689         }
690 
691         [System.Security.SecurityCritical]  // auto-generated_required
WriteInt16([In,Out]Object ptr, int ofs, char val)692         public static void WriteInt16([In,Out]Object ptr, int ofs, char val)
693         {
694             WriteInt16(ptr, ofs, (short)val);
695         }
696 
697         [System.Security.SecurityCritical]  // auto-generated_required
WriteInt16(IntPtr ptr, char val)698         public static void WriteInt16(IntPtr ptr, char val)
699         {
700             WriteInt16(ptr, 0, (short)val);
701         }
702 
703         [System.Security.SecurityCritical]  // auto-generated_required
704         [ResourceExposure(ResourceScope.None)]
WriteInt32(IntPtr ptr, int ofs, int val)705         public static unsafe void WriteInt32(IntPtr ptr, int ofs, int val)
706         {
707             try
708             {
709                 byte *addr = (byte *)ptr + ofs;
710                 if ((unchecked((int)addr) & 0x3) == 0)
711                 {
712                     // aligned write
713                     *((int *)addr) = val;
714                 }
715                 else
716                 {
717                     // unaligned write
718                     byte *valPtr = (byte *)&val;
719                     addr[0] = valPtr[0];
720                     addr[1] = valPtr[1];
721                     addr[2] = valPtr[2];
722                     addr[3] = valPtr[3];
723                 }
724             }
725             catch (NullReferenceException)
726             {
727                 // this method is documented to throw AccessViolationException on any AV
728                 throw new AccessViolationException();
729             }
730         }
731 
732         [DllImport(Win32Native.SHIM, EntryPoint="ND_WI4")]
733         [ResourceExposure(ResourceScope.None)]
734         [SuppressUnmanagedCodeSecurity]
735         [System.Security.SecurityCritical]  // auto-generated
WriteInt32([MarshalAs(UnmanagedType.AsAny),In,Out] Object ptr, int ofs, int val)736         public static extern void WriteInt32([MarshalAs(UnmanagedType.AsAny),In,Out] Object ptr, int ofs, int val);
737 
738         [System.Security.SecurityCritical]  // auto-generated_required
WriteInt32(IntPtr ptr, int val)739         public static void WriteInt32(IntPtr ptr, int val)
740         {
741             WriteInt32(ptr,0,val);
742         }
743 
744         [System.Security.SecurityCritical]  // auto-generated_required
WriteIntPtr(IntPtr ptr, int ofs, IntPtr val)745         public static void WriteIntPtr(IntPtr ptr, int ofs, IntPtr val)
746         {
747             #if WIN32
748                 WriteInt32(ptr, ofs, (int)val);
749             #else
750                 WriteInt64(ptr, ofs, (long)val);
751             #endif
752         }
753 
754         [System.Security.SecurityCritical]  // auto-generated_required
WriteIntPtr([MarshalAs(UnmanagedType.AsAny),In,Out] Object ptr, int ofs, IntPtr val)755         public static void WriteIntPtr([MarshalAs(UnmanagedType.AsAny),In,Out] Object ptr, int ofs, IntPtr val)
756         {
757             #if WIN32
758                 WriteInt32(ptr, ofs, (int)val);
759             #else
760                 WriteInt64(ptr, ofs, (long)val);
761             #endif
762         }
763 
764         [System.Security.SecurityCritical]  // auto-generated_required
WriteIntPtr(IntPtr ptr, IntPtr val)765         public static void WriteIntPtr(IntPtr ptr, IntPtr val)
766         {
767             #if WIN32
768                 WriteInt32(ptr, 0, (int)val);
769             #else
770                 WriteInt64(ptr, 0, (long)val);
771             #endif
772         }
773 
774         [System.Security.SecurityCritical]  // auto-generated_required
775         [ResourceExposure(ResourceScope.None)]
WriteInt64(IntPtr ptr, int ofs, long val)776         public static unsafe void WriteInt64(IntPtr ptr, int ofs, long val)
777         {
778             try
779             {
780                 byte *addr = (byte *)ptr + ofs;
781                 if ((unchecked((int)addr) & 0x7) == 0)
782                 {
783                     // aligned write
784                     *((long *)addr) = val;
785                 }
786                 else
787                 {
788                     // unaligned write
789                     byte *valPtr = (byte *)&val;
790                     addr[0] = valPtr[0];
791                     addr[1] = valPtr[1];
792                     addr[2] = valPtr[2];
793                     addr[3] = valPtr[3];
794                     addr[4] = valPtr[4];
795                     addr[5] = valPtr[5];
796                     addr[6] = valPtr[6];
797                     addr[7] = valPtr[7];
798                 }
799             }
800             catch (NullReferenceException)
801             {
802                 // this method is documented to throw AccessViolationException on any AV
803                 throw new AccessViolationException();
804             }
805         }
806 
807         [DllImport(Win32Native.SHIM, EntryPoint="ND_WI8")]
808         [ResourceExposure(ResourceScope.None)]
809         [SuppressUnmanagedCodeSecurity]
810         [System.Security.SecurityCritical]  // auto-generated
WriteInt64([MarshalAs(UnmanagedType.AsAny),In,Out] Object ptr, int ofs, long val)811         public static extern void WriteInt64([MarshalAs(UnmanagedType.AsAny),In,Out] Object ptr, int ofs, long val);
812 
813         [System.Security.SecurityCritical]  // auto-generated_required
WriteInt64(IntPtr ptr, long val)814         public static void WriteInt64(IntPtr ptr, long val)
815         {
816             WriteInt64(ptr, 0, val);
817         }
818 
819 
820         //====================================================================
821         // GetLastWin32Error
822         //====================================================================
823         [System.Security.SecurityCritical]  // auto-generated_required
824         [ResourceExposure(ResourceScope.None)]
825         [MethodImplAttribute(MethodImplOptions.InternalCall)]
826         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
GetLastWin32Error()827         public static extern int GetLastWin32Error();
828 
829 
830         //====================================================================
831         // SetLastWin32Error
832         //====================================================================
833         [ResourceExposure(ResourceScope.None)]
834         [MethodImplAttribute(MethodImplOptions.InternalCall)]
835         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
SetLastWin32Error(int error)836         internal static extern void SetLastWin32Error(int error);
837 
838 
839         //====================================================================
840         // GetHRForLastWin32Error
841         //====================================================================
842         [System.Security.SecurityCritical]  // auto-generated_required
843         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
GetHRForLastWin32Error()844         public static int GetHRForLastWin32Error()
845         {
846             int dwLastError = GetLastWin32Error();
847             if ((dwLastError & 0x80000000) == 0x80000000)
848                 return dwLastError;
849             else
850                 return (dwLastError & 0x0000FFFF) | unchecked((int)0x80070000);
851         }
852 
853 
854         //====================================================================
855         // Prelink
856         //====================================================================
857         [System.Security.SecurityCritical]  // auto-generated_required
Prelink(MethodInfo m)858         public static void Prelink(MethodInfo m)
859         {
860             if (m == null)
861                 throw new ArgumentNullException("m");
862             Contract.EndContractBlock();
863 
864             RuntimeMethodInfo rmi = m as RuntimeMethodInfo;
865 
866             if (rmi == null)
867                 throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo"));
868 
869             InternalPrelink(rmi);
870         }
871 
872         [ResourceExposure(ResourceScope.None)]
873         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
874         [SecurityCritical]
InternalPrelink(IRuntimeMethodInfo m)875         private static extern void InternalPrelink(IRuntimeMethodInfo m);
876 
877         [System.Security.SecurityCritical]  // auto-generated_required
PrelinkAll(Type c)878         public static void PrelinkAll(Type c)
879         {
880             if (c == null)
881                 throw new ArgumentNullException("c");
882             Contract.EndContractBlock();
883 
884             MethodInfo[] mi = c.GetMethods();
885             if (mi != null)
886             {
887                 for (int i = 0; i < mi.Length; i++)
888                 {
889                     Prelink(mi[i]);
890                 }
891             }
892         }
893 
894         //====================================================================
895         // NumParamBytes
896         //====================================================================
897         [System.Security.SecurityCritical]  // auto-generated_required
NumParamBytes(MethodInfo m)898         public static int NumParamBytes(MethodInfo m)
899         {
900             if (m == null)
901                 throw new ArgumentNullException("m");
902             Contract.EndContractBlock();
903 
904             RuntimeMethodInfo rmi = m as RuntimeMethodInfo;
905             if (rmi == null)
906                 throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo"));
907 
908             return InternalNumParamBytes(rmi);
909         }
910 
911         [ResourceExposure(ResourceScope.None)]
912         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
913         [SecurityCritical]
InternalNumParamBytes(IRuntimeMethodInfo m)914         private static extern int InternalNumParamBytes(IRuntimeMethodInfo m);
915 
916         //====================================================================
917         // Win32 Exception stuff
918         // These are mostly interesting for Structured exception handling,
919         // but need to be exposed for all exceptions (not just SEHException).
920         //====================================================================
921         [System.Security.SecurityCritical]  // auto-generated_required
922         [ResourceExposure(ResourceScope.None)]
923         [MethodImplAttribute(MethodImplOptions.InternalCall)]
924         [System.Runtime.InteropServices.ComVisible(true)]
GetExceptionPointers()925         public static extern /* struct _EXCEPTION_POINTERS* */ IntPtr GetExceptionPointers();
926 
927         [System.Security.SecurityCritical]  // auto-generated_required
928         [ResourceExposure(ResourceScope.None)]
929         [MethodImplAttribute(MethodImplOptions.InternalCall)]
GetExceptionCode()930         public static extern int GetExceptionCode();
931 
932 
933         //====================================================================
934         // Marshals data from a structure class to a native memory block.
935         // If the structure contains pointers to allocated blocks and
936         // "fDeleteOld" is true, this routine will call DestroyStructure() first.
937         //====================================================================
938         [System.Security.SecurityCritical]  // auto-generated_required
939         [ResourceExposure(ResourceScope.None)]
940         [MethodImplAttribute(MethodImplOptions.InternalCall), ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
941         [System.Runtime.InteropServices.ComVisible(true)]
StructureToPtr(Object structure, IntPtr ptr, bool fDeleteOld)942         public static extern void StructureToPtr(Object structure, IntPtr ptr, bool fDeleteOld);
943 
944         [System.Security.SecurityCritical]
StructureToPtr(T structure, IntPtr ptr, bool fDeleteOld)945         public static void StructureToPtr<T>(T structure, IntPtr ptr, bool fDeleteOld)
946         {
947             StructureToPtr((object)structure, ptr, fDeleteOld);
948         }
949 
950         //====================================================================
951         // Marshals data from a native memory block to a preallocated structure class.
952         //====================================================================
953         [System.Security.SecurityCritical]  // auto-generated_required
954         [System.Runtime.InteropServices.ComVisible(true)]
PtrToStructure(IntPtr ptr, Object structure)955         public static void PtrToStructure(IntPtr ptr, Object structure)
956         {
957             PtrToStructureHelper(ptr, structure, false);
958         }
959 
960         [System.Security.SecurityCritical]
PtrToStructure(IntPtr ptr, T structure)961         public static void PtrToStructure<T>(IntPtr ptr, T structure)
962         {
963             PtrToStructure(ptr, (object)structure);
964         }
965 
966         //====================================================================
967         // Creates a new instance of "structuretype" and marshals data from a
968         // native memory block to it.
969         //====================================================================
970         [System.Security.SecurityCritical]  // auto-generated_required
971         [System.Runtime.InteropServices.ComVisible(true)]
972         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
PtrToStructure(IntPtr ptr, Type structureType)973         public static Object PtrToStructure(IntPtr ptr, Type structureType)
974         {
975             if (ptr == IntPtr.Zero) return null;
976 
977             if (structureType == null)
978                 throw new ArgumentNullException("structureType");
979 
980             if (structureType.IsGenericType)
981                 throw new ArgumentException(Environment.GetResourceString("Argument_NeedNonGenericType"), "structureType");
982 
983             RuntimeType rt = structureType.UnderlyingSystemType as RuntimeType;
984 
985             if (rt == null)
986                 throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "type");
987 
988             StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
989 
990             Object structure = rt.CreateInstanceDefaultCtor(false /*publicOnly*/, false /*skipCheckThis*/, false /*fillCache*/, ref stackMark);
991             PtrToStructureHelper(ptr, structure, true);
992             return structure;
993         }
994 
995         [System.Security.SecurityCritical]
PtrToStructure(IntPtr ptr)996         public static T PtrToStructure<T>(IntPtr ptr)
997         {
998             return (T)PtrToStructure(ptr, typeof(T));
999         }
1000 
1001         //====================================================================
1002         // Helper function to copy a pointer into a preallocated structure.
1003         //====================================================================
1004         [ResourceExposure(ResourceScope.None)]
1005         [MethodImplAttribute(MethodImplOptions.InternalCall)]
PtrToStructureHelper(IntPtr ptr, Object structure, bool allowValueClasses)1006         private static extern void PtrToStructureHelper(IntPtr ptr, Object structure, bool allowValueClasses);
1007 
1008 
1009         //====================================================================
1010         // Freeds all substructures pointed to by the native memory block.
1011         // "structureclass" is used to provide layout information.
1012         //====================================================================
1013         [System.Security.SecurityCritical]  // auto-generated_required
1014         [ResourceExposure(ResourceScope.None)]
1015         [MethodImplAttribute(MethodImplOptions.InternalCall)]
1016         [System.Runtime.InteropServices.ComVisible(true)]
DestroyStructure(IntPtr ptr, Type structuretype)1017         public static extern void DestroyStructure(IntPtr ptr, Type structuretype);
1018 
1019         [System.Security.SecurityCritical]
DestroyStructure(IntPtr ptr)1020         public static void DestroyStructure<T>(IntPtr ptr)
1021         {
1022             DestroyStructure(ptr, typeof(T));
1023         }
1024 
1025         //====================================================================
1026         // Returns the HInstance for this module.  Returns -1 if the module
1027         // doesn't have an HInstance.  In Memory (Dynamic) Modules won't have
1028         // an HInstance.
1029         //====================================================================
1030         [System.Security.SecurityCritical]  // auto-generated_required
1031         [ResourceExposure(ResourceScope.Machine)]
1032         [ResourceConsumption(ResourceScope.Machine)]
GetHINSTANCE(Module m)1033         public static IntPtr GetHINSTANCE(Module m)
1034         {
1035             if (m == null)
1036                 throw new ArgumentNullException("m");
1037             Contract.EndContractBlock();
1038 
1039             RuntimeModule rtModule = m as RuntimeModule;
1040             if (rtModule == null)
1041             {
1042                 ModuleBuilder mb = m as ModuleBuilder;
1043                 if (mb != null)
1044                     rtModule = mb.InternalModule;
1045             }
1046 
1047             if (rtModule == null)
1048                 throw new ArgumentNullException(Environment.GetResourceString("Argument_MustBeRuntimeModule"));
1049 
1050             return GetHINSTANCE(rtModule.GetNativeHandle());
1051         }
1052 
1053         [System.Security.SecurityCritical]  // auto-generated_required
1054         [ResourceExposure(ResourceScope.Machine)]
1055         [SuppressUnmanagedCodeSecurity]
1056         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
GetHINSTANCE(RuntimeModule m)1057         private extern static IntPtr GetHINSTANCE(RuntimeModule m);
1058 
1059         //====================================================================
1060         // Throws a CLR exception based on the HRESULT.
1061         //====================================================================
1062         [System.Security.SecurityCritical]  // auto-generated_required
ThrowExceptionForHR(int errorCode)1063         public static void ThrowExceptionForHR(int errorCode)
1064         {
1065             if (errorCode < 0)
1066                 ThrowExceptionForHRInternal(errorCode, IntPtr.Zero);
1067         }
1068         [System.Security.SecurityCritical]  // auto-generated_required
ThrowExceptionForHR(int errorCode, IntPtr errorInfo)1069         public static void ThrowExceptionForHR(int errorCode, IntPtr errorInfo)
1070         {
1071             if (errorCode < 0)
1072                 ThrowExceptionForHRInternal(errorCode, errorInfo);
1073         }
1074 
1075         [ResourceExposure(ResourceScope.None)]
1076         [MethodImplAttribute(MethodImplOptions.InternalCall)]
ThrowExceptionForHRInternal(int errorCode, IntPtr errorInfo)1077         internal static extern void ThrowExceptionForHRInternal(int errorCode, IntPtr errorInfo);
1078 
1079 
1080         //====================================================================
1081         // Converts the HRESULT to a CLR exception.
1082         //====================================================================
1083         [System.Security.SecurityCritical]  // auto-generated_required
GetExceptionForHR(int errorCode)1084         public static Exception GetExceptionForHR(int errorCode)
1085         {
1086             if (errorCode < 0)
1087                 return GetExceptionForHRInternal(errorCode, IntPtr.Zero);
1088             else
1089                 return null;
1090         }
1091         [System.Security.SecurityCritical]  // auto-generated_required
GetExceptionForHR(int errorCode, IntPtr errorInfo)1092         public static Exception GetExceptionForHR(int errorCode, IntPtr errorInfo)
1093         {
1094             if (errorCode < 0)
1095                 return GetExceptionForHRInternal(errorCode, errorInfo);
1096             else
1097                 return null;
1098         }
1099 
1100         [ResourceExposure(ResourceScope.None)]
1101         [MethodImplAttribute(MethodImplOptions.InternalCall)]
GetExceptionForHRInternal(int errorCode, IntPtr errorInfo)1102         internal static extern Exception GetExceptionForHRInternal(int errorCode, IntPtr errorInfo);
1103 
1104 
1105         //====================================================================
1106         // Converts the CLR exception to an HRESULT. This function also sets
1107         // up an IErrorInfo for the exception.
1108         //====================================================================
1109         [System.Security.SecurityCritical]  // auto-generated_required
1110         [ResourceExposure(ResourceScope.None)]
1111         [MethodImplAttribute(MethodImplOptions.InternalCall)]
GetHRForException(Exception e)1112         public static extern int GetHRForException(Exception e);
1113 
1114         //====================================================================
1115         // Converts the CLR exception to an HRESULT. This function also sets
1116         // up an IErrorInfo for the exception.
1117         // This function is only used in WinRT and converts ObjectDisposedException
1118         // to RO_E_CLOSED
1119         //====================================================================
1120         [System.Security.SecurityCritical]  // auto-generated_required
1121         [ResourceExposure(ResourceScope.None)]
1122         [MethodImplAttribute(MethodImplOptions.InternalCall)]
GetHRForException_WinRT(Exception e)1123         internal static extern int GetHRForException_WinRT(Exception e);
1124 
1125 #if !FEATURE_PAL
1126         //====================================================================
1127         // This method is intended for compiler code generators rather
1128         // than applications.
1129         //====================================================================
1130         //
1131         [System.Security.SecurityCritical]  // auto-generated_required
1132         [ObsoleteAttribute("The GetUnmanagedThunkForManagedMethodPtr method has been deprecated and will be removed in a future release.", false)]
1133         [ResourceExposure(ResourceScope.None)]
1134         [MethodImplAttribute(MethodImplOptions.InternalCall)]
GetUnmanagedThunkForManagedMethodPtr(IntPtr pfnMethodToWrap, IntPtr pbSignature, int cbSignature)1135         public static extern IntPtr GetUnmanagedThunkForManagedMethodPtr(IntPtr pfnMethodToWrap, IntPtr pbSignature, int cbSignature);
1136 
1137         //====================================================================
1138         // This method is intended for compiler code generators rather
1139         // than applications.
1140         //====================================================================
1141         //
1142         [System.Security.SecurityCritical]  // auto-generated_required
1143         [ObsoleteAttribute("The GetManagedThunkForUnmanagedMethodPtr method has been deprecated and will be removed in a future release.", false)]
1144         [ResourceExposure(ResourceScope.None)]
1145         [MethodImplAttribute(MethodImplOptions.InternalCall)]
GetManagedThunkForUnmanagedMethodPtr(IntPtr pfnMethodToWrap, IntPtr pbSignature, int cbSignature)1146         public static extern IntPtr GetManagedThunkForUnmanagedMethodPtr(IntPtr pfnMethodToWrap, IntPtr pbSignature, int cbSignature);
1147 
1148         //====================================================================
1149         // The hosting APIs allow a sophisticated host to schedule fibers
1150         // onto OS threads, so long as they notify the runtime of this
1151         // activity.  A fiber cookie can be redeemed for its managed Thread
1152         // object by calling the following service.
1153         //====================================================================
1154         //
1155         [System.Security.SecurityCritical]  // auto-generated_required
1156         [ObsoleteAttribute("The GetThreadFromFiberCookie method has been deprecated.  Use the hosting API to perform this operation.", false)]
GetThreadFromFiberCookie(int cookie)1157         public static Thread GetThreadFromFiberCookie(int cookie)
1158         {
1159             if (cookie == 0)
1160                 throw new ArgumentException(Environment.GetResourceString("Argument_ArgumentZero"), "cookie");
1161             Contract.EndContractBlock();
1162 
1163             return InternalGetThreadFromFiberCookie(cookie);
1164         }
1165 
1166         [ResourceExposure(ResourceScope.None)]
1167         [MethodImplAttribute(MethodImplOptions.InternalCall)]
InternalGetThreadFromFiberCookie(int cookie)1168         private static extern Thread InternalGetThreadFromFiberCookie(int cookie);
1169 #endif //!FEATURE_PAL
1170 
1171 
1172         //====================================================================
1173         // Memory allocation and deallocation.
1174         //====================================================================
1175         [System.Security.SecurityCritical]  // auto-generated_required
1176         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
AllocHGlobal(IntPtr cb)1177         public static IntPtr AllocHGlobal(IntPtr cb)
1178         {
1179             // For backwards compatibility on 32 bit platforms, ensure we pass values between
1180             // Int32.MaxValue and UInt32.MaxValue to Windows.  If the binary has had the
1181             // LARGEADDRESSAWARE bit set in the PE header, it may get 3 or 4 GB of user mode
1182             // address space.  It is remotely that those allocations could have succeeded,
1183             // though I couldn't reproduce that.  In either case, that means we should continue
1184             // throwing an OOM instead of an ArgumentOutOfRangeException for "negative" amounts of memory.
1185             UIntPtr numBytes;
1186 #if WIN32
1187             numBytes = new UIntPtr(unchecked((uint)cb.ToInt32()));
1188 #else
1189             numBytes = new UIntPtr(unchecked((ulong)cb.ToInt64()));
1190 #endif
1191 
1192             IntPtr pNewMem = Win32Native.LocalAlloc_NoSafeHandle(LMEM_FIXED, unchecked(numBytes));
1193 
1194             if (pNewMem == IntPtr.Zero) {
1195                 throw new OutOfMemoryException();
1196             }
1197             return pNewMem;
1198         }
1199 
1200         [System.Security.SecurityCritical]  // auto-generated_required
1201         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
AllocHGlobal(int cb)1202         public static IntPtr AllocHGlobal(int cb)
1203         {
1204             return AllocHGlobal((IntPtr)cb);
1205         }
1206 
1207         [System.Security.SecurityCritical]  // auto-generated_required
1208         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
FreeHGlobal(IntPtr hglobal)1209         public static void FreeHGlobal(IntPtr hglobal)
1210         {
1211             if (IsNotWin32Atom(hglobal)) {
1212                 if (IntPtr.Zero != Win32Native.LocalFree(hglobal)) {
1213                     ThrowExceptionForHR(GetHRForLastWin32Error());
1214                 }
1215             }
1216         }
1217 
1218 #if !FEATURE_PAL
1219         [System.Security.SecurityCritical]  // auto-generated_required
ReAllocHGlobal(IntPtr pv, IntPtr cb)1220         public static IntPtr ReAllocHGlobal(IntPtr pv, IntPtr cb)
1221         {
1222             IntPtr pNewMem = Win32Native.LocalReAlloc(pv, cb, LMEM_MOVEABLE);
1223             if (pNewMem == IntPtr.Zero) {
1224                 throw new OutOfMemoryException();
1225             }
1226             return pNewMem;
1227         }
1228 
1229 
1230         //====================================================================
1231         // String convertions.
1232         //====================================================================
1233         [System.Security.SecurityCritical]  // auto-generated_required
StringToHGlobalAnsi(String s)1234         unsafe public static IntPtr StringToHGlobalAnsi(String s)
1235         {
1236             if (s == null)
1237             {
1238                 return IntPtr.Zero;
1239             }
1240             else
1241             {
1242                 int nb = (s.Length + 1) * SystemMaxDBCSCharSize;
1243 
1244                 // Overflow checking
1245                 if (nb < s.Length)
1246                     throw new ArgumentOutOfRangeException("s");
1247 
1248                 UIntPtr len = new UIntPtr((uint)nb);
1249                 IntPtr hglobal = Win32Native.LocalAlloc_NoSafeHandle(LMEM_FIXED, len);
1250 
1251                 if (hglobal == IntPtr.Zero)
1252                 {
1253                     throw new OutOfMemoryException();
1254                 }
1255                 else
1256                 {
1257                     s.ConvertToAnsi((byte *)hglobal, nb, false, false);
1258                     return hglobal;
1259                 }
1260             }
1261         }
1262 #endif // !FEATURE_PAL
1263 
1264         [System.Security.SecurityCritical]  // auto-generated_required
StringToHGlobalUni(String s)1265         unsafe public static IntPtr StringToHGlobalUni(String s)
1266         {
1267             if (s == null)
1268             {
1269                 return IntPtr.Zero;
1270             }
1271             else
1272             {
1273                 int nb = (s.Length + 1) * 2;
1274 
1275                 // Overflow checking
1276                 if (nb < s.Length)
1277                     throw new ArgumentOutOfRangeException("s");
1278 
1279                 UIntPtr len = new UIntPtr((uint)nb);
1280                 IntPtr hglobal = Win32Native.LocalAlloc_NoSafeHandle(LMEM_FIXED, len);
1281 
1282                 if (hglobal == IntPtr.Zero)
1283                 {
1284                     throw new OutOfMemoryException();
1285                 }
1286                 else
1287                 {
1288                     fixed (char* firstChar = s)
1289                     {
1290                         String.wstrcpy((char*)hglobal, firstChar, s.Length + 1);
1291                     }
1292                     return hglobal;
1293                 }
1294             }
1295         }
1296 
1297 #if !FEATURE_PAL
1298         [System.Security.SecurityCritical]  // auto-generated_required
StringToHGlobalAuto(String s)1299         public static IntPtr StringToHGlobalAuto(String s)
1300         {
1301             // Ansi platforms are no longer supported
1302             return StringToHGlobalUni(s);
1303         }
1304 #endif //!FEATURE_PAL
1305 
1306 #if FEATURE_COMINTEROP
1307 
1308 		internal static readonly Guid ManagedNameGuid = new Guid("{0F21F359-AB84-41E8-9A78-36D110E6D2F9}");
1309 
1310         //====================================================================
1311         // Given a managed object that wraps a UCOMITypeLib, return its name
1312         //====================================================================
1313         [System.Security.SecurityCritical]  // auto-generated_required
1314         [Obsolete("Use System.Runtime.InteropServices.Marshal.GetTypeLibName(ITypeLib pTLB) instead. http://go.microsoft.com/fwlink/?linkid=14202&ID=0000011.", false)]
GetTypeLibName(UCOMITypeLib pTLB)1315         public static String GetTypeLibName(UCOMITypeLib pTLB)
1316         {
1317             return GetTypeLibName((ITypeLib)pTLB);
1318         }
1319 
1320 
1321         //====================================================================
1322         // Given a managed object that wraps an ITypeLib, return its name
1323         //====================================================================
1324         [System.Security.SecurityCritical]  // auto-generated_required
GetTypeLibName(ITypeLib typelib)1325         public static String GetTypeLibName(ITypeLib typelib)
1326         {
1327             if (typelib == null)
1328                 throw new ArgumentNullException("typelib");
1329             Contract.EndContractBlock();
1330 
1331             String strTypeLibName = null;
1332             String strDocString = null;
1333             int dwHelpContext = 0;
1334             String strHelpFile = null;
1335 
1336             typelib.GetDocumentation(-1, out strTypeLibName, out strDocString, out dwHelpContext, out strHelpFile);
1337 
1338             return strTypeLibName;
1339         }
1340 
1341         //====================================================================
1342         // Internal version of GetTypeLibName
1343         // Support GUID_ManagedName which aligns with TlbImp
1344         //====================================================================
1345         [System.Security.SecurityCritical]  // auto-generated_required
GetTypeLibNameInternal(ITypeLib typelib)1346         internal static String GetTypeLibNameInternal(ITypeLib typelib)
1347         {
1348             if (typelib == null)
1349                 throw new ArgumentNullException("typelib");
1350             Contract.EndContractBlock();
1351 
1352             // Try GUID_ManagedName first
1353             ITypeLib2 typeLib2 = typelib as ITypeLib2;
1354             if (typeLib2 != null)
1355             {
1356                 Guid guid = ManagedNameGuid;
1357                 object val;
1358 
1359                 try
1360                 {
1361                     typeLib2.GetCustData(ref guid, out val);
1362                 }
1363                 catch(Exception)
1364                 {
1365                     val = null;
1366                 }
1367 
1368                 if (val != null && val.GetType() == typeof(string))
1369                 {
1370                     string customManagedNamespace = (string)val;
1371                     customManagedNamespace = customManagedNamespace.Trim();
1372                     if (customManagedNamespace.EndsWith(".DLL", StringComparison.OrdinalIgnoreCase))
1373                         customManagedNamespace = customManagedNamespace.Substring(0, customManagedNamespace.Length - 4);
1374                     else if (customManagedNamespace.EndsWith(".EXE", StringComparison.OrdinalIgnoreCase))
1375                         customManagedNamespace = customManagedNamespace.Substring(0, customManagedNamespace.Length - 4);
1376                     return customManagedNamespace;
1377                 }
1378             }
1379 
1380             return GetTypeLibName(typelib);
1381         }
1382 
1383 
1384         //====================================================================
1385         // Given an managed object that wraps an UCOMITypeLib, return its guid
1386         //====================================================================
1387         [System.Security.SecurityCritical]  // auto-generated_required
1388         [Obsolete("Use System.Runtime.InteropServices.Marshal.GetTypeLibGuid(ITypeLib pTLB) instead. http://go.microsoft.com/fwlink/?linkid=14202&ID=0000011.", false)]
GetTypeLibGuid(UCOMITypeLib pTLB)1389         public static Guid GetTypeLibGuid(UCOMITypeLib pTLB)
1390         {
1391             return GetTypeLibGuid((ITypeLib)pTLB);
1392         }
1393 
1394         //====================================================================
1395         // Given an managed object that wraps an ITypeLib, return its guid
1396         //====================================================================
1397         [System.Security.SecurityCritical]  // auto-generated_required
GetTypeLibGuid(ITypeLib typelib)1398         public static Guid GetTypeLibGuid(ITypeLib typelib)
1399         {
1400             Guid result = new Guid ();
1401             FCallGetTypeLibGuid (ref result, typelib);
1402             return result;
1403         }
1404 
1405         [ResourceExposure(ResourceScope.None)]
1406         [MethodImplAttribute(MethodImplOptions.InternalCall)]
FCallGetTypeLibGuid(ref Guid result, ITypeLib pTLB)1407         private static extern void FCallGetTypeLibGuid(ref Guid result, ITypeLib pTLB);
1408 
1409         //====================================================================
1410         // Given a managed object that wraps a UCOMITypeLib, return its lcid
1411         //====================================================================
1412         [System.Security.SecurityCritical]  // auto-generated_required
1413         [Obsolete("Use System.Runtime.InteropServices.Marshal.GetTypeLibLcid(ITypeLib pTLB) instead. http://go.microsoft.com/fwlink/?linkid=14202&ID=0000011.", false)]
GetTypeLibLcid(UCOMITypeLib pTLB)1414         public static int GetTypeLibLcid(UCOMITypeLib pTLB)
1415         {
1416             return GetTypeLibLcid((ITypeLib)pTLB);
1417         }
1418 
1419         //====================================================================
1420         // Given a managed object that wraps an ITypeLib, return its lcid
1421         //====================================================================
1422         [System.Security.SecurityCritical]  // auto-generated_required
1423         [ResourceExposure(ResourceScope.None)]
1424         [MethodImplAttribute(MethodImplOptions.InternalCall)]
GetTypeLibLcid(ITypeLib typelib)1425         public static extern int GetTypeLibLcid(ITypeLib typelib);
1426 
1427         //====================================================================
1428         // Given a managed object that wraps an ITypeLib, return it's
1429         // version information.
1430         //====================================================================
1431         [ResourceExposure(ResourceScope.None)]
1432         [MethodImplAttribute(MethodImplOptions.InternalCall)]
GetTypeLibVersion(ITypeLib typeLibrary, out int major, out int minor)1433         internal static extern void GetTypeLibVersion(ITypeLib typeLibrary, out int major, out int minor);
1434 
1435         //====================================================================
1436         // Given a managed object that wraps an ITypeInfo, return its guid.
1437         //====================================================================
1438         [System.Security.SecurityCritical]  // auto-generated
GetTypeInfoGuid(ITypeInfo typeInfo)1439         internal static Guid GetTypeInfoGuid(ITypeInfo typeInfo)
1440         {
1441             Guid result = new Guid ();
1442             FCallGetTypeInfoGuid (ref result, typeInfo);
1443             return result;
1444         }
1445 
1446         [ResourceExposure(ResourceScope.None)]
1447         [MethodImplAttribute(MethodImplOptions.InternalCall)]
FCallGetTypeInfoGuid(ref Guid result, ITypeInfo typeInfo)1448         private static extern void FCallGetTypeInfoGuid(ref Guid result, ITypeInfo typeInfo);
1449 
1450         //====================================================================
1451         // Given a assembly, return the TLBID that will be generated for the
1452         // typelib exported from the assembly.
1453         //====================================================================
1454         [System.Security.SecurityCritical]  // auto-generated_required
GetTypeLibGuidForAssembly(Assembly asm)1455         public static Guid GetTypeLibGuidForAssembly(Assembly asm)
1456         {
1457             if (asm == null)
1458                 throw new ArgumentNullException("asm");
1459             Contract.EndContractBlock();
1460 
1461             RuntimeAssembly rtAssembly = asm as RuntimeAssembly;
1462             if (rtAssembly == null)
1463                 throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeAssembly"), "asm");
1464 
1465             Guid result = new Guid();
1466             FCallGetTypeLibGuidForAssembly(ref result, rtAssembly);
1467             return result;
1468         }
1469 
1470         [ResourceExposure(ResourceScope.None)]  // Scoped to assembly
1471         [MethodImplAttribute(MethodImplOptions.InternalCall)]
FCallGetTypeLibGuidForAssembly(ref Guid result, RuntimeAssembly asm)1472         private static extern void FCallGetTypeLibGuidForAssembly(ref Guid result, RuntimeAssembly asm);
1473 
1474         //====================================================================
1475         // Given a assembly, return the version number of the type library
1476         // that would be exported from the assembly.
1477         //====================================================================
1478         [ResourceExposure(ResourceScope.None)]
1479         [MethodImplAttribute(MethodImplOptions.InternalCall)]
_GetTypeLibVersionForAssembly(RuntimeAssembly inputAssembly, out int majorVersion, out int minorVersion)1480         private static extern void _GetTypeLibVersionForAssembly(RuntimeAssembly inputAssembly, out int majorVersion, out int minorVersion);
1481 
1482         [System.Security.SecurityCritical]  // auto-generated_required
1483         [ResourceExposure(ResourceScope.None)]
GetTypeLibVersionForAssembly(Assembly inputAssembly, out int majorVersion, out int minorVersion)1484         public static void GetTypeLibVersionForAssembly(Assembly inputAssembly, out int majorVersion, out int minorVersion)
1485         {
1486             if (inputAssembly == null)
1487                 throw new ArgumentNullException("inputAssembly");
1488             Contract.EndContractBlock();
1489 
1490             RuntimeAssembly rtAssembly = inputAssembly as RuntimeAssembly;
1491             if (rtAssembly == null)
1492                 throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeAssembly"), "inputAssembly");
1493 
1494             _GetTypeLibVersionForAssembly(rtAssembly, out majorVersion, out minorVersion);
1495         }
1496 
1497         //====================================================================
1498         // Given a managed object that wraps an UCOMITypeInfo, return its name
1499         //====================================================================
1500         [System.Security.SecurityCritical]  // auto-generated_required
1501         [Obsolete("Use System.Runtime.InteropServices.Marshal.GetTypeInfoName(ITypeInfo pTLB) instead. http://go.microsoft.com/fwlink/?linkid=14202&ID=0000011.", false)]
GetTypeInfoName(UCOMITypeInfo pTI)1502         public static String GetTypeInfoName(UCOMITypeInfo pTI)
1503         {
1504             return GetTypeInfoName((ITypeInfo)pTI);
1505         }
1506 
1507         //====================================================================
1508         // Given a managed object that wraps an ITypeInfo, return its name
1509         //====================================================================
1510         [System.Security.SecurityCritical]  // auto-generated_required
GetTypeInfoName(ITypeInfo typeInfo)1511         public static String GetTypeInfoName(ITypeInfo typeInfo)
1512         {
1513             if (typeInfo == null)
1514                 throw new ArgumentNullException("typeInfo");
1515             Contract.EndContractBlock();
1516 
1517             String strTypeLibName = null;
1518             String strDocString = null;
1519             int dwHelpContext = 0;
1520             String strHelpFile = null;
1521 
1522             typeInfo.GetDocumentation(-1, out strTypeLibName, out strDocString, out dwHelpContext, out strHelpFile);
1523 
1524             return strTypeLibName;
1525         }
1526 
1527         //====================================================================
1528         // Internal version of GetTypeInfoName
1529         // Support GUID_ManagedName which aligns with TlbImp
1530         //====================================================================
1531         [System.Security.SecurityCritical]  // auto-generated_required
GetTypeInfoNameInternal(ITypeInfo typeInfo, out bool hasManagedName)1532         internal static String GetTypeInfoNameInternal(ITypeInfo typeInfo, out bool hasManagedName)
1533         {
1534             if (typeInfo == null)
1535                 throw new ArgumentNullException("typeInfo");
1536             Contract.EndContractBlock();
1537 
1538             // Try ManagedNameGuid first
1539             ITypeInfo2 typeInfo2 = typeInfo as ITypeInfo2;
1540             if (typeInfo2 != null)
1541             {
1542                 Guid guid = ManagedNameGuid;
1543                 object val;
1544 
1545                 try
1546                 {
1547                     typeInfo2.GetCustData(ref guid, out val);
1548                 }
1549                 catch(Exception)
1550                 {
1551                     val = null;
1552                 }
1553 
1554                 if (val != null && val.GetType() == typeof(string))
1555                 {
1556                     hasManagedName = true;
1557                     return (string)val;
1558                 }
1559             }
1560 
1561             hasManagedName = false;
1562             return GetTypeInfoName(typeInfo);
1563         }
1564 
1565         //====================================================================
1566         // Get the corresponding managed name as converted by TlbImp
1567         // Used to get the type using GetType() from imported assemblies
1568         //====================================================================
1569         [System.Security.SecurityCritical]  // auto-generated_required
GetManagedTypeInfoNameInternal(ITypeLib typeLib, ITypeInfo typeInfo)1570         internal static String GetManagedTypeInfoNameInternal(ITypeLib typeLib, ITypeInfo typeInfo)
1571         {
1572             bool hasManagedName;
1573             string name = GetTypeInfoNameInternal(typeInfo, out hasManagedName);
1574             if (hasManagedName)
1575                 return name;
1576             else
1577                 return GetTypeLibNameInternal(typeLib) + "." + name;
1578         }
1579 
1580         //====================================================================
1581         // If a type with the specified GUID is loaded, this method will
1582         // return the reflection type that represents it. Otherwise it returns
1583         // NULL.
1584         //====================================================================
1585         [ResourceExposure(ResourceScope.None)]
1586         [MethodImplAttribute(MethodImplOptions.InternalCall)]
GetLoadedTypeForGUID(ref Guid guid)1587         private static extern Type GetLoadedTypeForGUID(ref Guid guid);
1588 
1589 #if !FEATURE_CORECLR // current implementation requires reflection only load
1590         //====================================================================
1591         // map ITypeInfo* to Type
1592         //====================================================================
1593         [System.Security.SecurityCritical]  // auto-generated_required
GetTypeForITypeInfo(IntPtr piTypeInfo)1594         public static Type GetTypeForITypeInfo(IntPtr /* ITypeInfo* */ piTypeInfo)
1595         {
1596             ITypeInfo pTI = null;
1597             ITypeLib pTLB = null;
1598             Type TypeObj = null;
1599             Assembly AsmBldr = null;
1600             TypeLibConverter TlbConverter = null;
1601             int Index = 0;
1602             Guid clsid;
1603 
1604             // If the input ITypeInfo is NULL then return NULL.
1605             if (piTypeInfo == IntPtr.Zero)
1606                 return null;
1607 
1608             // Wrap the ITypeInfo in a CLR object.
1609             pTI = (ITypeInfo)GetObjectForIUnknown(piTypeInfo);
1610 
1611             // Check to see if a class exists with the specified GUID.
1612 
1613             clsid = GetTypeInfoGuid(pTI);
1614             TypeObj = GetLoadedTypeForGUID(ref clsid);
1615 
1616             // If we managed to find the type based on the GUID then return it.
1617             if (TypeObj != null)
1618                 return TypeObj;
1619 
1620             // There is no type with the specified GUID in the app domain so lets
1621             // try and convert the containing typelib.
1622             try
1623             {
1624                 pTI.GetContainingTypeLib(out pTLB, out Index);
1625             }
1626             catch(COMException)
1627             {
1628                 pTLB = null;
1629             }
1630 
1631             // Check to see if we managed to get a containing typelib.
1632             if (pTLB != null)
1633             {
1634                 // Get the assembly name from the typelib.
1635                 AssemblyName AsmName = TypeLibConverter.GetAssemblyNameFromTypelib(pTLB, null, null, null, null, AssemblyNameFlags.None);
1636                 String AsmNameString = AsmName.FullName;
1637 
1638                 // Check to see if the assembly that will contain the type already exists.
1639                 Assembly[] aAssemblies = Thread.GetDomain().GetAssemblies();
1640                 int NumAssemblies = aAssemblies.Length;
1641                 for (int i = 0; i < NumAssemblies; i++)
1642                 {
1643                     if (String.Compare(aAssemblies[i].FullName,
1644                                        AsmNameString,StringComparison.Ordinal) == 0)
1645                         AsmBldr = aAssemblies[i];
1646                 }
1647 
1648                 // If we haven't imported the assembly yet then import it.
1649                 if (AsmBldr == null)
1650                 {
1651                     TlbConverter = new TypeLibConverter();
1652                     AsmBldr = TlbConverter.ConvertTypeLibToAssembly(pTLB,
1653                         GetTypeLibName(pTLB) + ".dll", 0, new ImporterCallback(), null, null, null, null);
1654                 }
1655 
1656                 // Load the type object from the imported typelib.
1657                 // Call GetManagedTypeInfoNameInternal to align with TlbImp behavior
1658                 TypeObj = AsmBldr.GetType(GetManagedTypeInfoNameInternal(pTLB, pTI), true, false);
1659                 if (TypeObj != null && !TypeObj.IsVisible)
1660                     TypeObj = null;
1661             }
1662             else
1663             {
1664                 // If the ITypeInfo does not have a containing typelib then simply
1665                 // return Object as the type.
1666                 TypeObj = typeof(Object);
1667             }
1668 
1669             return TypeObj;
1670         }
1671 #endif // #if !FEATURE_CORECLR
1672 
1673         // This method is identical to Type.GetTypeFromCLSID. Since it's interop specific, we expose it
1674         // on Marshal for more consistent API surface.
1675 #if !FEATURE_CORECLR
1676         [System.Security.SecuritySafeCritical]
1677 #endif //!FEATURE_CORECLR
GetTypeFromCLSID(Guid clsid)1678         public static Type GetTypeFromCLSID(Guid clsid)
1679         {
1680             return RuntimeType.GetTypeFromCLSIDImpl(clsid, null, false);
1681         }
1682 
1683         //====================================================================
1684         // map Type to ITypeInfo*
1685         //====================================================================
1686         [System.Security.SecurityCritical]  // auto-generated_required
1687         [ResourceExposure(ResourceScope.None)]
1688         [MethodImplAttribute(MethodImplOptions.InternalCall)]
GetITypeInfoForType(Type t)1689         public static extern IntPtr /* ITypeInfo* */ GetITypeInfoForType(Type t);
1690 
1691         //====================================================================
1692         // return the IUnknown* for an Object if the current context
1693         // is the one where the RCW was first seen. Will return null
1694         // otherwise.
1695         //====================================================================
1696         [System.Security.SecurityCritical]  // auto-generated_required
GetIUnknownForObject(Object o)1697         public static IntPtr /* IUnknown* */ GetIUnknownForObject(Object o)
1698         {
1699             return GetIUnknownForObjectNative(o, false);
1700         }
1701 
1702         [System.Security.SecurityCritical]  // auto-generated_required
GetIUnknownForObjectInContext(Object o)1703         public static IntPtr /* IUnknown* */ GetIUnknownForObjectInContext(Object o)
1704         {
1705             return GetIUnknownForObjectNative(o, true);
1706         }
1707 
1708         [ResourceExposure(ResourceScope.None)]
1709         [MethodImplAttribute(MethodImplOptions.InternalCall)]
GetIUnknownForObjectNative(Object o, bool onlyInContext)1710         private static extern IntPtr /* IUnknown* */ GetIUnknownForObjectNative(Object o, bool onlyInContext);
1711 
1712         //====================================================================
1713         // return the raw IUnknown* for a COM Object not related to current
1714         // context
1715         // Does not call AddRef
1716         //====================================================================
1717         [ResourceExposure(ResourceScope.None)]
1718         [MethodImplAttribute(MethodImplOptions.InternalCall)]
GetRawIUnknownForComObjectNoAddRef(Object o)1719         internal static extern IntPtr /* IUnknown* */ GetRawIUnknownForComObjectNoAddRef(Object o);
1720 
1721         //====================================================================
1722         // return the IDispatch* for an Object
1723         //====================================================================
1724         [System.Security.SecurityCritical]  // auto-generated_required
GetIDispatchForObject(Object o)1725         public static IntPtr /* IDispatch */ GetIDispatchForObject(Object o)
1726         {
1727             return GetIDispatchForObjectNative(o, false);
1728         }
1729 
1730         //====================================================================
1731         // return the IDispatch* for an Object if the current context
1732         // is the one where the RCW was first seen. Will return null
1733         // otherwise.
1734         //====================================================================
1735         [System.Security.SecurityCritical]  // auto-generated_required
GetIDispatchForObjectInContext(Object o)1736         public static IntPtr /* IUnknown* */ GetIDispatchForObjectInContext(Object o)
1737         {
1738             return GetIDispatchForObjectNative(o, true);
1739         }
1740 
1741         [ResourceExposure(ResourceScope.None)]
1742         [MethodImplAttribute(MethodImplOptions.InternalCall)]
GetIDispatchForObjectNative(Object o, bool onlyInContext)1743         private static extern IntPtr /* IUnknown* */ GetIDispatchForObjectNative(Object o, bool onlyInContext);
1744 
1745         //====================================================================
1746         // return the IUnknown* representing the interface for the Object
1747         // Object o should support Type T
1748         //====================================================================
1749         [System.Security.SecurityCritical]  // auto-generated_required
GetComInterfaceForObject(Object o, Type T)1750         public static IntPtr /* IUnknown* */ GetComInterfaceForObject(Object o, Type T)
1751         {
1752             return GetComInterfaceForObjectNative(o, T, false, true);
1753         }
1754 
1755         [System.Security.SecurityCritical]
GetComInterfaceForObject(T o)1756         public static IntPtr GetComInterfaceForObject<T, TInterface>(T o)
1757         {
1758             return GetComInterfaceForObject(o, typeof(TInterface));
1759         }
1760 
1761         //====================================================================
1762         // return the IUnknown* representing the interface for the Object
1763         // Object o should support Type T, it refer the value of mode to
1764         // invoke customized QueryInterface or not
1765         //====================================================================
1766         [System.Security.SecurityCritical]  // auto-generated_required
GetComInterfaceForObject(Object o, Type T, CustomQueryInterfaceMode mode)1767         public static IntPtr /* IUnknown* */ GetComInterfaceForObject(Object o, Type T, CustomQueryInterfaceMode mode)
1768         {
1769             bool bEnableCustomizedQueryInterface = ((mode == CustomQueryInterfaceMode.Allow) ? true : false);
1770             return GetComInterfaceForObjectNative(o, T, false, bEnableCustomizedQueryInterface);
1771         }
1772 
1773         //====================================================================
1774         // return the IUnknown* representing the interface for the Object
1775         // Object o should support Type T if the current context
1776         // is the one where the RCW was first seen. Will return null
1777         // otherwise.
1778         //====================================================================
1779         [System.Security.SecurityCritical]  // auto-generated_required
GetComInterfaceForObjectInContext(Object o, Type t)1780         public static IntPtr /* IUnknown* */ GetComInterfaceForObjectInContext(Object o, Type t)
1781         {
1782             return GetComInterfaceForObjectNative(o, t, true, true);
1783         }
1784 
1785         [ResourceExposure(ResourceScope.None)]
1786         [MethodImplAttribute(MethodImplOptions.InternalCall)]
GetComInterfaceForObjectNative(Object o, Type t, bool onlyInContext, bool fEnalbeCustomizedQueryInterface)1787         private static extern IntPtr /* IUnknown* */ GetComInterfaceForObjectNative(Object o, Type t, bool onlyInContext, bool fEnalbeCustomizedQueryInterface);
1788 
1789         //====================================================================
1790         // return an Object for IUnknown
1791         //====================================================================
1792         [System.Security.SecurityCritical]  // auto-generated_required
1793         [ResourceExposure(ResourceScope.None)]
1794         [MethodImplAttribute(MethodImplOptions.InternalCall)]
GetObjectForIUnknown(IntPtr pUnk)1795         public static extern Object GetObjectForIUnknown(IntPtr /* IUnknown* */ pUnk);
1796 
1797         //====================================================================
1798         // Return a unique Object given an IUnknown.  This ensures that you
1799         //  receive a fresh object (we will not look in the cache to match up this
1800         //  IUnknown to an already existing object).  This is useful in cases
1801         //  where you want to be able to call ReleaseComObject on a RCW
1802         //  and not worry about other active uses of said RCW.
1803         //====================================================================
1804         [System.Security.SecurityCritical]  // auto-generated_required
1805         [ResourceExposure(ResourceScope.None)]
1806         [MethodImplAttribute(MethodImplOptions.InternalCall)]
GetUniqueObjectForIUnknown(IntPtr unknown)1807         public static extern Object GetUniqueObjectForIUnknown(IntPtr unknown);
1808 
1809         //====================================================================
1810         // return an Object for IUnknown, using the Type T,
1811         //  NOTE:
1812         //  Type T should be either a COM imported Type or a sub-type of COM
1813         //  imported Type
1814         //====================================================================
1815         [System.Security.SecurityCritical]  // auto-generated_required
1816         [ResourceExposure(ResourceScope.None)]
1817         [MethodImplAttribute(MethodImplOptions.InternalCall)]
GetTypedObjectForIUnknown(IntPtr pUnk, Type t)1818         public static extern Object GetTypedObjectForIUnknown(IntPtr /* IUnknown* */ pUnk, Type t);
1819 
1820         [System.Security.SecurityCritical]  // auto-generated_required
1821         [ResourceExposure(ResourceScope.None)]
1822         [MethodImplAttribute(MethodImplOptions.InternalCall)]
CreateAggregatedObject(IntPtr pOuter, Object o)1823         public static extern IntPtr CreateAggregatedObject(IntPtr pOuter, Object o);
1824 
1825         [System.Security.SecurityCritical]
CreateAggregatedObject(IntPtr pOuter, T o)1826         public static IntPtr CreateAggregatedObject<T>(IntPtr pOuter, T o)
1827         {
1828             return CreateAggregatedObject(pOuter, (object)o);
1829         }
1830 
1831         [System.Security.SecurityCritical]  // auto-generated_required
1832         [ResourceExposure(ResourceScope.None)]
1833         [MethodImplAttribute(MethodImplOptions.InternalCall)]
CleanupUnusedObjectsInCurrentContext()1834         public static extern void CleanupUnusedObjectsInCurrentContext();
1835 
1836         [System.Security.SecurityCritical]
1837         [ResourceExposure(ResourceScope.None)]
1838         [MethodImplAttribute(MethodImplOptions.InternalCall)]
AreComObjectsAvailableForCleanup()1839         public static extern bool AreComObjectsAvailableForCleanup();
1840 
1841         //====================================================================
1842         // check if the object is classic COM component
1843         //====================================================================
1844 #if !FEATURE_CORECLR // with FEATURE_CORECLR, the whole type is SecurityCritical
1845         [System.Security.SecuritySafeCritical]
1846 #endif
1847         [ResourceExposure(ResourceScope.None)]
1848         [MethodImplAttribute(MethodImplOptions.InternalCall)]
IsComObject(Object o)1849         public static extern bool IsComObject(Object o);
1850 
1851 #endif // FEATURE_COMINTEROP
1852 
1853         [System.Security.SecurityCritical]  // auto-generated_required
AllocCoTaskMem(int cb)1854         public static IntPtr AllocCoTaskMem(int cb)
1855         {
1856             IntPtr pNewMem = Win32Native.CoTaskMemAlloc(new UIntPtr((uint)cb));
1857             if (pNewMem == IntPtr.Zero)
1858             {
1859                 throw new OutOfMemoryException();
1860             }
1861             return pNewMem;
1862         }
1863 
1864         [System.Security.SecurityCritical]  // auto-generated_required
StringToCoTaskMemUni(String s)1865         unsafe public static IntPtr StringToCoTaskMemUni(String s)
1866         {
1867             if (s == null)
1868             {
1869                 return IntPtr.Zero;
1870             }
1871             else
1872             {
1873                 int nb = (s.Length + 1) * 2;
1874 
1875                 // Overflow checking
1876                 if (nb < s.Length)
1877                     throw new ArgumentOutOfRangeException("s");
1878 
1879                 IntPtr hglobal = Win32Native.CoTaskMemAlloc(new UIntPtr((uint)nb));
1880 
1881                 if (hglobal == IntPtr.Zero)
1882                 {
1883                     throw new OutOfMemoryException();
1884                 }
1885                 else
1886                 {
1887                     fixed (char* firstChar = s)
1888                     {
1889                         String.wstrcpy((char *)hglobal, firstChar, s.Length + 1);
1890                     }
1891                     return hglobal;
1892                 }
1893             }
1894         }
1895 
1896         [System.Security.SecurityCritical]  // auto-generated_required
StringToCoTaskMemAuto(String s)1897         public static IntPtr StringToCoTaskMemAuto(String s)
1898         {
1899             // Ansi platforms are no longer supported
1900             return StringToCoTaskMemUni(s);
1901         }
1902 
1903         [System.Security.SecurityCritical]  // auto-generated_required
StringToCoTaskMemAnsi(String s)1904         unsafe public static IntPtr StringToCoTaskMemAnsi(String s)
1905         {
1906             if (s == null)
1907             {
1908                 return IntPtr.Zero;
1909             }
1910             else
1911             {
1912                 int nb = (s.Length + 1) * SystemMaxDBCSCharSize;
1913 
1914                 // Overflow checking
1915                 if (nb < s.Length)
1916                     throw new ArgumentOutOfRangeException("s");
1917 
1918                 IntPtr hglobal = Win32Native.CoTaskMemAlloc(new UIntPtr((uint)nb));
1919 
1920                 if (hglobal == IntPtr.Zero)
1921                 {
1922                     throw new OutOfMemoryException();
1923                 }
1924                 else
1925                 {
1926                     s.ConvertToAnsi((byte *)hglobal, nb, false, false);
1927                     return hglobal;
1928                 }
1929             }
1930         }
1931 
1932         [System.Security.SecurityCritical]  // auto-generated_required
FreeCoTaskMem(IntPtr ptr)1933         public static void FreeCoTaskMem(IntPtr ptr)
1934         {
1935             if (IsNotWin32Atom(ptr)) {
1936                 Win32Native.CoTaskMemFree(ptr);
1937             }
1938         }
1939 
1940         [System.Security.SecurityCritical]  // auto-generated_required
ReAllocCoTaskMem(IntPtr pv, int cb)1941         public static IntPtr ReAllocCoTaskMem(IntPtr pv, int cb)
1942         {
1943             IntPtr pNewMem = Win32Native.CoTaskMemRealloc(pv, new UIntPtr((uint)cb));
1944             if (pNewMem == IntPtr.Zero && cb != 0)
1945             {
1946                 throw new OutOfMemoryException();
1947             }
1948             return pNewMem;
1949         }
1950 
1951 
1952 #if FEATURE_COMINTEROP
1953         //====================================================================
1954         // release the COM component and if the reference hits 0 zombie this object
1955         // further usage of this Object might throw an exception
1956         //====================================================================
1957         [System.Security.SecurityCritical]  // auto-generated_required
ReleaseComObject(Object o)1958         public static int ReleaseComObject(Object o)
1959         {
1960             __ComObject co = null;
1961 
1962             // Make sure the obj is an __ComObject.
1963             try
1964             {
1965                 co = (__ComObject)o;
1966             }
1967             catch (InvalidCastException)
1968             {
1969                 throw new ArgumentException(Environment.GetResourceString("Argument_ObjNotComObject"), "o");
1970             }
1971 
1972             return co.ReleaseSelf();
1973         }
1974 
1975         [ResourceExposure(ResourceScope.None)]
1976         [MethodImplAttribute(MethodImplOptions.InternalCall)]
InternalReleaseComObject(Object o)1977         internal static extern int InternalReleaseComObject(Object o);
1978 
1979 
1980         //====================================================================
1981         // release the COM component and zombie this object
1982         // further usage of this Object might throw an exception
1983         //====================================================================
1984         [System.Security.SecurityCritical]  // auto-generated_required
FinalReleaseComObject(Object o)1985         public static Int32 FinalReleaseComObject(Object o)
1986         {
1987             if (o == null)
1988                 throw new ArgumentNullException("o");
1989             Contract.EndContractBlock();
1990 
1991             __ComObject co = null;
1992 
1993             // Make sure the obj is an __ComObject.
1994             try
1995             {
1996                 co = (__ComObject)o;
1997             }
1998             catch (InvalidCastException)
1999             {
2000                 throw new ArgumentException(Environment.GetResourceString("Argument_ObjNotComObject"), "o");
2001             }
2002 
2003             co.FinalReleaseSelf();
2004 
2005             return 0;
2006         }
2007 
2008         [ResourceExposure(ResourceScope.None)]
2009         [MethodImplAttribute(MethodImplOptions.InternalCall)]
InternalFinalReleaseComObject(Object o)2010         internal static extern void InternalFinalReleaseComObject(Object o);
2011 
2012         //====================================================================
2013         // This method retrieves data from the COM object.
2014         //====================================================================
2015         [System.Security.SecurityCritical]  // auto-generated_required
GetComObjectData(Object obj, Object key)2016         public static Object GetComObjectData(Object obj, Object key)
2017         {
2018             // Validate that the arguments aren't null.
2019             if (obj == null)
2020                 throw new ArgumentNullException("obj");
2021             if (key == null)
2022                 throw new ArgumentNullException("key");
2023             Contract.EndContractBlock();
2024 
2025             __ComObject comObj = null;
2026 
2027             // Make sure the obj is an __ComObject.
2028             try
2029             {
2030                 comObj = (__ComObject)obj;
2031             }
2032             catch (InvalidCastException)
2033             {
2034                 throw new ArgumentException(Environment.GetResourceString("Argument_ObjNotComObject"), "obj");
2035             }
2036 
2037             if (obj.GetType().IsWindowsRuntimeObject)
2038             {
2039                 throw new ArgumentException(Environment.GetResourceString("Argument_ObjIsWinRTObject"), "obj");
2040             }
2041 
2042             // Retrieve the data from the __ComObject.
2043             return comObj.GetData(key);
2044         }
2045 
2046         //====================================================================
2047         // This method sets data on the COM object. The data can only be set
2048         // once for a given key and cannot be removed. This function returns
2049         // true if the data has been added, false if the data could not be
2050         // added because there already was data for the specified key.
2051         //====================================================================
2052         [System.Security.SecurityCritical]  // auto-generated_required
SetComObjectData(Object obj, Object key, Object data)2053         public static bool SetComObjectData(Object obj, Object key, Object data)
2054         {
2055             // Validate that the arguments aren't null. The data can validly be null.
2056             if (obj == null)
2057                 throw new ArgumentNullException("obj");
2058             if (key == null)
2059                 throw new ArgumentNullException("key");
2060             Contract.EndContractBlock();
2061 
2062             __ComObject comObj = null;
2063 
2064             // Make sure the obj is an __ComObject.
2065             try
2066             {
2067                 comObj = (__ComObject)obj;
2068             }
2069             catch (InvalidCastException)
2070             {
2071                 throw new ArgumentException(Environment.GetResourceString("Argument_ObjNotComObject"), "obj");
2072             }
2073 
2074             if (obj.GetType().IsWindowsRuntimeObject)
2075             {
2076                 throw new ArgumentException(Environment.GetResourceString("Argument_ObjIsWinRTObject"), "obj");
2077             }
2078 
2079             // Retrieve the data from the __ComObject.
2080             return comObj.SetData(key, data);
2081         }
2082 
2083         //====================================================================
2084         // This method takes the given COM object and wraps it in an object
2085         // of the specified type. The type must be derived from __ComObject.
2086         //====================================================================
2087         [System.Security.SecurityCritical]  // auto-generated_required
CreateWrapperOfType(Object o, Type t)2088         public static Object CreateWrapperOfType(Object o, Type t)
2089         {
2090             // Validate the arguments.
2091             if (t == null)
2092                 throw new ArgumentNullException("t");
2093             if (!t.IsCOMObject)
2094                 throw new ArgumentException(Environment.GetResourceString("Argument_TypeNotComObject"), "t");
2095             if (t.IsGenericType)
2096                 throw new ArgumentException(Environment.GetResourceString("Argument_NeedNonGenericType"), "t");
2097             Contract.EndContractBlock();
2098 
2099             if (t.IsWindowsRuntimeObject)
2100                 throw new ArgumentException(Environment.GetResourceString("Argument_TypeIsWinRTType"), "t");
2101 
2102             // Check for the null case.
2103             if (o == null)
2104                 return null;
2105 
2106             // Make sure the object is a COM object.
2107             if (!o.GetType().IsCOMObject)
2108                 throw new ArgumentException(Environment.GetResourceString("Argument_ObjNotComObject"), "o");
2109             if (o.GetType().IsWindowsRuntimeObject)
2110                 throw new ArgumentException(Environment.GetResourceString("Argument_ObjIsWinRTObject"), "o");
2111 
2112             // Check to see if the type of the object is the requested type.
2113             if (o.GetType() == t)
2114                 return o;
2115 
2116             // Check to see if we already have a cached wrapper for this type.
2117             Object Wrapper = GetComObjectData(o, t);
2118             if (Wrapper == null)
2119             {
2120                 // Create the wrapper for the specified type.
2121                 Wrapper = InternalCreateWrapperOfType(o, t);
2122 
2123                 // Attempt to cache the wrapper on the object.
2124                 if (!SetComObjectData(o, t, Wrapper))
2125                 {
2126                     // Another thead already cached the wrapper so use that one instead.
2127                     Wrapper = GetComObjectData(o, t);
2128                 }
2129             }
2130 
2131             return Wrapper;
2132         }
2133 
2134         [System.Security.SecurityCritical]
CreateWrapperOfType(T o)2135         public static TWrapper CreateWrapperOfType<T, TWrapper>(T o)
2136         {
2137             return (TWrapper)CreateWrapperOfType(o, typeof(TWrapper));
2138         }
2139 
2140         //====================================================================
2141         // Helper method called from CreateWrapperOfType.
2142         //====================================================================
2143         [System.Security.SecurityCritical]  // auto-generated_required
2144         [ResourceExposure(ResourceScope.None)]
2145         [MethodImplAttribute(MethodImplOptions.InternalCall)]
InternalCreateWrapperOfType(Object o, Type t)2146         private static extern Object InternalCreateWrapperOfType(Object o, Type t);
2147 
2148         //====================================================================
2149         // There may be a thread-based cache of COM components.  This service can
2150         // force the aggressive release of the current thread's cache.
2151         //====================================================================
2152         //
2153         [System.Security.SecurityCritical]  // auto-generated_required
2154         [Obsolete("This API did not perform any operation and will be removed in future versions of the CLR.", false)]
ReleaseThreadCache()2155         public static void ReleaseThreadCache()
2156         {
2157         }
2158 
2159         //====================================================================
2160         // check if the type is visible from COM.
2161         //====================================================================
2162         [System.Security.SecuritySafeCritical]
2163         [ResourceExposure(ResourceScope.None)]
2164         [MethodImplAttribute(MethodImplOptions.InternalCall)]
IsTypeVisibleFromCom(Type t)2165         public static extern bool IsTypeVisibleFromCom(Type t);
2166 
2167         //====================================================================
2168         // IUnknown Helpers
2169         //====================================================================
2170         [System.Security.SecurityCritical]  // auto-generated_required
2171         [ResourceExposure(ResourceScope.None)]
2172         [MethodImplAttribute(MethodImplOptions.InternalCall)]
QueryInterface(IntPtr pUnk, ref Guid iid, out IntPtr ppv)2173         public static extern int /* HRESULT */ QueryInterface(IntPtr /* IUnknown */ pUnk, ref Guid iid, out IntPtr ppv);
2174 
2175         [System.Security.SecurityCritical]  // auto-generated_required
2176         [ResourceExposure(ResourceScope.None)]
2177         [MethodImplAttribute(MethodImplOptions.InternalCall)]
AddRef(IntPtr pUnk )2178         public static extern int /* ULONG */ AddRef(IntPtr /* IUnknown */ pUnk );
2179         [System.Security.SecurityCritical]  // auto-generated_required
2180         [ResourceExposure(ResourceScope.None)]
2181         [MethodImplAttribute(MethodImplOptions.InternalCall)]
2182         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
Release(IntPtr pUnk )2183         public static extern int /* ULONG */ Release(IntPtr /* IUnknown */ pUnk );
2184 
2185         //====================================================================
2186         // BSTR allocation and dealocation.
2187         //====================================================================
2188         [System.Security.SecurityCritical]  // auto-generated_required
FreeBSTR(IntPtr ptr)2189         public static void FreeBSTR(IntPtr ptr)
2190         {
2191             if (IsNotWin32Atom(ptr)) {
2192                 Win32Native.SysFreeString(ptr);
2193             }
2194         }
2195 
2196         [System.Security.SecurityCritical]  // auto-generated_required
StringToBSTR(String s)2197         public static IntPtr StringToBSTR(String s)
2198         {
2199             if (s == null)
2200                 return IntPtr.Zero;
2201 
2202             // Overflow checking
2203             if (s.Length+1 < s.Length)
2204                 throw new ArgumentOutOfRangeException("s");
2205 
2206             IntPtr bstr = Win32Native.SysAllocStringLen(s, s.Length);
2207             if (bstr == IntPtr.Zero)
2208                 throw new OutOfMemoryException();
2209 
2210             return bstr;
2211         }
2212 
2213         [System.Security.SecurityCritical]  // auto-generated_required
PtrToStringBSTR(IntPtr ptr)2214         public static String PtrToStringBSTR(IntPtr ptr)
2215         {
2216             return PtrToStringUni(ptr, (int)Win32Native.SysStringLen(ptr));
2217         }
2218 
2219         [System.Security.SecurityCritical]  // auto-generated_required
2220         [ResourceExposure(ResourceScope.None)]
2221         [MethodImplAttribute(MethodImplOptions.InternalCall)]
GetNativeVariantForObject(Object obj, IntPtr pDstNativeVariant)2222         public static extern void GetNativeVariantForObject(Object obj, /* VARIANT * */ IntPtr pDstNativeVariant);
2223 
2224         [System.Security.SecurityCritical]
GetNativeVariantForObject(T obj, IntPtr pDstNativeVariant)2225         public static void GetNativeVariantForObject<T>(T obj, IntPtr pDstNativeVariant)
2226         {
2227             GetNativeVariantForObject((object)obj, pDstNativeVariant);
2228         }
2229 
2230         [System.Security.SecurityCritical]  // auto-generated_required
2231         [ResourceExposure(ResourceScope.None)]
2232         [MethodImplAttribute(MethodImplOptions.InternalCall)]
GetObjectForNativeVariant( IntPtr pSrcNativeVariant )2233         public static extern Object GetObjectForNativeVariant(/* VARIANT * */ IntPtr pSrcNativeVariant );
2234 
2235         [System.Security.SecurityCritical]
GetObjectForNativeVariant(IntPtr pSrcNativeVariant)2236         public static T GetObjectForNativeVariant<T>(IntPtr pSrcNativeVariant)
2237         {
2238             return (T)GetObjectForNativeVariant(pSrcNativeVariant);
2239         }
2240 
2241         [System.Security.SecurityCritical]  // auto-generated_required
2242         [ResourceExposure(ResourceScope.None)]
2243         [MethodImplAttribute(MethodImplOptions.InternalCall)]
GetObjectsForNativeVariants( IntPtr aSrcNativeVariant, int cVars )2244         public static extern Object[] GetObjectsForNativeVariants(/* VARIANT * */ IntPtr aSrcNativeVariant, int cVars );
2245 
2246         [System.Security.SecurityCritical]
GetObjectsForNativeVariants(IntPtr aSrcNativeVariant, int cVars)2247         public static T[] GetObjectsForNativeVariants<T>(IntPtr aSrcNativeVariant, int cVars)
2248         {
2249             object[] objects = GetObjectsForNativeVariants(aSrcNativeVariant, cVars);
2250             T[] result = null;
2251 
2252             if (objects != null)
2253             {
2254                 result = new T[objects.Length];
2255                 Array.Copy(objects, result, objects.Length);
2256             }
2257 
2258             return result;
2259         }
2260 
2261         /// <summary>
2262         /// <para>Returns the first valid COM slot that GetMethodInfoForSlot will work on
2263         /// This will be 3 for IUnknown based interfaces and 7 for IDispatch based interfaces. </para>
2264         /// </summary>
2265         [System.Security.SecurityCritical]  // auto-generated_required
2266         [ResourceExposure(ResourceScope.None)]
2267         [MethodImplAttribute(MethodImplOptions.InternalCall)]
GetStartComSlot(Type t)2268         public static extern int GetStartComSlot(Type t);
2269 
2270         /// <summary>
2271         /// <para>Returns the last valid COM slot that GetMethodInfoForSlot will work on. </para>
2272         /// </summary>
2273         [System.Security.SecurityCritical]  // auto-generated_required
2274         [ResourceExposure(ResourceScope.None)]
2275         [MethodImplAttribute(MethodImplOptions.InternalCall)]
GetEndComSlot(Type t)2276         public static extern int GetEndComSlot(Type t);
2277 
2278         /// <summary>
2279         /// <para>Returns the MemberInfo that COM callers calling through the exposed
2280         /// vtable on the given slot will be calling. The slot should take into account
2281         /// if the exposed interface is IUnknown based or IDispatch based.
2282         /// For classes, the lookup is done on the default interface that will be
2283         /// exposed for the class. </para>
2284         /// </summary>
2285         [System.Security.SecurityCritical]  // auto-generated_required
2286         [ResourceExposure(ResourceScope.None)]
2287         [MethodImplAttribute(MethodImplOptions.InternalCall)]
GetMethodInfoForComSlot(Type t, int slot, ref ComMemberType memberType)2288         public static extern MemberInfo GetMethodInfoForComSlot(Type t, int slot, ref ComMemberType memberType);
2289 
2290         /// <summary>
2291         /// <para>Returns the COM slot for a memeber info, taking into account whether
2292         /// the exposed interface is IUnknown based or IDispatch based</para>
2293         /// </summary>
2294         [System.Security.SecurityCritical]  // auto-generated_required
GetComSlotForMethodInfo(MemberInfo m)2295         public static int GetComSlotForMethodInfo(MemberInfo m)
2296         {
2297             if (m== null)
2298                 throw new ArgumentNullException("m");
2299 
2300             if (!(m is RuntimeMethodInfo))
2301                 throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo"), "m");
2302 
2303             if (!m.DeclaringType.IsInterface)
2304                 throw new ArgumentException(Environment.GetResourceString("Argument_MustBeInterfaceMethod"), "m");
2305             if (m.DeclaringType.IsGenericType)
2306                 throw new ArgumentException(Environment.GetResourceString("Argument_NeedNonGenericType"), "m");
2307             Contract.EndContractBlock();
2308 
2309             return InternalGetComSlotForMethodInfo((IRuntimeMethodInfo)m);
2310         }
2311 
2312         [ResourceExposure(ResourceScope.None)]
2313         [MethodImplAttribute(MethodImplOptions.InternalCall)]
InternalGetComSlotForMethodInfo(IRuntimeMethodInfo m)2314         private static extern int InternalGetComSlotForMethodInfo(IRuntimeMethodInfo m);
2315 
2316         //====================================================================
2317         // This method generates a GUID for the specified type. If the type
2318         // has a GUID in the metadata then it is returned otherwise a stable
2319         // guid GUID is generated based on the fully qualified name of the
2320         // type.
2321         //====================================================================
2322         [System.Security.SecurityCritical]  // auto-generated_required
GenerateGuidForType(Type type)2323         public static Guid GenerateGuidForType(Type type)
2324         {
2325             Guid result = new Guid ();
2326             FCallGenerateGuidForType (ref result, type);
2327             return result;
2328         }
2329 
2330         // The full assembly name is used to compute the GUID, so this should be SxS-safe
2331         [ResourceExposure(ResourceScope.None)]
2332         [MethodImplAttribute(MethodImplOptions.InternalCall)]
FCallGenerateGuidForType(ref Guid result, Type type)2333         private static extern void FCallGenerateGuidForType(ref Guid result, Type type);
2334 
2335         //====================================================================
2336         // This method generates a PROGID for the specified type. If the type
2337         // has a PROGID in the metadata then it is returned otherwise a stable
2338         // PROGID is generated based on the fully qualified name of the
2339         // type.
2340         //====================================================================
2341         [System.Security.SecurityCritical]  // auto-generated_required
GenerateProgIdForType(Type type)2342         public static String GenerateProgIdForType(Type type)
2343         {
2344             if (type == null)
2345                 throw new ArgumentNullException("type");
2346             if (type.IsImport)
2347                 throw new ArgumentException(Environment.GetResourceString("Argument_TypeMustNotBeComImport"), "type");
2348             if (type.IsGenericType)
2349                 throw new ArgumentException(Environment.GetResourceString("Argument_NeedNonGenericType"), "type");
2350             Contract.EndContractBlock();
2351 
2352             if (!RegistrationServices.TypeRequiresRegistrationHelper(type))
2353                 throw new ArgumentException(Environment.GetResourceString("Argument_TypeMustBeComCreatable"), "type");
2354 
2355             IList<CustomAttributeData> cas = CustomAttributeData.GetCustomAttributes(type);
2356             for (int i = 0; i < cas.Count; i ++)
2357             {
2358                 if (cas[i].Constructor.DeclaringType == typeof(ProgIdAttribute))
2359                 {
2360                     // Retrieve the PROGID string from the ProgIdAttribute.
2361                     IList<CustomAttributeTypedArgument> caConstructorArgs = cas[i].ConstructorArguments;
2362                     Contract.Assert(caConstructorArgs.Count == 1, "caConstructorArgs.Count == 1");
2363 
2364                     CustomAttributeTypedArgument progIdConstructorArg = caConstructorArgs[0];
2365                     Contract.Assert(progIdConstructorArg.ArgumentType == typeof(String), "progIdConstructorArg.ArgumentType == typeof(String)");
2366 
2367                     String strProgId = (String)progIdConstructorArg.Value;
2368 
2369                     if (strProgId == null)
2370                         strProgId = String.Empty;
2371 
2372                     return strProgId;
2373                 }
2374             }
2375 
2376             // If there is no prog ID attribute then use the full name of the type as the prog id.
2377             return type.FullName;
2378         }
2379 
2380         //====================================================================
2381         // This method binds to the specified moniker.
2382         //====================================================================
2383         [System.Security.SecurityCritical]  // auto-generated_required
2384         [ResourceExposure(ResourceScope.Machine)]
2385         [ResourceConsumption(ResourceScope.Machine)]
BindToMoniker(String monikerName)2386         public static Object BindToMoniker(String monikerName)
2387         {
2388             Object obj = null;
2389             IBindCtx bindctx = null;
2390             CreateBindCtx(0, out bindctx);
2391 
2392             UInt32 cbEaten;
2393             IMoniker pmoniker = null;
2394             MkParseDisplayName(bindctx, monikerName, out cbEaten, out pmoniker);
2395 
2396             BindMoniker(pmoniker, 0, ref IID_IUnknown, out obj);
2397             return obj;
2398         }
2399 
2400         //====================================================================
2401         // This method gets the currently running object.
2402         //====================================================================
2403         [System.Security.SecurityCritical]  // auto-generated_required
GetActiveObject(String progID)2404         public static Object GetActiveObject(String progID)
2405         {
2406             Object obj = null;
2407             Guid clsid;
2408 
2409             // Call CLSIDFromProgIDEx first then fall back on CLSIDFromProgID if
2410             // CLSIDFromProgIDEx doesn't exist.
2411             try
2412             {
2413                 CLSIDFromProgIDEx(progID, out clsid);
2414             }
2415 //            catch
2416             catch(Exception)
2417             {
2418                 CLSIDFromProgID(progID, out clsid);
2419             }
2420 
2421             GetActiveObject(ref clsid, IntPtr.Zero, out obj);
2422             return obj;
2423         }
2424 
2425         [DllImport(Microsoft.Win32.Win32Native.OLE32, PreserveSig = false)]
2426         [ResourceExposure(ResourceScope.None)]
2427         [SuppressUnmanagedCodeSecurity]
2428         [System.Security.SecurityCritical]  // auto-generated
CLSIDFromProgIDEx([MarshalAs(UnmanagedType.LPWStr)] String progId, out Guid clsid)2429         private static extern void CLSIDFromProgIDEx([MarshalAs(UnmanagedType.LPWStr)] String progId, out Guid clsid);
2430 
2431         [DllImport(Microsoft.Win32.Win32Native.OLE32, PreserveSig = false)]
2432         [ResourceExposure(ResourceScope.None)]
2433         [SuppressUnmanagedCodeSecurity]
2434         [System.Security.SecurityCritical]  // auto-generated
CLSIDFromProgID([MarshalAs(UnmanagedType.LPWStr)] String progId, out Guid clsid)2435         private static extern void CLSIDFromProgID([MarshalAs(UnmanagedType.LPWStr)] String progId, out Guid clsid);
2436 
2437         [DllImport(Microsoft.Win32.Win32Native.OLE32, PreserveSig = false)]
2438         [ResourceExposure(ResourceScope.None)]
2439         [SuppressUnmanagedCodeSecurity]
2440         [System.Security.SecurityCritical]  // auto-generated
CreateBindCtx(UInt32 reserved, out IBindCtx ppbc)2441         private static extern void CreateBindCtx(UInt32 reserved, out IBindCtx ppbc);
2442 
2443         [DllImport(Microsoft.Win32.Win32Native.OLE32, PreserveSig = false)]
2444         [ResourceExposure(ResourceScope.Machine)]
2445         [SuppressUnmanagedCodeSecurity]
2446         [System.Security.SecurityCritical]  // auto-generated
MkParseDisplayName(IBindCtx pbc, [MarshalAs(UnmanagedType.LPWStr)] String szUserName, out UInt32 pchEaten, out IMoniker ppmk)2447         private static extern void MkParseDisplayName(IBindCtx pbc, [MarshalAs(UnmanagedType.LPWStr)] String szUserName, out UInt32 pchEaten, out IMoniker ppmk);
2448 
2449         [DllImport(Microsoft.Win32.Win32Native.OLE32, PreserveSig = false)]
2450         [ResourceExposure(ResourceScope.None)]
2451         [SuppressUnmanagedCodeSecurity]
2452         [System.Security.SecurityCritical]  // auto-generated
BindMoniker(IMoniker pmk, UInt32 grfOpt, ref Guid iidResult, [MarshalAs(UnmanagedType.Interface)] out Object ppvResult)2453         private static extern void BindMoniker(IMoniker pmk, UInt32 grfOpt, ref Guid iidResult, [MarshalAs(UnmanagedType.Interface)] out Object ppvResult);
2454 
2455         [DllImport(Microsoft.Win32.Win32Native.OLEAUT32, PreserveSig = false)]
2456         [ResourceExposure(ResourceScope.None)]
2457         [SuppressUnmanagedCodeSecurity]
2458         [System.Security.SecurityCritical]  // auto-generated
GetActiveObject(ref Guid rclsid, IntPtr reserved, [MarshalAs(UnmanagedType.Interface)] out Object ppunk)2459         private static extern void GetActiveObject(ref Guid rclsid, IntPtr reserved, [MarshalAs(UnmanagedType.Interface)] out Object ppunk);
2460 
2461         //========================================================================
2462         // Private method called from remoting to support ServicedComponents.
2463         //========================================================================
2464         [ResourceExposure(ResourceScope.None)]
2465         [MethodImplAttribute(MethodImplOptions.InternalCall)]
InternalSwitchCCW(Object oldtp, Object newtp)2466         internal static extern bool InternalSwitchCCW(Object oldtp, Object newtp);
2467 
2468         [ResourceExposure(ResourceScope.None)]
2469         [MethodImplAttribute(MethodImplOptions.InternalCall)]
InternalWrapIUnknownWithComObject(IntPtr i)2470         internal static extern Object InternalWrapIUnknownWithComObject(IntPtr i);
2471 
2472         //========================================================================
2473         // Private method called from EE upon use of license/ICF2 marshaling.
2474         //========================================================================
2475         [SecurityCritical]
LoadLicenseManager()2476         private static IntPtr LoadLicenseManager()
2477         {
2478             Assembly sys = Assembly.Load("System, Version="+ ThisAssembly.Version +
2479                 ", Culture=neutral, PublicKeyToken=" + AssemblyRef.EcmaPublicKeyToken);
2480             Type t = sys.GetType("System.ComponentModel.LicenseManager");
2481             if (t == null || !t.IsVisible)
2482                 return IntPtr.Zero;
2483             return t.TypeHandle.Value;
2484         }
2485 
2486         [System.Security.SecurityCritical]  // auto-generated_required
2487         [ResourceExposure(ResourceScope.None)]
2488         [MethodImplAttribute(MethodImplOptions.InternalCall)]
ChangeWrapperHandleStrength(Object otp, bool fIsWeak)2489         public static extern void ChangeWrapperHandleStrength(Object otp, bool fIsWeak);
2490 
2491         [System.Security.SecurityCritical]
2492         [ResourceExposure(ResourceScope.None)]
2493         [MethodImplAttribute(MethodImplOptions.InternalCall)]
InitializeWrapperForWinRT(object o, ref IntPtr pUnk)2494         internal static extern void InitializeWrapperForWinRT(object o, ref IntPtr pUnk);
2495 
2496 #if FEATURE_COMINTEROP_WINRT_MANAGED_ACTIVATION
2497         [System.Security.SecurityCritical]
2498         [ResourceExposure(ResourceScope.None)]
2499         [MethodImplAttribute(MethodImplOptions.InternalCall)]
InitializeManagedWinRTFactoryObject(object o, RuntimeType runtimeClassType)2500         internal static extern void InitializeManagedWinRTFactoryObject(object o, RuntimeType runtimeClassType);
2501 #endif
2502 
2503         //========================================================================
2504         // Create activation factory and wraps it with a unique RCW
2505         //========================================================================
2506         [System.Security.SecurityCritical]
2507         [ResourceExposure(ResourceScope.None)]
2508         [MethodImplAttribute(MethodImplOptions.InternalCall)]
GetNativeActivationFactory(Type type)2509         internal static extern object GetNativeActivationFactory(Type type);
2510 
2511         //========================================================================
2512         // Methods allowing retrieval of the IIDs exposed by an underlying WinRT
2513         // object, as specified by the object's IInspectable::GetIids()
2514         //========================================================================
2515         [System.Security.SecurityCritical]
2516         [ResourceExposure(ResourceScope.None)]
2517         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
_GetInspectableIids(ObjectHandleOnStack obj, ObjectHandleOnStack guids)2518         private static extern void _GetInspectableIids(ObjectHandleOnStack obj, ObjectHandleOnStack guids);
2519 
2520         [System.Security.SecurityCritical]
GetInspectableIids(object obj)2521         internal static System.Guid[] GetInspectableIids(object obj)
2522         {
2523             System.Guid[] result = null;
2524             System.__ComObject comObj = obj as System.__ComObject;
2525             if (comObj != null)
2526             {
2527                 _GetInspectableIids(JitHelpers.GetObjectHandleOnStack(ref comObj),
2528                                     JitHelpers.GetObjectHandleOnStack(ref result));
2529             }
2530 
2531             return result;
2532         }
2533 
2534         //========================================================================
2535         // Methods allowing retrieval of the cached WinRT type corresponding to
2536         // the specified GUID
2537         //========================================================================
2538         [System.Security.SecurityCritical]
2539         [ResourceExposure(ResourceScope.None)]
2540         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
_GetCachedWinRTTypeByIid( ObjectHandleOnStack appDomainObj, System.Guid iid, out IntPtr rthHandle)2541         private static extern void _GetCachedWinRTTypeByIid(
2542                         ObjectHandleOnStack appDomainObj,
2543                         System.Guid iid,
2544                         out IntPtr rthHandle);
2545 
2546         [System.Security.SecurityCritical]
GetCachedWinRTTypeByIid( System.AppDomain ad, System.Guid iid)2547         internal static System.Type GetCachedWinRTTypeByIid(
2548                         System.AppDomain ad,
2549                         System.Guid iid)
2550         {
2551             IntPtr rthHandle;
2552             _GetCachedWinRTTypeByIid(JitHelpers.GetObjectHandleOnStack(ref ad),
2553                         iid,
2554                         out rthHandle);
2555             System.Type res = Type.GetTypeFromHandleUnsafe(rthHandle);
2556             return res;
2557         }
2558 
2559 
2560         //========================================================================
2561         // Methods allowing retrieval of the WinRT types cached in the specified
2562         // app domain
2563         //========================================================================
2564         [System.Security.SecurityCritical]
2565         [ResourceExposure(ResourceScope.None)]
2566         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
_GetCachedWinRTTypes( ObjectHandleOnStack appDomainObj, ref int epoch, ObjectHandleOnStack winrtTypes)2567         private static extern void _GetCachedWinRTTypes(
2568                         ObjectHandleOnStack appDomainObj,
2569                         ref int epoch,
2570                         ObjectHandleOnStack winrtTypes);
2571 
2572         [System.Security.SecurityCritical]
GetCachedWinRTTypes( System.AppDomain ad, ref int epoch)2573         internal static System.Type[] GetCachedWinRTTypes(
2574                         System.AppDomain ad,
2575                         ref int epoch)
2576         {
2577             System.IntPtr[] res = null;
2578 
2579             _GetCachedWinRTTypes(JitHelpers.GetObjectHandleOnStack(ref ad),
2580                                 ref epoch,
2581                                 JitHelpers.GetObjectHandleOnStack(ref res));
2582 
2583             System.Type[] result = new System.Type[res.Length];
2584             for (int i = 0; i < res.Length; ++i)
2585             {
2586                 result[i] = Type.GetTypeFromHandleUnsafe(res[i]);
2587             }
2588 
2589             return result;
2590         }
2591 
2592         [System.Security.SecurityCritical]
GetCachedWinRTTypes( System.AppDomain ad)2593         internal static System.Type[] GetCachedWinRTTypes(
2594                         System.AppDomain ad)
2595         {
2596             int dummyEpoch = 0;
2597             return GetCachedWinRTTypes(ad, ref dummyEpoch);
2598         }
2599 
2600 
2601 #endif // FEATURE_COMINTEROP
2602 
2603         [System.Security.SecurityCritical]  // auto-generated_required
GetDelegateForFunctionPointer(IntPtr ptr, Type t)2604         public static Delegate GetDelegateForFunctionPointer(IntPtr ptr, Type t)
2605         {
2606             // Validate the parameters
2607             if (ptr == IntPtr.Zero)
2608                 throw new ArgumentNullException("ptr");
2609 
2610             if (t == null)
2611                 throw new ArgumentNullException("t");
2612             Contract.EndContractBlock();
2613 
2614             if ((t as RuntimeType) == null)
2615                 throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), "t");
2616 
2617             if (t.IsGenericType)
2618                 throw new ArgumentException(Environment.GetResourceString("Argument_NeedNonGenericType"), "t");
2619 
2620             Type c = t.BaseType;
2621             if (c == null || (c != typeof(Delegate) && c != typeof(MulticastDelegate)))
2622                 throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"), "t");
2623 
2624             return GetDelegateForFunctionPointerInternal(ptr, t);
2625         }
2626 
2627         [System.Security.SecurityCritical]
GetDelegateForFunctionPointer(IntPtr ptr)2628         public static TDelegate GetDelegateForFunctionPointer<TDelegate>(IntPtr ptr)
2629         {
2630             return (TDelegate)(object)GetDelegateForFunctionPointer(ptr, typeof(TDelegate));
2631         }
2632 
2633         [ResourceExposure(ResourceScope.None)]
2634         [MethodImplAttribute(MethodImplOptions.InternalCall)]
GetDelegateForFunctionPointerInternal(IntPtr ptr, Type t)2635         internal static extern Delegate GetDelegateForFunctionPointerInternal(IntPtr ptr, Type t);
2636 
2637         [System.Security.SecurityCritical]  // auto-generated_required
GetFunctionPointerForDelegate(Delegate d)2638         public static IntPtr GetFunctionPointerForDelegate(Delegate d)
2639         {
2640             if (d == null)
2641                 throw new ArgumentNullException("d");
2642             Contract.EndContractBlock();
2643 
2644             return GetFunctionPointerForDelegateInternal(d);
2645         }
2646 
2647         [System.Security.SecurityCritical]
GetFunctionPointerForDelegate(TDelegate d)2648         public static IntPtr GetFunctionPointerForDelegate<TDelegate>(TDelegate d)
2649         {
2650             return GetFunctionPointerForDelegate((Delegate)(object)d);
2651         }
2652 
2653         [ResourceExposure(ResourceScope.None)]
2654         [MethodImplAttribute(MethodImplOptions.InternalCall)]
GetFunctionPointerForDelegateInternal(Delegate d)2655         internal static extern IntPtr GetFunctionPointerForDelegateInternal(Delegate d);
2656 
2657 #if FEATURE_COMINTEROP
2658         [System.Security.SecurityCritical]  // auto-generated_required
SecureStringToBSTR(SecureString s)2659         public static IntPtr SecureStringToBSTR(SecureString s) {
2660             if( s == null) {
2661                 throw new ArgumentNullException("s");
2662             }
2663             Contract.EndContractBlock();
2664 
2665             return s.ToBSTR();
2666         }
2667 #endif
2668 
2669         [System.Security.SecurityCritical]  // auto-generated_required
SecureStringToCoTaskMemAnsi(SecureString s)2670         public static IntPtr SecureStringToCoTaskMemAnsi(SecureString s) {
2671             if( s == null) {
2672                 throw new ArgumentNullException("s");
2673             }
2674             Contract.EndContractBlock();
2675 
2676             return s.ToAnsiStr(false);
2677         }
2678 
2679         [System.Security.SecurityCritical]  // auto-generated_required
SecureStringToCoTaskMemUnicode(SecureString s)2680         public static IntPtr SecureStringToCoTaskMemUnicode(SecureString s)
2681         {
2682             if (s == null)
2683             {
2684                 throw new ArgumentNullException("s");
2685             }
2686             Contract.EndContractBlock();
2687 
2688             return s.ToUniStr(false);
2689         }
2690 
2691 #if FEATURE_COMINTEROP
2692         [System.Security.SecurityCritical]  // auto-generated_required
ZeroFreeBSTR(IntPtr s)2693         public static void ZeroFreeBSTR(IntPtr s)
2694         {
2695             Win32Native.ZeroMemory(s, (UIntPtr)(Win32Native.SysStringLen(s) * 2));
2696             FreeBSTR(s);
2697         }
2698 #endif
2699 
2700         [System.Security.SecurityCritical]  // auto-generated_required
ZeroFreeCoTaskMemAnsi(IntPtr s)2701         public static void ZeroFreeCoTaskMemAnsi(IntPtr s)
2702         {
2703             Win32Native.ZeroMemory(s, (UIntPtr)(Win32Native.lstrlenA(s)));
2704             FreeCoTaskMem(s);
2705         }
2706 
2707         [System.Security.SecurityCritical]  // auto-generated_required
ZeroFreeCoTaskMemUnicode(IntPtr s)2708         public static void ZeroFreeCoTaskMemUnicode(IntPtr s)
2709         {
2710             Win32Native.ZeroMemory(s, (UIntPtr)(Win32Native.lstrlenW(s) * 2));
2711             FreeCoTaskMem(s);
2712         }
2713 
2714         [System.Security.SecurityCritical]  // auto-generated_required
SecureStringToGlobalAllocAnsi(SecureString s)2715         public static IntPtr SecureStringToGlobalAllocAnsi(SecureString s) {
2716             if( s == null) {
2717                 throw new ArgumentNullException("s");
2718             }
2719             Contract.EndContractBlock();
2720 
2721             return s.ToAnsiStr(true);
2722         }
2723 
2724         [System.Security.SecurityCritical]  // auto-generated_required
SecureStringToGlobalAllocUnicode(SecureString s)2725         public static IntPtr SecureStringToGlobalAllocUnicode(SecureString s) {
2726             if( s == null) {
2727                 throw new ArgumentNullException("s");
2728             }
2729             Contract.EndContractBlock();
2730 
2731             return s.ToUniStr(true);
2732         }
2733 
2734         [System.Security.SecurityCritical]  // auto-generated_required
ZeroFreeGlobalAllocAnsi(IntPtr s)2735         public static void ZeroFreeGlobalAllocAnsi(IntPtr s) {
2736             Win32Native.ZeroMemory(s, (UIntPtr)(Win32Native.lstrlenA(s)));
2737             FreeHGlobal(s);
2738         }
2739 
2740         [System.Security.SecurityCritical]  // auto-generated_required
ZeroFreeGlobalAllocUnicode(IntPtr s)2741         public static void ZeroFreeGlobalAllocUnicode(IntPtr s) {
2742             Win32Native.ZeroMemory(s, (UIntPtr)(Win32Native.lstrlenW(s) * 2));
2743             FreeHGlobal(s);
2744         }
2745     }
2746 
2747 #if FEATURE_COMINTEROP && !FEATURE_CORECLR // current implementation requires reflection only load
2748     //========================================================================
2749     // Typelib importer callback implementation.
2750     //========================================================================
2751     internal class ImporterCallback : ITypeLibImporterNotifySink
2752     {
ReportEvent(ImporterEventKind EventKind, int EventCode, String EventMsg)2753         public void ReportEvent(ImporterEventKind EventKind, int EventCode, String EventMsg)
2754         {
2755         }
2756 
2757         [System.Security.SecuritySafeCritical] // overrides transparent public member
ResolveRef(Object TypeLib)2758         public Assembly ResolveRef(Object TypeLib)
2759         {
2760             try
2761             {
2762                 // Create the TypeLibConverter.
2763                 ITypeLibConverter TLBConv = new TypeLibConverter();
2764 
2765                 // Convert the typelib.
2766                 return TLBConv.ConvertTypeLibToAssembly(TypeLib,
2767                                                         Marshal.GetTypeLibName((ITypeLib)TypeLib) + ".dll",
2768                                                         0,
2769                                                         new ImporterCallback(),
2770                                                         null,
2771                                                         null,
2772                                                         null,
2773                                                         null);
2774             }
2775             catch(Exception)
2776 //            catch
2777             {
2778                 return null;
2779             }
2780         }
2781     }
2782 #endif // FEATURE_COMINTEROP && !FEATURE_CORECLR
2783 }
2784 
2785