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