Merge pull request #3394 from mono/netstandard
[mono.git] / mcs / class / corlib / System.Runtime.InteropServices / Marshal.cs
1 // System.Runtime.InteropServices.Marshal.cs
2 //
3 // Sean MacIsaac (macisaac@ximian.com)
4 // Paolo Molaro (lupus@ximian.com)
5 // Dietmar Maurer (dietmar@ximian.com)
6 // Jonathan Chambers (joncham@gmail.com)
7 //
8 // (C) 2001-2002 Ximian, Inc.
9
10 //
11 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
12 //
13 // Permission is hereby granted, free of charge, to any person obtaining
14 // a copy of this software and associated documentation files (the
15 // "Software"), to deal in the Software without restriction, including
16 // without limitation the rights to use, copy, modify, merge, publish,
17 // distribute, sublicense, and/or sell copies of the Software, and to
18 // permit persons to whom the Software is furnished to do so, subject to
19 // the following conditions:
20 // 
21 // The above copyright notice and this permission notice shall be
22 // included in all copies or substantial portions of the Software.
23 // 
24 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
25 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
27 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
28 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
29 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
30 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
31 //
32
33 using System.Collections;
34 using System.Collections.Generic;
35 using System.Runtime.CompilerServices;
36 using System;
37 using System.Security;
38 using System.Reflection;
39 using System.Threading;
40
41 using System.Runtime.ConstrainedExecution;
42 #if !FULL_AOT_RUNTIME
43 using System.Runtime.InteropServices.ComTypes;
44 using Mono.Interop;
45 #endif
46
47 namespace System.Runtime.InteropServices
48 {
49         public static class Marshal
50         {
51                 /* fields */
52                 public static readonly int SystemMaxDBCSCharSize = 2; // don't know what this is
53                 public static readonly int SystemDefaultCharSize = Environment.IsRunningOnWindows ? 2 : 1;
54
55 #if !MOBILE
56                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
57                 private extern static int AddRefInternal (IntPtr pUnk);
58 #endif
59
60                 public static int AddRef (IntPtr pUnk)
61                 {
62 #if !MOBILE
63                         if (pUnk == IntPtr.Zero)
64                                 throw new ArgumentException ("Value cannot be null.", "pUnk");
65                         return AddRefInternal (pUnk);
66 #else
67                         throw new NotImplementedException ();
68 #endif
69                 }
70
71                 [MonoTODO]
72                 public static bool AreComObjectsAvailableForCleanup ()
73                 {
74                         return false;
75                 }
76
77                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
78                 public extern static IntPtr AllocCoTaskMem (int cb);
79
80                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
81                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
82                 public extern static IntPtr AllocHGlobal (IntPtr cb);
83
84                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
85                 public static IntPtr AllocHGlobal (int cb)
86                 {
87                         return AllocHGlobal ((IntPtr)cb);
88                 }
89
90                 [MonoTODO]
91                 public static object BindToMoniker (string monikerName)
92                 {
93                         throw new NotImplementedException ();
94                 }
95
96                 [MonoTODO]
97                 public static void ChangeWrapperHandleStrength (object otp, bool fIsWeak)
98                 {
99                         throw new NotImplementedException ();
100                 }
101
102                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
103                 internal extern static void copy_to_unmanaged (Array source, int startIndex,
104                                                                IntPtr destination, int length);
105
106                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
107                 internal extern static void copy_from_unmanaged (IntPtr source, int startIndex,
108                                                                  Array destination, int length);
109
110                 public static void Copy (byte[] source, int startIndex, IntPtr destination, int length)
111                 {
112                         copy_to_unmanaged (source, startIndex, destination, length);
113                 }
114
115                 public static void Copy (char[] source, int startIndex, IntPtr destination, int length)
116                 {
117                         copy_to_unmanaged (source, startIndex, destination, length);
118                 }
119
120                 public static void Copy (short[] source, int startIndex, IntPtr destination, int length)
121                 {
122                         copy_to_unmanaged (source, startIndex, destination, length);
123                 }
124
125                 public static void Copy (int[] source, int startIndex, IntPtr destination, int length)
126                 {
127                         copy_to_unmanaged (source, startIndex, destination, length);
128                 }
129
130                 public static void Copy (long[] source, int startIndex, IntPtr destination, int length)
131                 {
132                         copy_to_unmanaged (source, startIndex, destination, length);
133                 }
134
135                 public static void Copy (float[] source, int startIndex, IntPtr destination, int length)
136                 {
137                         copy_to_unmanaged (source, startIndex, destination, length);
138                 }
139
140                 public static void Copy (double[] source, int startIndex, IntPtr destination, int length)
141                 {
142                         copy_to_unmanaged (source, startIndex, destination, length);
143                 }
144
145                 public static void Copy (IntPtr[] source, int startIndex, IntPtr destination, int length)
146                 {
147                         copy_to_unmanaged (source, startIndex, destination, length);
148                 }
149
150                 public static void Copy (IntPtr source, byte[] destination, int startIndex, int length)
151                 {
152                         copy_from_unmanaged (source, startIndex, destination, length);
153                 }
154
155                 public static void Copy (IntPtr source, char[] destination, int startIndex, int length)
156                 {
157                         copy_from_unmanaged (source, startIndex, destination, length);
158                 }
159
160                 public static void Copy (IntPtr source, short[] destination, int startIndex, int length)
161                 {
162                         copy_from_unmanaged (source, startIndex, destination, length);
163                 }
164
165                 public static void Copy (IntPtr source, int[] destination, int startIndex, int length)
166                 {
167                         copy_from_unmanaged (source, startIndex, destination, length);
168                 }
169
170                 public static void Copy (IntPtr source, long[] destination, int startIndex, int length)
171                 {
172                         copy_from_unmanaged (source, startIndex, destination, length);
173                 }
174
175                 public static void Copy (IntPtr source, float[] destination, int startIndex, int length)
176                 {
177                         copy_from_unmanaged (source, startIndex, destination, length);
178                 }
179
180                 public static void Copy (IntPtr source, double[] destination, int startIndex, int length)
181                 {
182                         copy_from_unmanaged (source, startIndex, destination, length);
183                 }
184
185                 public static void Copy (IntPtr source, IntPtr[] destination, int startIndex, int length)
186                 {
187                         copy_from_unmanaged (source, startIndex, destination, length);
188                 }
189
190                 public static IntPtr CreateAggregatedObject (IntPtr pOuter,
191                                                              object o)
192                 {
193                         throw new NotImplementedException ();
194                 }
195
196                 public static IntPtr CreateAggregatedObject<T> (IntPtr pOuter, T o) {
197                         return CreateAggregatedObject (pOuter, (object)o);
198                 }
199
200 #if !FULL_AOT_RUNTIME
201                 public static object CreateWrapperOfType (object o, Type t)
202                 {
203                         __ComObject co = o as __ComObject;
204                         if (co == null)
205                                 throw new ArgumentException ("o must derive from __ComObject", "o");
206                         if (t == null)
207                                 throw new ArgumentNullException ("t");
208
209                         Type[] itfs = o.GetType ().GetInterfaces ();
210                         foreach (Type itf in itfs) {
211                                 if (itf.IsImport && co.GetInterface (itf) == IntPtr.Zero)
212                                         throw new InvalidCastException ();
213                         }
214
215                         return ComInteropProxy.GetProxy (co.IUnknown, t).GetTransparentProxy ();
216                 }
217
218                 public static TWrapper CreateWrapperOfType<T, TWrapper> (T o) {
219                         return (TWrapper)CreateWrapperOfType ((object)o, typeof (TWrapper));
220                 }
221 #endif
222
223                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
224                 [ComVisible (true)]
225                 public extern static void DestroyStructure (IntPtr ptr, Type structuretype);
226
227                 public static void DestroyStructure<T> (IntPtr ptr) {
228                         DestroyStructure (ptr, typeof (T));
229                 }
230
231                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
232                 public extern static void FreeBSTR (IntPtr ptr);
233
234                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
235                 public extern static void FreeCoTaskMem (IntPtr ptr);
236
237                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
238                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
239                 public extern static void FreeHGlobal (IntPtr hglobal);
240
241                 static void ClearBSTR (IntPtr ptr)
242                 {
243                         int len = ReadInt32 (ptr, -4);
244
245                         for (int i = 0; i < len; i++)
246                                 WriteByte (ptr, i, 0);
247                 }
248                 
249                 public static void ZeroFreeBSTR (IntPtr s)
250                 {
251                         ClearBSTR (s);
252                         FreeBSTR (s);
253                 }
254
255                 static void ClearAnsi (IntPtr ptr)
256                 {
257                         for (int i = 0; ReadByte (ptr, i) != 0; i++)
258                                 WriteByte (ptr, i, 0);
259                 }
260
261                 static void ClearUnicode (IntPtr ptr)
262                 {
263                         for (int i = 0; ReadInt16 (ptr, i) != 0; i += 2)
264                                 WriteInt16 (ptr, i, 0);
265                 }
266                 
267                 public static void ZeroFreeCoTaskMemAnsi (IntPtr s)
268                 {
269                         ClearAnsi (s);
270                         FreeCoTaskMem (s);
271                 }
272
273                 public static void ZeroFreeCoTaskMemUnicode (IntPtr s)
274                 {
275                         ClearUnicode (s);
276                         FreeCoTaskMem (s);
277                 }
278
279                 public static void ZeroFreeGlobalAllocAnsi (IntPtr s)
280                 {
281                         ClearAnsi (s);
282                         FreeHGlobal (s);
283                 }
284
285                 public static void ZeroFreeGlobalAllocUnicode (IntPtr s)
286                 {
287                         ClearUnicode (s);
288                         FreeHGlobal (s);
289                 }
290
291 #if !FULL_AOT_RUNTIME
292                 public static Guid GenerateGuidForType (Type type)
293                 {
294                         return type.GUID;
295                 }
296
297                 public static string GenerateProgIdForType (Type type)
298                 {
299                         IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (type);
300
301                         foreach (var a in attrs)
302                         {
303                                 var dt = a.Constructor.DeclaringType;
304                                 string name = dt.Name;
305                                 if (name == "ProgIdAttribute")
306                                 {
307                                         var args = a.ConstructorArguments;
308                                         string text = a.ConstructorArguments[0].Value as string;
309                                         if (text == null)
310                                         {
311                                                 text = string.Empty;
312                                         }
313                                         return text;
314                                 }
315                         }
316
317                         return type.FullName;
318                 }
319
320                 [MonoTODO]
321                 public static object GetActiveObject (string progID)
322                 {
323                         throw new NotImplementedException ();
324                 }
325
326 #if !MOBILE
327                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
328                 private extern static IntPtr GetCCW (object o, Type T);
329
330                 private static IntPtr GetComInterfaceForObjectInternal (object o, Type T)
331                 {
332                         if (IsComObject (o))
333                                 return ((__ComObject)o).GetInterface (T);
334                         else
335                                 return GetCCW (o, T);
336                 }
337 #endif
338
339                 public static IntPtr GetComInterfaceForObject (object o, Type T)
340                 {
341 #if !MOBILE
342                         IntPtr pItf = GetComInterfaceForObjectInternal (o, T);
343                         AddRef (pItf);
344                         return pItf;
345 #else
346                         throw new NotImplementedException ();
347 #endif
348                 }
349
350                 [MonoTODO]
351                 public static IntPtr GetComInterfaceForObject (object o, Type T, CustomQueryInterfaceMode mode)
352                 {
353                         throw new NotImplementedException ();
354                 }
355
356                 public static IntPtr GetComInterfaceForObject<T, TInterface> (T o) {
357                         return GetComInterfaceForObject ((object)o, typeof (T));
358                 }
359
360                 [MonoTODO]
361                 public static IntPtr GetComInterfaceForObjectInContext (object o, Type t)
362                 {
363                         throw new NotImplementedException ();
364                 }
365
366                 [MonoNotSupportedAttribute ("MSDN states user code should never need to call this method.")]
367                 public static object GetComObjectData (object obj, object key)
368                 {
369                         throw new NotSupportedException ("MSDN states user code should never need to call this method.");
370                 }
371
372 #if !MOBILE
373                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
374                 private extern static int GetComSlotForMethodInfoInternal (MemberInfo m);
375 #endif
376
377                 public static int GetComSlotForMethodInfo (MemberInfo m)
378                 {
379 #if !MOBILE
380                         if (m == null)
381                                 throw new ArgumentNullException ("m");
382                         if (!(m is MethodInfo))
383                                 throw new ArgumentException ("The MemberInfo must be an interface method.", "m");
384                         if (!m.DeclaringType.IsInterface)
385                                 throw new ArgumentException ("The MemberInfo must be an interface method.", "m");
386                         return GetComSlotForMethodInfoInternal (m);
387 #else
388                         throw new NotImplementedException ();
389 #endif
390                 }
391
392                 [MonoTODO]
393                 public static int GetEndComSlot (Type t)
394                 {
395                         throw new NotImplementedException ();
396                 }
397
398                 [MonoTODO]
399                 public static int GetExceptionCode()
400                 {
401                         throw new NotImplementedException ();
402                 }
403
404                 [MonoTODO]
405                 [ComVisible (true)]
406                 public static IntPtr GetExceptionPointers()
407                 {
408                         throw new NotImplementedException ();
409                 }
410
411                 public static IntPtr GetHINSTANCE (Module m)
412                 {
413                         if (m == null)
414                                 throw new ArgumentNullException ("m");
415
416                         return m.GetHINSTANCE ();
417                 }
418 #endif // !FULL_AOT_RUNTIME
419
420 #if !FULL_AOT_RUNTIME
421                 public static int GetHRForException (Exception e)
422                 {
423 #if FEATURE_COMINTEROP
424                         var errorInfo = new ManagedErrorInfo(e);
425                         SetErrorInfo (0, errorInfo);
426
427                         return e._HResult;
428 #else                   
429                         return -1;
430 #endif
431                 }
432
433                 [MonoTODO]
434                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
435                 public static int GetHRForLastWin32Error()
436                 {
437                         throw new NotImplementedException ();
438                 }
439
440                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
441                 private extern static IntPtr GetIDispatchForObjectInternal (object o);
442
443                 public static IntPtr GetIDispatchForObject (object o)
444                 {
445                         IntPtr pUnk = GetIDispatchForObjectInternal (o);
446                         // Internal method does not AddRef
447                         AddRef (pUnk);
448                         return pUnk;
449                 }
450
451                 [MonoTODO]
452                 public static IntPtr GetIDispatchForObjectInContext (object o)
453                 {
454                         throw new NotImplementedException ();
455                 }
456
457                 [MonoTODO]
458                 public static IntPtr GetITypeInfoForType (Type t)
459                 {
460                         throw new NotImplementedException ();
461                 }
462
463                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
464                 private extern static IntPtr GetIUnknownForObjectInternal (object o);
465
466                 public static IntPtr GetIUnknownForObject (object o)
467                 {
468                         IntPtr pUnk = GetIUnknownForObjectInternal (o);
469                         // Internal method does not AddRef
470                         AddRef (pUnk);
471                         return pUnk;
472                 }
473
474                 [MonoTODO]
475                 public static IntPtr GetIUnknownForObjectInContext (object o)
476                 {
477                         throw new NotImplementedException ();
478                 }
479
480                 [MonoTODO]
481                 [Obsolete ("This method has been deprecated")]
482                 public static IntPtr GetManagedThunkForUnmanagedMethodPtr (IntPtr pfnMethodToWrap, IntPtr pbSignature, int cbSignature)
483                 {
484                         throw new NotImplementedException ();
485                 }
486
487                 [MonoTODO]
488                 public static MemberInfo GetMethodInfoForComSlot (Type t, int slot, ref ComMemberType memberType)
489                 {
490                         throw new NotImplementedException ();
491                 }
492
493                 public static void GetNativeVariantForObject (object obj, IntPtr pDstNativeVariant)
494                 {
495                         Variant vt = new Variant();
496                         vt.SetValue(obj);
497                         Marshal.StructureToPtr(vt, pDstNativeVariant, false);
498                 }
499
500                 public static void GetNativeVariantForObject<T> (T obj, IntPtr pDstNativeVariant) {
501                         GetNativeVariantForObject ((object)obj, pDstNativeVariant);
502                 }
503
504 #if !MOBILE
505                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
506                 private static extern object GetObjectForCCW (IntPtr pUnk);
507 #endif
508
509                 public static object GetObjectForIUnknown (IntPtr pUnk)
510                 {
511 #if !MOBILE
512                         object obj = GetObjectForCCW (pUnk);
513                         // was not a CCW
514                         if (obj == null) {
515                                 ComInteropProxy proxy = ComInteropProxy.GetProxy (pUnk, typeof (__ComObject));
516                                 obj = proxy.GetTransparentProxy ();
517                         }
518                         return obj;
519 #else
520                         throw new NotImplementedException ();
521 #endif
522                 }
523
524                 public static object GetObjectForNativeVariant (IntPtr pSrcNativeVariant)
525                 {
526                         Variant vt = (Variant)Marshal.PtrToStructure(pSrcNativeVariant, typeof(Variant));
527                         return vt.GetValue();
528                 }
529
530                 public static T GetObjectForNativeVariant<T> (IntPtr pSrcNativeVariant) {
531                         Variant vt = (Variant)Marshal.PtrToStructure(pSrcNativeVariant, typeof(Variant));
532                         return (T)vt.GetValue();
533                 }
534
535                 public static object[] GetObjectsForNativeVariants (IntPtr aSrcNativeVariant, int cVars)
536                 {
537                         if (cVars < 0)
538                                 throw new ArgumentOutOfRangeException ("cVars", "cVars cannot be a negative number.");
539                         object[] objects = new object[cVars];
540                         for (int i = 0; i < cVars; i++)
541                                 objects[i] = GetObjectForNativeVariant ((IntPtr)(aSrcNativeVariant.ToInt64 () +
542                                         i * SizeOf (typeof(Variant))));
543                         return objects;
544                 }
545
546                 public static T[] GetObjectsForNativeVariants<T> (IntPtr aSrcNativeVariant, int cVars) {
547                         if (cVars < 0)
548                                 throw new ArgumentOutOfRangeException ("cVars", "cVars cannot be a negative number.");
549                         T[] objects = new T[cVars];
550                         for (int i = 0; i < cVars; i++)
551                                 objects[i] = GetObjectForNativeVariant<T> ((IntPtr)(aSrcNativeVariant.ToInt64 () +
552                                         i * SizeOf (typeof(Variant))));
553                         return objects;
554                 }
555
556                 [MonoTODO]
557                 public static int GetStartComSlot (Type t)
558                 {
559                         throw new NotImplementedException ();
560                 }
561
562                 [MonoTODO]
563                 [Obsolete ("This method has been deprecated")]
564                 public static Thread GetThreadFromFiberCookie (int cookie)
565                 {
566                         throw new NotImplementedException ();
567                 }
568
569                 public static object GetTypedObjectForIUnknown (IntPtr pUnk, Type t)
570                 {
571                         ComInteropProxy proxy = new ComInteropProxy (pUnk, t);
572                         __ComObject co = (__ComObject)proxy.GetTransparentProxy ();
573                         foreach (Type itf in t.GetInterfaces ()) {
574                                 if ((itf.Attributes & TypeAttributes.Import) == TypeAttributes.Import) {
575                                         if (co.GetInterface (itf) == IntPtr.Zero)
576                                                 return null;
577                                 }
578                         }
579                         return co;
580                 }
581
582                 [MonoTODO]
583                 public static Type GetTypeForITypeInfo (IntPtr piTypeInfo)
584                 {
585                         throw new NotImplementedException ();
586                 }
587
588                 public static Type GetTypeFromCLSID (Guid clsid)
589                 {
590                         throw new NotImplementedException ();                   
591                 }
592
593 #if !FULL_AOT_RUNTIME
594                 [Obsolete]
595                 [MonoTODO]
596                 public static string GetTypeInfoName (UCOMITypeInfo pTI)
597                 {
598                         throw new NotImplementedException ();
599                 }
600
601                 public static string GetTypeInfoName (ITypeInfo typeInfo)
602                 {
603                         throw new NotImplementedException ();
604                 }
605
606                 [Obsolete]
607                 [MonoTODO]
608                 public static Guid GetTypeLibGuid (UCOMITypeLib pTLB)
609                 {
610                         throw new NotImplementedException ();
611                 }
612
613                 [MonoTODO]
614                 public static Guid GetTypeLibGuid (ITypeLib typelib)
615                 {
616                         throw new NotImplementedException ();
617                 }
618
619                 [MonoTODO]
620                 public static Guid GetTypeLibGuidForAssembly (Assembly asm)
621                 {
622                         throw new NotImplementedException ();
623                 }
624
625                 [Obsolete]
626                 [MonoTODO]
627                 public static int GetTypeLibLcid (UCOMITypeLib pTLB)
628                 {
629                         throw new NotImplementedException ();
630                 }
631
632                 [MonoTODO]
633                 public static int GetTypeLibLcid (ITypeLib typelib)
634                 {
635                         throw new NotImplementedException ();
636                 }
637
638                 [Obsolete]
639                 [MonoTODO]
640                 public static string GetTypeLibName (UCOMITypeLib pTLB)
641                 {
642                         throw new NotImplementedException ();
643                 }
644
645                 [MonoTODO]
646                 public static string GetTypeLibName (ITypeLib typelib)
647                 {
648                         throw new NotImplementedException ();
649                 }
650
651                 [MonoTODO]
652                 public static void GetTypeLibVersionForAssembly (Assembly inputAssembly, out int majorVersion, out int minorVersion)
653                 {
654                         throw new NotImplementedException ();
655                 }
656
657                 public static object GetUniqueObjectForIUnknown (IntPtr unknown)
658                 {
659                         throw new NotImplementedException ();
660                 }
661 #endif
662
663                 [MonoTODO]
664                 [Obsolete ("This method has been deprecated")]
665                 public static IntPtr GetUnmanagedThunkForManagedMethodPtr (IntPtr pfnMethodToWrap, IntPtr pbSignature, int cbSignature)
666                 {
667                         throw new NotImplementedException ();
668                 }
669
670 #if !MOBILE
671                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
672                 public extern static bool IsComObject (object o);
673 #else
674                 public static bool IsComObject (object o)
675                 {
676                         throw new NotImplementedException ();
677                 }
678 #endif          
679
680                 [MonoTODO]
681                 public static bool IsTypeVisibleFromCom (Type t)
682                 {
683                         throw new NotImplementedException ();
684                 }
685
686                 [MonoTODO]
687                 public static int NumParamBytes (MethodInfo m)
688                 {
689                         throw new NotImplementedException ();
690                 }
691 #endif
692
693                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
694                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
695                 public static extern int GetLastWin32Error();
696
697                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
698                 public extern static IntPtr OffsetOf (Type t, string fieldName);
699
700                 public static IntPtr OffsetOf<T> (string fieldName) {
701                         return OffsetOf (typeof (T), fieldName);
702                 }
703
704                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
705                 public extern static void Prelink (MethodInfo m);
706
707                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
708                 public extern static void PrelinkAll (Type c);
709
710                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
711                 public extern static string PtrToStringAnsi (IntPtr ptr);
712                 
713                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
714                 public extern static string PtrToStringAnsi (IntPtr ptr, int len);
715
716                 public static string PtrToStringAuto (IntPtr ptr)
717                 {
718                         return SystemDefaultCharSize == 2
719                                 ? PtrToStringUni (ptr) : PtrToStringAnsi (ptr);
720                 }
721                 
722                 public static string PtrToStringAuto (IntPtr ptr, int len)
723                 {
724                         return SystemDefaultCharSize == 2
725                                 ? PtrToStringUni (ptr, len) : PtrToStringAnsi (ptr, len);
726                 }
727
728                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
729                 public extern static string PtrToStringUni (IntPtr ptr);
730
731                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
732                 public extern static string PtrToStringUni (IntPtr ptr, int len);
733
734 #if !MOBILE
735                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
736                 public extern static string PtrToStringBSTR (IntPtr ptr);
737 #else
738                 public static string PtrToStringBSTR (IntPtr ptr)
739                 {
740                         throw new NotImplementedException ();
741                 }
742 #endif
743                 
744                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
745                 [ComVisible (true)]
746                 public extern static void PtrToStructure (IntPtr ptr, object structure);
747
748                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
749                 [ComVisible (true)]
750                 public extern static object PtrToStructure (IntPtr ptr, Type structureType);
751
752                 public static void PtrToStructure<T> (IntPtr ptr, T structure) {
753                         PtrToStructure (ptr, (object)structure);
754                 }
755
756                 public static T PtrToStructure<T> (IntPtr ptr) {
757                         return (T) PtrToStructure (ptr, typeof (T));
758                 }
759
760 #if !MOBILE
761                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
762                 private extern static int QueryInterfaceInternal (IntPtr pUnk, ref Guid iid, out IntPtr ppv);
763 #endif
764
765                 public static int QueryInterface (IntPtr pUnk, ref Guid iid, out IntPtr ppv)
766                 {
767 #if !MOBILE
768                         if (pUnk == IntPtr.Zero)
769                                 throw new ArgumentException ("Value cannot be null.", "pUnk");
770                         return QueryInterfaceInternal (pUnk, ref iid, out ppv);
771 #else
772                         throw new NotImplementedException ();
773 #endif
774                 }
775
776                 public static byte ReadByte (IntPtr ptr)
777                 {
778                         unsafe {
779                                 return *(byte*)ptr;
780                         }
781                 }
782
783                 public static byte ReadByte (IntPtr ptr, int ofs) {
784                         unsafe {
785                                 return *((byte*)ptr + ofs);
786                         }
787                 }
788
789                 [MonoTODO]
790                 [SuppressUnmanagedCodeSecurity]
791                 public static byte ReadByte ([In, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs)
792                 {
793                         throw new NotImplementedException ();
794                 }
795
796                 public unsafe static short ReadInt16 (IntPtr ptr)
797                 {
798                         byte *addr = (byte *) ptr;
799                         
800                         // The mono JIT can't inline this due to the hight number of calls
801                         // return ReadInt16 (ptr, 0);
802                         
803                         if (((uint)addr & 1) == 0) 
804                                 return *(short*)addr;
805
806                         short s;
807                         Buffer.Memcpy ((byte*)&s, (byte*)ptr, 2);
808                         return s;
809                 }
810
811                 public unsafe static short ReadInt16 (IntPtr ptr, int ofs)
812                 {
813                         byte *addr = ((byte *) ptr) + ofs;
814
815                         if (((uint) addr & 1) == 0)
816                                 return *(short*)addr;
817
818                         short s;
819                         Buffer.Memcpy ((byte*)&s, addr, 2);
820                         return s;
821                 }
822
823                 [MonoTODO]
824                 [SuppressUnmanagedCodeSecurity]
825                 public static short ReadInt16 ([In, MarshalAs(UnmanagedType.AsAny)] object ptr, int ofs)
826                 {
827                         throw new NotImplementedException ();
828                 }
829
830                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
831                 public unsafe static int ReadInt32 (IntPtr ptr)
832                 {
833                         byte *addr = (byte *) ptr;
834                         
835                         if (((uint)addr & 3) == 0) 
836                                 return *(int*)addr;
837
838                         int s;
839                         Buffer.Memcpy ((byte*)&s, addr, 4);
840                         return s;
841                 }
842
843                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
844                 public unsafe static int ReadInt32 (IntPtr ptr, int ofs)
845                 {
846                         byte *addr = ((byte *) ptr) + ofs;
847                         
848                         if ((((int) addr) & 3) == 0)
849                                 return *(int*)addr;
850                         else {
851                                 int s;
852                                 Buffer.Memcpy ((byte*)&s, addr, 4);
853                                 return s;
854                         }
855                 }
856
857                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
858                 [MonoTODO]
859                 [SuppressUnmanagedCodeSecurity]
860                 public static int ReadInt32 ([In, MarshalAs(UnmanagedType.AsAny)] object ptr, int ofs)
861                 {
862                         throw new NotImplementedException ();
863                 }
864
865                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
866                 public unsafe static long ReadInt64 (IntPtr ptr)
867                 {
868                         byte *addr = (byte *) ptr;
869                                 
870                         // The real alignment might be 4 on some platforms, but this is just an optimization,
871                         // so it doesn't matter.
872                         if (((uint) addr & 7) == 0)
873                                 return *(long*)ptr;
874
875                         long s;
876                         Buffer.Memcpy ((byte*)&s, addr, 8);
877                         return s;
878                 }
879
880                 public unsafe static long ReadInt64 (IntPtr ptr, int ofs)
881                 {
882                         byte *addr = ((byte *) ptr) + ofs;
883
884                         if (((uint) addr & 7) == 0)
885                                 return *(long*)addr;
886                         
887                         long s;
888                         Buffer.Memcpy ((byte*)&s, addr, 8);
889                         return s;
890                 }
891
892                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
893                 [MonoTODO]
894                 [SuppressUnmanagedCodeSecurity]
895                 public static long ReadInt64 ([In, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs)
896                 {
897                         throw new NotImplementedException ();
898                 }
899
900                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
901                 public static IntPtr ReadIntPtr (IntPtr ptr)
902                 {
903                         if (IntPtr.Size == 4)
904                                 return (IntPtr)ReadInt32 (ptr);
905                         else
906                                 return (IntPtr)ReadInt64 (ptr);
907                 }
908                 
909                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
910                 public static IntPtr ReadIntPtr (IntPtr ptr, int ofs)
911                 {
912                         if (IntPtr.Size == 4)
913                                 return (IntPtr)ReadInt32 (ptr, ofs);
914                         else
915                                 return (IntPtr)ReadInt64 (ptr, ofs);
916                 }
917
918                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
919                 [MonoTODO]
920                 public static IntPtr ReadIntPtr ([In, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs)
921                 {
922                         throw new NotImplementedException ();
923                 }
924
925                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
926                 public extern static IntPtr ReAllocCoTaskMem (IntPtr pv, int cb);
927
928                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
929                 public extern static IntPtr ReAllocHGlobal (IntPtr pv, IntPtr cb);
930
931 #if !MOBILE
932                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
933                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
934                 private extern static int ReleaseInternal (IntPtr pUnk);
935 #endif
936
937                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
938                 public static int Release (IntPtr pUnk)
939                 {
940 #if !MOBILE
941                         if (pUnk == IntPtr.Zero)
942                                 throw new ArgumentException ("Value cannot be null.", "pUnk");
943
944                         return ReleaseInternal (pUnk);
945 #else
946                         throw new NotImplementedException ();
947 #endif
948                 }
949
950 #if !FULL_AOT_RUNTIME
951                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
952                 private extern static int ReleaseComObjectInternal (object co);
953
954                 public static int ReleaseComObject (object o)
955                 {
956                         if (o == null)
957                                 throw new ArgumentException ("Value cannot be null.", "o");
958                         if (!IsComObject (o))
959                                 throw new ArgumentException ("Value must be a Com object.", "o");
960                         return ReleaseComObjectInternal (o);
961                 }
962
963                 [Obsolete]
964                 [MonoTODO]
965                 public static void ReleaseThreadCache()
966                 {
967                         throw new NotImplementedException ();
968                 }
969
970                 [MonoNotSupportedAttribute ("MSDN states user code should never need to call this method.")]
971                 public static bool SetComObjectData (object obj, object key, object data)
972                 {
973                         throw new NotSupportedException ("MSDN states user code should never need to call this method.");
974                 }
975 #endif
976
977                 [ComVisible (true)]
978                 public static int SizeOf (object structure)
979                 {
980                         return SizeOf (structure.GetType ());
981                 }
982
983                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
984                 public extern static int SizeOf (Type t);
985
986                 public static int SizeOf<T> () {
987                         return SizeOf (typeof (T));
988                 }
989
990                 public static int SizeOf<T> (T structure) {
991                         return SizeOf (structure.GetType ());
992                 }
993
994                 internal static uint SizeOfType (Type type)
995                 {
996                         return (uint) SizeOf (type);
997                 }
998
999                 internal static uint AlignedSizeOf<T> () where T : struct
1000                 {
1001                         uint size = SizeOfType (typeof (T));
1002                         if (size == 1 || size == 2)
1003                                 return size;
1004                         if (IntPtr.Size == 8 && size == 4)
1005                                 return size;
1006                         return (size + 3) & (~((uint)3));
1007                 }
1008
1009                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1010                 public extern static IntPtr StringToBSTR (string s);
1011
1012                 //
1013                 // I believe this is wrong, because in Mono and in P/Invoke
1014                 // we treat "Ansi" conversions as UTF-8 conversions, while
1015                 // this one does not do this
1016                 //
1017                 public static IntPtr StringToCoTaskMemAnsi (string s)
1018                 {
1019                         int length = s.Length + 1;
1020                         IntPtr ctm = AllocCoTaskMem (length);
1021
1022                         byte[] asBytes = new byte[length];
1023                         for (int i = 0; i < s.Length; i++)
1024                                 asBytes[i] = (byte)s[i];
1025                         asBytes[s.Length] = 0;
1026
1027                         copy_to_unmanaged (asBytes, 0, ctm, length);
1028                         return ctm;
1029                 }
1030
1031                 public static IntPtr StringToCoTaskMemAuto (string s)
1032                 {
1033                         return SystemDefaultCharSize == 2
1034                                 ? StringToCoTaskMemUni (s) : StringToCoTaskMemAnsi (s);
1035                 }
1036
1037                 public static IntPtr StringToCoTaskMemUni (string s)
1038                 {
1039                         int length = s.Length + 1;
1040                         IntPtr ctm = AllocCoTaskMem (length * 2);
1041                         
1042                         char[] asChars = new char[length];
1043                         s.CopyTo (0, asChars, 0, s.Length);
1044                         asChars[s.Length] = '\0';
1045
1046                         copy_to_unmanaged (asChars, 0, ctm, length);
1047                         return ctm;
1048                 }
1049
1050                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1051                 public extern static IntPtr StringToHGlobalAnsi (string s);
1052
1053                 public static IntPtr StringToHGlobalAuto (string s)
1054                 {
1055                         return SystemDefaultCharSize == 2
1056                                 ? StringToHGlobalUni (s) : StringToHGlobalAnsi (s);
1057                 }
1058
1059                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1060                 public extern static IntPtr StringToHGlobalUni (string s);
1061
1062                 public static IntPtr SecureStringToBSTR (SecureString s)
1063                 {
1064                         if (s == null)
1065                                 throw new ArgumentNullException ("s");
1066
1067                         byte[] buffer = s.GetBuffer ();
1068                         int len = s.Length;
1069                         
1070                         // SecureString doesn't take endian-ness into account. 
1071                         // Therefore swap bytes here before we send it to c-side if little-endian.
1072                         if (BitConverter.IsLittleEndian) {
1073                                 for (int i = 0; i < buffer.Length; i += 2) {
1074                                         byte b = buffer[i];
1075                                         buffer[i] = buffer[i + 1];
1076                                         buffer[i + 1] = b;
1077                                 }
1078                         }
1079                         return BufferToBSTR (buffer, len);
1080         }
1081
1082                 public static IntPtr SecureStringToCoTaskMemAnsi (SecureString s)
1083                 {
1084                         if (s == null)
1085                                 throw new ArgumentNullException ("s");
1086                         int len = s.Length;
1087                         IntPtr ctm = AllocCoTaskMem (len + 1);
1088                         byte [] copy = new byte [len+1];
1089
1090                         try {
1091                                 byte [] buffer = s.GetBuffer ();
1092                                 int i = 0, j = 0;
1093                                 for (; i < len; i++, j += 2){
1094                                         copy [i] = buffer [j+1];
1095                                         buffer [j] = 0;
1096                                         buffer [j+1] = 0;
1097                                 }
1098                                 copy [i] = 0;
1099                                 copy_to_unmanaged (copy, 0, ctm, len+1);
1100                         } finally {
1101                                 // Ensure that we clear the buffer.
1102                                 for (int i = len; i > 0; ){
1103                                         i--;
1104                                         copy [i] = 0;
1105                                 }
1106                         }
1107                         return ctm;
1108                 }
1109
1110                 public static IntPtr SecureStringToCoTaskMemUnicode (SecureString s)
1111                 {
1112                         if (s == null)
1113                                 throw new ArgumentNullException ("s");
1114                         int len = s.Length;
1115                         IntPtr ctm = AllocCoTaskMem (len * 2 + 2);
1116                         byte [] buffer = null;
1117                         try {
1118                                 buffer = s.GetBuffer ();
1119                                 for (int i = 0; i < len; i++)
1120                                         WriteInt16 (ctm, i * 2, (short) ((buffer [(i*2)] << 8) | (buffer [i*2+1])));
1121                                 WriteInt16 (ctm, buffer.Length, 0);
1122                         } finally {
1123                                 if (buffer != null)
1124                                         for (int i = buffer.Length; i > 0; ){
1125                                                 i--;
1126                                                 buffer [i] = 0;
1127                                         }
1128                         }
1129                         return ctm;
1130                 }
1131
1132                 public static IntPtr SecureStringToGlobalAllocAnsi (SecureString s)
1133                 {
1134                         if (s == null)
1135                                 throw new ArgumentNullException ("s");
1136                         return SecureStringToCoTaskMemAnsi (s);
1137                 }
1138
1139                 public static IntPtr SecureStringToGlobalAllocUnicode (SecureString s)
1140                 {
1141                         if (s == null)
1142                                 throw new ArgumentNullException ("s");
1143                         return SecureStringToCoTaskMemUnicode (s);
1144                 }
1145
1146                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
1147                 [ComVisible (true)]
1148                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1149                 public extern static void StructureToPtr (object structure, IntPtr ptr, bool fDeleteOld);
1150
1151                 public static void StructureToPtr<T> (T structure, IntPtr ptr, bool fDeleteOld) {
1152                         StructureToPtr ((object)structure, ptr, fDeleteOld);
1153                 }
1154
1155                 public static void ThrowExceptionForHR (int errorCode) {
1156                         Exception ex = GetExceptionForHR (errorCode);
1157                         if (ex != null)
1158                                 throw ex;
1159                 }
1160
1161                 public static void ThrowExceptionForHR (int errorCode, IntPtr errorInfo) {
1162                         Exception ex = GetExceptionForHR (errorCode, errorInfo);
1163                         if (ex != null)
1164                                 throw ex;
1165                 }
1166
1167
1168                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1169                 public extern static IntPtr BufferToBSTR (Array ptr, int slen);
1170
1171                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1172                 public extern static IntPtr UnsafeAddrOfPinnedArrayElement (Array arr, int index);
1173
1174                 public static IntPtr UnsafeAddrOfPinnedArrayElement<T> (T[] arr, int index) {
1175                         return UnsafeAddrOfPinnedArrayElement ((Array)arr, index);
1176                 }
1177
1178                 public static void WriteByte (IntPtr ptr, byte val)
1179                 {
1180                         unsafe {
1181                                 *(byte*)ptr = val;
1182                         }
1183                 }
1184
1185                 public static void WriteByte (IntPtr ptr, int ofs, byte val) {
1186                         unsafe {
1187                                 *(byte*)(IntPtr.Add (ptr, ofs)) = val;
1188                         }
1189                 }
1190
1191                 [MonoTODO]
1192                 [SuppressUnmanagedCodeSecurity]
1193                 public static void WriteByte ([In, Out, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs, byte val)
1194                 {
1195                         throw new NotImplementedException ();
1196                 }
1197
1198                 public static unsafe void WriteInt16 (IntPtr ptr, short val)
1199                 {
1200                         byte *addr = (byte *) ptr;
1201                         
1202                         if (((uint)addr & 1) == 0)
1203                                 *(short*)addr = val;
1204                         else
1205                                 Buffer.Memcpy (addr, (byte*)&val, 2);
1206                 }
1207
1208                 public static unsafe void WriteInt16 (IntPtr ptr, int ofs, short val)
1209                 {
1210                         byte *addr = ((byte *) ptr) + ofs;
1211
1212                         if (((uint)addr & 1) == 0)
1213                                 *(short*)addr = val;
1214                         else {
1215                                 Buffer.Memcpy (addr, (byte*)&val, 2);
1216                         }
1217                 }
1218
1219                 [MonoTODO]
1220                 [SuppressUnmanagedCodeSecurity]
1221                 public static void WriteInt16 ([In, Out, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs, short val)
1222                 {
1223                         throw new NotImplementedException ();
1224                 }
1225
1226                 public static void WriteInt16 (IntPtr ptr, char val)
1227                 {
1228                         WriteInt16 (ptr, 0, (short)val);
1229                 }
1230
1231                 public static void WriteInt16 (IntPtr ptr, int ofs, char val)
1232                 {
1233                         WriteInt16 (ptr, ofs, (short)val);
1234                 }
1235
1236                 [MonoTODO]
1237                 public static void WriteInt16([In, Out] object ptr, int ofs, char val)
1238                 {
1239                         throw new NotImplementedException ();
1240                 }
1241
1242                 public static unsafe void WriteInt32 (IntPtr ptr, int val)
1243                 {
1244                         byte *addr = (byte *) ptr;
1245                         
1246                         if (((uint)addr & 3) == 0) 
1247                                 *(int*)addr = val;
1248                         else {
1249                                 Buffer.Memcpy (addr, (byte*)&val, 4);
1250                         }
1251                 }
1252
1253                 public unsafe static void WriteInt32 (IntPtr ptr, int ofs, int val)
1254                 {
1255                         byte *addr = ((byte *) ptr) + ofs;
1256
1257                         if (((uint)addr & 3) == 0) 
1258                                 *(int*)addr = val;
1259                         else {
1260                                 Buffer.Memcpy (addr, (byte*)&val, 4);
1261                         }
1262                 }
1263
1264                 [MonoTODO]
1265                 [SuppressUnmanagedCodeSecurity]
1266                 public static void WriteInt32([In, Out, MarshalAs(UnmanagedType.AsAny)] object ptr, int ofs, int val)
1267                 {
1268                         throw new NotImplementedException ();
1269                 }
1270
1271                 public static unsafe void WriteInt64 (IntPtr ptr, long val)
1272                 {
1273                         byte *addr = (byte *) ptr;
1274                         
1275                         // The real alignment might be 4 on some platforms, but this is just an optimization,
1276                         // so it doesn't matter.
1277                         if (((uint)addr & 7) == 0) 
1278                                 *(long*)addr = val;
1279                         else 
1280                                 Buffer.Memcpy (addr, (byte*)&val, 8);
1281                 }
1282
1283                 public static unsafe void WriteInt64 (IntPtr ptr, int ofs, long val)
1284                 {
1285                         byte *addr = ((byte *) ptr) + ofs;
1286
1287                         // The real alignment might be 4 on some platforms, but this is just an optimization,
1288                         // so it doesn't matter.
1289                         if (((uint)addr & 7) == 0) 
1290                                 *(long*)addr = val;
1291                         else 
1292                                 Buffer.Memcpy (addr, (byte*)&val, 8);
1293                 }
1294
1295                 [MonoTODO]
1296                 [SuppressUnmanagedCodeSecurity]
1297                 public static void WriteInt64 ([In, Out, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs, long val)
1298                 {
1299                         throw new NotImplementedException ();
1300                 }
1301
1302                 public static void WriteIntPtr (IntPtr ptr, IntPtr val)
1303                 {
1304                         if (IntPtr.Size == 4)
1305                                 WriteInt32 (ptr, (int)val);
1306                         else
1307                                 WriteInt64 (ptr, (long)val);
1308                 }
1309
1310                 public static void WriteIntPtr (IntPtr ptr, int ofs, IntPtr val)
1311                 {
1312                         if (IntPtr.Size == 4)
1313                                 WriteInt32 (ptr, ofs, (int)val);
1314                         else
1315                                 WriteInt64 (ptr, ofs, (long)val);
1316                 }
1317
1318                 [MonoTODO]
1319                 public static void WriteIntPtr([In, Out, MarshalAs(UnmanagedType.AsAny)] object ptr, int ofs, IntPtr val)
1320                 {
1321                         throw new NotImplementedException ();
1322                 }
1323
1324                 private static Exception ConvertHrToException (int errorCode)
1325                 {
1326                         const int MSEE_E_APPDOMAINUNLOADED = unchecked ((int)0x80131014L);
1327                         const int COR_E_APPLICATION = unchecked ((int)0x80131600L);
1328                         const int E_INVALIDARG = unchecked ((int)0x80070057);
1329                         const int COR_E_ARGUMENTOUTOFRANGE = unchecked ((int)0x80131502L);
1330                         const int COR_E_ARITHMETIC = unchecked ((int)0x80070216);
1331                         const int COR_E_ARRAYTYPEMISMATCH = unchecked ((int)0x80131503L);
1332                         const int COR_E_BADIMAGEFORMAT = unchecked ((int)0x8007000BL);
1333                         const int ERROR_BAD_FORMAT = unchecked ((int)0x0B);
1334                         //const int COR_E_COMEMULATE_ERROR = unchecked ((int)?);
1335                         const int COR_E_CONTEXTMARSHAL = unchecked ((int)0x80131504L);
1336                         //const int COR_E_CORE = unchecked ((int)?);
1337                         const int NTE_FAIL = unchecked ((int)0x80090020L);
1338                         const int COR_E_DIRECTORYNOTFOUND = unchecked ((int)0x80070003L);
1339                         const int ERROR_PATH_NOT_FOUND = unchecked ((int)0x03);
1340                         const int COR_E_DIVIDEBYZERO = unchecked ((int)0x80020012L);
1341                         const int COR_E_DUPLICATEWAITOBJECT = unchecked ((int)0x80131529L);
1342                         const int COR_E_ENDOFSTREAM = unchecked ((int)0x80070026L);
1343                         const int COR_E_TYPELOAD = unchecked ((int)0x80131522L);
1344                         const int COR_E_EXCEPTION = unchecked ((int)0x80131500L);
1345                         const int COR_E_EXECUTIONENGINE = unchecked ((int)0x80131506L);
1346                         const int COR_E_FIELDACCESS = unchecked ((int)0x80131507L);
1347                         const int COR_E_FILENOTFOUND = unchecked ((int)0x80070002L);
1348                         const int ERROR_FILE_NOT_FOUND = unchecked ((int)0x02);
1349                         const int COR_E_FORMAT = unchecked ((int)0x80131537L);
1350                         const int COR_E_INDEXOUTOFRANGE = unchecked ((int)0x80131508L);
1351                         const int COR_E_INVALIDCAST = unchecked ((int)0x80004002L);
1352                         const int COR_E_INVALIDCOMOBJECT = unchecked ((int)0x80131527L);
1353                         const int COR_E_INVALIDFILTERCRITERIA = unchecked ((int)0x80131601L);
1354                         const int COR_E_INVALIDOLEVARIANTTYPE = unchecked ((int)0x80131531L);
1355                         const int COR_E_INVALIDOPERATION = unchecked ((int)0x80131509L);
1356                         const int COR_E_IO = unchecked ((int)0x80131620L);
1357                         const int COR_E_MEMBERACCESS = unchecked ((int)0x8013151AL);
1358                         const int COR_E_METHODACCESS = unchecked ((int)0x80131510L);
1359                         const int COR_E_MISSINGFIELD = unchecked ((int)0x80131511L);
1360                         const int COR_E_MISSINGMANIFESTRESOURCE = unchecked ((int)0x80131532L);
1361                         const int COR_E_MISSINGMEMBER = unchecked ((int)0x80131512L);
1362                         const int COR_E_MISSINGMETHOD = unchecked ((int)0x80131513L);
1363                         const int COR_E_MULTICASTNOTSUPPORTED = unchecked ((int)0x80131514L);
1364                         const int COR_E_NOTFINITENUMBER = unchecked ((int)0x80131528L);
1365                         const int E_NOTIMPL = unchecked ((int)0x80004001L);
1366                         const int COR_E_NOTSUPPORTED = unchecked ((int)0x80131515L);
1367                         const int COR_E_NULLREFERENCE = unchecked ((int)0x80004003L);
1368                         const int E_OUTOFMEMORY = unchecked ((int)0x8007000EL);
1369                         const int COR_E_OVERFLOW = unchecked ((int)0x80131516L);
1370                         const int COR_E_PATHTOOLONG = unchecked ((int)0x800700CEL);
1371                         const int ERROR_FILENAME_EXCED_RANGE = unchecked ((int)0xCE);
1372                         const int COR_E_RANK = unchecked ((int)0x80131517L);
1373                         const int COR_E_REFLECTIONTYPELOAD = unchecked ((int)0x80131602L);
1374                         const int COR_E_REMOTING = unchecked ((int)0x8013150BL);
1375                         const int COR_E_SAFEARRAYTYPEMISMATCH = unchecked ((int)0x80131533L);
1376                         const int COR_E_SECURITY = unchecked ((int)0x8013150AL);
1377                         const int COR_E_SERIALIZATION = unchecked ((int)0x8013150CL);
1378                         const int COR_E_STACKOVERFLOW = unchecked ((int)0x800703E9L);
1379                         const int ERROR_STACK_OVERFLOW = unchecked ((int)0x03E9);
1380                         const int COR_E_SYNCHRONIZATIONLOCK = unchecked ((int)0x80131518L);
1381                         const int COR_E_SYSTEM = unchecked ((int)0x80131501L);
1382                         const int COR_E_TARGET = unchecked ((int)0x80131603L);
1383                         const int COR_E_TARGETINVOCATION = unchecked ((int)0x80131604L);
1384                         const int COR_E_TARGETPARAMCOUNT = unchecked ((int)0x8002000EL);
1385                         const int COR_E_THREADABORTED = unchecked ((int)0x80131530L);
1386                         const int COR_E_THREADINTERRUPTED = unchecked ((int)0x80131519L);
1387                         const int COR_E_THREADSTATE = unchecked ((int)0x80131520L);
1388                         const int COR_E_THREADSTOP = unchecked ((int)0x80131521L);
1389                         const int COR_E_TYPEINITIALIZATION = unchecked ((int)0x80131534L);
1390                         const int COR_E_VERIFICATION = unchecked ((int)0x8013150DL);
1391                         //const int COR_E_WEAKREFERENCE = unchecked ((int)?);
1392                         //const int COR_E_VTABLECALLSNOTSUPPORTED = unchecked ((int));
1393
1394                         switch (errorCode) {
1395                                 case MSEE_E_APPDOMAINUNLOADED:
1396                                         return new AppDomainUnloadedException ();
1397                                 case COR_E_APPLICATION:
1398                                         return new ApplicationException ();
1399                                 case E_INVALIDARG:
1400                                         return new ArgumentException ();
1401                                 case COR_E_ARGUMENTOUTOFRANGE:
1402                                         return new ArgumentOutOfRangeException ();
1403                                 case COR_E_ARITHMETIC:
1404                                         return new ArithmeticException ();
1405                                 case COR_E_ARRAYTYPEMISMATCH:
1406                                         return new ArrayTypeMismatchException ();
1407                                 case COR_E_BADIMAGEFORMAT:
1408                                 case ERROR_BAD_FORMAT:
1409                                         return new BadImageFormatException ();
1410 //                              case COR_E_COMEMULATE_ERROR:
1411 //                                      return new COMEmulateException ();
1412                                 case COR_E_CONTEXTMARSHAL:
1413                                         return new ContextMarshalException ();
1414 //                              case COR_E_CORE:
1415 //                                      return new CoreException ();
1416                                 case NTE_FAIL:
1417                                         return new System.Security.Cryptography.CryptographicException ();
1418                                 case COR_E_DIRECTORYNOTFOUND:
1419                                 case ERROR_PATH_NOT_FOUND:
1420                                         return new System.IO.DirectoryNotFoundException ();
1421                                 case COR_E_DIVIDEBYZERO:
1422                                         return new DivideByZeroException ();
1423                                 case COR_E_DUPLICATEWAITOBJECT:
1424                                         return new DuplicateWaitObjectException ();
1425                                 case COR_E_ENDOFSTREAM:
1426                                         return new System.IO.EndOfStreamException ();
1427                                 case COR_E_EXCEPTION:
1428                                         return new Exception ();
1429                                 case COR_E_EXECUTIONENGINE:
1430                                         return new ExecutionEngineException ();
1431                                 case COR_E_FIELDACCESS:
1432                                         return new FieldAccessException ();
1433                                 case COR_E_FILENOTFOUND:
1434                                 case ERROR_FILE_NOT_FOUND:
1435                                         return new System.IO.FileNotFoundException ();
1436                                 case COR_E_FORMAT:
1437                                         return new FormatException ();
1438                                 case COR_E_INDEXOUTOFRANGE:
1439                                         return new IndexOutOfRangeException ();
1440                                 case COR_E_INVALIDCAST:
1441                                 // E_NOINTERFACE has same value as COR_E_INVALIDCAST
1442                                         return new InvalidCastException ();
1443                                 case COR_E_INVALIDCOMOBJECT:
1444                                         return new InvalidComObjectException ();
1445                                 case COR_E_INVALIDFILTERCRITERIA:
1446                                         return new InvalidFilterCriteriaException ();
1447                                 case COR_E_INVALIDOLEVARIANTTYPE:
1448                                         return new InvalidOleVariantTypeException ();
1449                                 case COR_E_INVALIDOPERATION:
1450                                         return new InvalidOperationException ();
1451                                 case COR_E_IO:
1452                                         return new System.IO.IOException ();
1453                                 case COR_E_MEMBERACCESS:
1454                                         return new MemberAccessException ();
1455                                 case COR_E_METHODACCESS:
1456                                         return new MethodAccessException ();
1457                                 case COR_E_MISSINGFIELD:
1458                                         return new MissingFieldException ();
1459                                 case COR_E_MISSINGMANIFESTRESOURCE:
1460                                         return new System.Resources.MissingManifestResourceException ();
1461                                 case COR_E_MISSINGMEMBER:
1462                                         return new MissingMemberException ();
1463                                 case COR_E_MISSINGMETHOD:
1464                                         return new MissingMethodException ();
1465                                 case COR_E_MULTICASTNOTSUPPORTED:
1466                                         return new MulticastNotSupportedException ();
1467                                 case COR_E_NOTFINITENUMBER:
1468                                         return new NotFiniteNumberException ();
1469                                 case E_NOTIMPL:
1470                                         return new NotImplementedException ();
1471                                 case COR_E_NOTSUPPORTED:
1472                                         return new NotSupportedException ();
1473                                 case COR_E_NULLREFERENCE:
1474                                 // E_POINTER has the same value as COR_E_NULLREFERENCE
1475                                         return new NullReferenceException ();
1476                                 case E_OUTOFMEMORY:
1477                                 // COR_E_OUTOFMEMORY has the same value as E_OUTOFMEMORY
1478                                         return new OutOfMemoryException ();
1479                                 case COR_E_OVERFLOW:
1480                                         return new OverflowException ();
1481                                 case COR_E_PATHTOOLONG:
1482                                 case ERROR_FILENAME_EXCED_RANGE:
1483                                         return new System.IO.PathTooLongException ();
1484                                 case COR_E_RANK:
1485                                         return new RankException ();
1486                                 case COR_E_REFLECTIONTYPELOAD:
1487                                         return new System.Reflection.ReflectionTypeLoadException (new Type[] { }, new Exception[] { });
1488                                 case COR_E_REMOTING:
1489                                         return new System.Runtime.Remoting.RemotingException ();
1490                                 case COR_E_SAFEARRAYTYPEMISMATCH:
1491                                         return new SafeArrayTypeMismatchException ();
1492                                 case COR_E_SECURITY:
1493                                         return new SecurityException ();
1494                                 case COR_E_SERIALIZATION:
1495                                         return new System.Runtime.Serialization.SerializationException ();
1496                                 case COR_E_STACKOVERFLOW:
1497                                 case ERROR_STACK_OVERFLOW:
1498                                         return new StackOverflowException ();
1499                                 case COR_E_SYNCHRONIZATIONLOCK:
1500                                         return new SynchronizationLockException ();
1501                                 case COR_E_SYSTEM:
1502                                         return new SystemException ();
1503                                 case COR_E_TARGET:
1504                                         return new TargetException ();
1505                                 case COR_E_TARGETINVOCATION:
1506                                         return new System.Reflection.TargetInvocationException (null);
1507                                 case COR_E_TARGETPARAMCOUNT:
1508                                         return new TargetParameterCountException ();
1509 //                              case COR_E_THREADABORTED:
1510 //                                      ThreadAbortException c'tor is inaccessible
1511 //                                      return new System.Threading.ThreadAbortException ();
1512                                 case COR_E_THREADINTERRUPTED:
1513                                         return new ThreadInterruptedException ();
1514                                 case COR_E_THREADSTATE:
1515                                         return new ThreadStateException ();
1516 //                              case COR_E_THREADSTOP:
1517 //                                      ThreadStopException does not exist
1518 //                                      return new System.Threading.ThreadStopException ();
1519                                 case COR_E_TYPELOAD:
1520                                         return new TypeLoadException ();
1521                                 // MSDN lists COR_E_TYPELOAD twice with different exceptions.
1522                                 // return new EntryPointNotFoundException ();
1523                                 case COR_E_TYPEINITIALIZATION:
1524                                         return new TypeInitializationException("", null);
1525                                 case COR_E_VERIFICATION:
1526                                         return new VerificationException ();
1527 //                              case COR_E_WEAKREFERENCE:
1528 //                                      return new WeakReferenceException ();
1529 //                              case COR_E_VTABLECALLSNOTSUPPORTED:
1530 //                                      return new VTableCallsNotSupportedException ();
1531                         }
1532                         if (errorCode < 0)
1533                                 return new COMException ("", errorCode);
1534                         return null;
1535                 }
1536
1537 #if FEATURE_COMINTEROP
1538                 [DllImport ("oleaut32.dll", CharSet=CharSet.Unicode, EntryPoint = "SetErrorInfo")]
1539                 static extern int _SetErrorInfo (int dwReserved,
1540                         [MarshalAs(UnmanagedType.Interface)] IErrorInfo pIErrorInfo);
1541
1542                 [DllImport ("oleaut32.dll", CharSet=CharSet.Unicode, EntryPoint = "GetErrorInfo")]
1543                 static extern int _GetErrorInfo (int dwReserved,
1544                         [MarshalAs(UnmanagedType.Interface)] out IErrorInfo ppIErrorInfo);
1545
1546                 static bool SetErrorInfoNotAvailable;
1547                 static bool GetErrorInfoNotAvailable;
1548
1549                 internal static int SetErrorInfo (int dwReserved, IErrorInfo errorInfo)
1550                 {
1551                         int retVal = 0;
1552                         errorInfo = null;
1553
1554                         if (SetErrorInfoNotAvailable)
1555                                 return -1;
1556
1557                         try {
1558                                 retVal = _SetErrorInfo (dwReserved, errorInfo);
1559                         }
1560                         catch (Exception) {
1561                                 // ignore any exception - probably there's no suitable SetErrorInfo
1562                                 // method available.
1563                                 SetErrorInfoNotAvailable = true;
1564                         }
1565                         return retVal;
1566                 }
1567
1568                 internal static int GetErrorInfo (int dwReserved, out IErrorInfo errorInfo)
1569                 {
1570                         int retVal = 0;
1571                         errorInfo = null;
1572
1573                         if (GetErrorInfoNotAvailable)
1574                                 return -1;
1575
1576                         try {
1577                                 retVal = _GetErrorInfo (dwReserved, out errorInfo);
1578                         }
1579                         catch (Exception) {
1580                                 // ignore any exception - probably there's no suitable GetErrorInfo
1581                                 // method available.
1582                                 GetErrorInfoNotAvailable = true;
1583                         }
1584                         return retVal;
1585                 }
1586 #endif
1587                 public static Exception GetExceptionForHR (int errorCode)
1588                 {
1589                         return GetExceptionForHR (errorCode, IntPtr.Zero);
1590                 }
1591
1592                 public static Exception GetExceptionForHR (int errorCode, IntPtr errorInfo)
1593                 {
1594 #if FEATURE_COMINTEROP
1595                         IErrorInfo info = null;
1596                         if (errorInfo != (IntPtr)(-1)) {
1597                                 if (errorInfo == IntPtr.Zero) {
1598                                         if (GetErrorInfo (0, out info) != 0) {
1599                                                 info  = null;
1600                                         }
1601                                 } else {
1602                                         info  = Marshal.GetObjectForIUnknown (errorInfo) as IErrorInfo;
1603                                 }
1604                         }
1605
1606                         if (info is ManagedErrorInfo && ((ManagedErrorInfo) info).Exception._HResult == errorCode) {
1607                                 return ((ManagedErrorInfo) info).Exception;
1608                         }
1609
1610                         Exception e = ConvertHrToException (errorCode);
1611                         if (info != null && e != null) {
1612                                 uint helpContext;
1613                                 info.GetHelpContext (out helpContext);
1614                                 string str;
1615                                 info.GetSource (out str);
1616                                 e.Source = str;
1617                                 info.GetDescription (out str);
1618                                 e.SetMessage (str);
1619                                 info.GetHelpFile (out str);
1620
1621                                 if (helpContext == 0) {
1622                                         e.HelpLink = str;
1623                                 } else {
1624                                         e.HelpLink = string.Format ("{0}#{1}", str, helpContext);
1625                                 }
1626                         }
1627                         return e;
1628 #else
1629                         return ConvertHrToException (errorCode);
1630 #endif
1631                 }
1632
1633 #if !FULL_AOT_RUNTIME
1634                 public static int FinalReleaseComObject (object o)
1635                 {
1636                         while (ReleaseComObject (o) != 0);
1637                         return 0;
1638                 }
1639 #endif
1640
1641                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1642                 private static extern Delegate GetDelegateForFunctionPointerInternal (IntPtr ptr, Type t);
1643
1644                 public static Delegate GetDelegateForFunctionPointer (IntPtr ptr, Type t)
1645                 {
1646                         if (t == null)
1647                                 throw new ArgumentNullException ("t");
1648                         if (!t.IsSubclassOf (typeof (MulticastDelegate)) || (t == typeof (MulticastDelegate)))
1649                                 throw new ArgumentException ("Type is not a delegate", "t");
1650                         if (t.IsGenericType)
1651                                 throw new ArgumentException ("The specified Type must not be a generic type definition.");
1652                         if (ptr == IntPtr.Zero)
1653                                 throw new ArgumentNullException ("ptr");
1654
1655                         return GetDelegateForFunctionPointerInternal (ptr, t);
1656                 }
1657
1658                 public static TDelegate GetDelegateForFunctionPointer<TDelegate> (IntPtr ptr) {
1659                         return (TDelegate) (object) GetDelegateForFunctionPointer (ptr, typeof (TDelegate));
1660                 }
1661
1662                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1663                 private static extern IntPtr GetFunctionPointerForDelegateInternal (Delegate d);
1664                 
1665                 public static IntPtr GetFunctionPointerForDelegate (Delegate d)
1666                 {
1667                         if (d == null)
1668                                 throw new ArgumentNullException ("d");
1669                         
1670                         return GetFunctionPointerForDelegateInternal (d);
1671                 }
1672
1673                 public static IntPtr GetFunctionPointerForDelegate<TDelegate> (TDelegate d) {
1674                         if (d == null)
1675                                 throw new ArgumentNullException ("d");
1676                         
1677                         return GetFunctionPointerForDelegateInternal ((Delegate)(object)d);
1678                 }
1679
1680                 internal static void SetLastWin32Error (int error)
1681                 {
1682                 }
1683         }
1684 }