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