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