Moving BSTR conv to native code in SecureStringToBSTR.
[mono.git] / mcs / class / corlib / System.Runtime.InteropServices / Marshal.cs
1 // System.Runtime.InteropServices.Marshal.cs
2 //
3 // Sean MacIsaac (macisaac@ximian.com)
4 // Paolo Molaro (lupus@ximian.com)
5 // Dietmar Maurer (dietmar@ximian.com)
6 // Jonathan Chambers (joncham@gmail.com)
7 //
8 // (C) 2001-2002 Ximian, Inc.
9
10 //
11 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
12 //
13 // Permission is hereby granted, free of charge, to any person obtaining
14 // a copy of this software and associated documentation files (the
15 // "Software"), to deal in the Software without restriction, including
16 // without limitation the rights to use, copy, modify, merge, publish,
17 // distribute, sublicense, and/or sell copies of the Software, and to
18 // permit persons to whom the Software is furnished to do so, subject to
19 // the following conditions:
20 // 
21 // The above copyright notice and this permission notice shall be
22 // included in all copies or substantial portions of the Software.
23 // 
24 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
25 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
27 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
28 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
29 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
30 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
31 //
32
33 using System.Collections;
34 using System.Collections.Generic;
35 using System.Runtime.CompilerServices;
36 using System;
37 using System.Security;
38 using System.Reflection;
39 using System.Threading;
40
41 using System.Runtime.ConstrainedExecution;
42 #if !FULL_AOT_RUNTIME
43 using System.Runtime.InteropServices.ComTypes;
44 using Mono.Interop;
45 #endif
46
47 namespace System.Runtime.InteropServices
48 {
49         public static class Marshal
50         {
51                 /* fields */
52                 public static readonly int SystemMaxDBCSCharSize = 2; // don't know what this is
53                 public static readonly int SystemDefaultCharSize = Environment.IsRunningOnWindows ? 2 : 1;
54
55 #if !MOBILE
56                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
57                 private extern static int AddRefInternal (IntPtr pUnk);
58 #endif
59
60                 public static int AddRef (IntPtr pUnk)
61                 {
62 #if !MOBILE
63                         if (pUnk == IntPtr.Zero)
64                                 throw new ArgumentException ("Value cannot be null.", "pUnk");
65                         return AddRefInternal (pUnk);
66 #else
67                         throw new NotImplementedException ();
68 #endif
69                 }
70
71                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
72                 public extern static IntPtr AllocCoTaskMem (int cb);
73
74                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
75                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
76                 public extern static IntPtr AllocHGlobal (IntPtr cb);
77
78                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
79                 public static IntPtr AllocHGlobal (int cb)
80                 {
81                         return AllocHGlobal ((IntPtr)cb);
82                 }
83
84                 [MonoTODO]
85                 public static object BindToMoniker (string monikerName)
86                 {
87                         throw new NotImplementedException ();
88                 }
89
90                 [MonoTODO]
91                 public static void ChangeWrapperHandleStrength (object otp, bool fIsWeak)
92                 {
93                         throw new NotImplementedException ();
94                 }
95
96                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
97                 internal extern static void copy_to_unmanaged (Array source, int startIndex,
98                                                                IntPtr destination, int length);
99
100                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
101                 internal extern static void copy_from_unmanaged (IntPtr source, int startIndex,
102                                                                  Array destination, int length);
103
104                 public static void Copy (byte[] source, int startIndex, IntPtr destination, int length)
105                 {
106                         copy_to_unmanaged (source, startIndex, destination, length);
107                 }
108
109                 public static void Copy (char[] source, int startIndex, IntPtr destination, int length)
110                 {
111                         copy_to_unmanaged (source, startIndex, destination, length);
112                 }
113
114                 public static void Copy (short[] source, int startIndex, IntPtr destination, int length)
115                 {
116                         copy_to_unmanaged (source, startIndex, destination, length);
117                 }
118
119                 public static void Copy (int[] source, int startIndex, IntPtr destination, int length)
120                 {
121                         copy_to_unmanaged (source, startIndex, destination, length);
122                 }
123
124                 public static void Copy (long[] source, int startIndex, IntPtr destination, int length)
125                 {
126                         copy_to_unmanaged (source, startIndex, destination, length);
127                 }
128
129                 public static void Copy (float[] source, int startIndex, IntPtr destination, int length)
130                 {
131                         copy_to_unmanaged (source, startIndex, destination, length);
132                 }
133
134                 public static void Copy (double[] source, int startIndex, IntPtr destination, int length)
135                 {
136                         copy_to_unmanaged (source, startIndex, destination, length);
137                 }
138
139                 public static void Copy (IntPtr[] source, int startIndex, IntPtr destination, int length)
140                 {
141                         copy_to_unmanaged (source, startIndex, destination, length);
142                 }
143
144                 public static void Copy (IntPtr source, byte[] destination, int startIndex, int length)
145                 {
146                         copy_from_unmanaged (source, startIndex, destination, length);
147                 }
148
149                 public static void Copy (IntPtr source, char[] destination, int startIndex, int length)
150                 {
151                         copy_from_unmanaged (source, startIndex, destination, length);
152                 }
153
154                 public static void Copy (IntPtr source, short[] destination, int startIndex, int length)
155                 {
156                         copy_from_unmanaged (source, startIndex, destination, length);
157                 }
158
159                 public static void Copy (IntPtr source, int[] destination, int startIndex, int length)
160                 {
161                         copy_from_unmanaged (source, startIndex, destination, length);
162                 }
163
164                 public static void Copy (IntPtr source, long[] destination, int startIndex, int length)
165                 {
166                         copy_from_unmanaged (source, startIndex, destination, length);
167                 }
168
169                 public static void Copy (IntPtr source, float[] destination, int startIndex, int length)
170                 {
171                         copy_from_unmanaged (source, startIndex, destination, length);
172                 }
173
174                 public static void Copy (IntPtr source, double[] destination, int startIndex, int length)
175                 {
176                         copy_from_unmanaged (source, startIndex, destination, length);
177                 }
178
179                 public static void Copy (IntPtr source, IntPtr[] destination, int startIndex, int length)
180                 {
181                         copy_from_unmanaged (source, startIndex, destination, length);
182                 }
183
184                 public static IntPtr CreateAggregatedObject (IntPtr pOuter,
185                                                              object o)
186                 {
187                         throw new NotImplementedException ();
188                 }
189
190                 public static IntPtr CreateAggregatedObject<T> (IntPtr pOuter, T o) {
191                         return CreateAggregatedObject (pOuter, (object)o);
192                 }
193
194 #if !FULL_AOT_RUNTIME
195                 public static object CreateWrapperOfType (object o, Type t)
196                 {
197                         __ComObject co = o as __ComObject;
198                         if (co == null)
199                                 throw new ArgumentException ("o must derive from __ComObject", "o");
200                         if (t == null)
201                                 throw new ArgumentNullException ("t");
202
203                         Type[] itfs = o.GetType ().GetInterfaces ();
204                         foreach (Type itf in itfs) {
205                                 if (itf.IsImport && co.GetInterface (itf) == IntPtr.Zero)
206                                         throw new InvalidCastException ();
207                         }
208
209                         return ComInteropProxy.GetProxy (co.IUnknown, t).GetTransparentProxy ();
210                 }
211
212                 public static TWrapper CreateWrapperOfType<T, TWrapper> (T o) {
213                         return (TWrapper)CreateWrapperOfType ((object)o, typeof (TWrapper));
214                 }
215 #endif
216
217                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
218                 [ComVisible (true)]
219                 public extern static void DestroyStructure (IntPtr ptr, Type structuretype);
220
221                 public static void DestroyStructure<T> (IntPtr ptr) {
222                         DestroyStructure (ptr, typeof (T));
223                 }
224
225                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
226                 public extern static void FreeBSTR (IntPtr ptr);
227
228                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
229                 public extern static void FreeCoTaskMem (IntPtr ptr);
230
231                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
232                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
233                 public extern static void FreeHGlobal (IntPtr hglobal);
234
235                 static void ClearBSTR (IntPtr ptr)
236                 {
237                         int len = ReadInt32 (ptr, -4);
238
239                         for (int i = 0; i < len; i++)
240                                 WriteByte (ptr, i, 0);
241                 }
242                 
243                 public static void ZeroFreeBSTR (IntPtr s)
244                 {
245                         ClearBSTR (s);
246                         FreeBSTR (s);
247                 }
248
249                 static void ClearAnsi (IntPtr ptr)
250                 {
251                         for (int i = 0; ReadByte (ptr, i) != 0; i++)
252                                 WriteByte (ptr, i, 0);
253                 }
254
255                 static void ClearUnicode (IntPtr ptr)
256                 {
257                         for (int i = 0; ReadInt16 (ptr, i) != 0; i += 2)
258                                 WriteInt16 (ptr, i, 0);
259                 }
260                 
261                 public static void ZeroFreeCoTaskMemAnsi (IntPtr s)
262                 {
263                         ClearAnsi (s);
264                         FreeCoTaskMem (s);
265                 }
266
267                 public static void ZeroFreeCoTaskMemUnicode (IntPtr s)
268                 {
269                         ClearUnicode (s);
270                         FreeCoTaskMem (s);
271                 }
272
273                 public static void ZeroFreeGlobalAllocAnsi (IntPtr s)
274                 {
275                         ClearAnsi (s);
276                         FreeHGlobal (s);
277                 }
278
279                 public static void ZeroFreeGlobalAllocUnicode (IntPtr s)
280                 {
281                         ClearUnicode (s);
282                         FreeHGlobal (s);
283                 }
284
285 #if !FULL_AOT_RUNTIME
286                 public static Guid GenerateGuidForType (Type type)
287                 {
288                         return type.GUID;
289                 }
290
291                 public static string GenerateProgIdForType (Type type)
292                 {
293                         IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (type);
294
295                         foreach (var a in attrs)
296                         {
297                                 var dt = a.Constructor.DeclaringType;
298                                 string name = dt.Name;
299                                 if (name == "ProgIdAttribute")
300                                 {
301                                         var args = a.ConstructorArguments;
302                                         string text = a.ConstructorArguments[0].Value as string;
303                                         if (text == null)
304                                         {
305                                                 text = string.Empty;
306                                         }
307                                         return text;
308                                 }
309                         }
310
311                         return type.FullName;
312                 }
313
314                 [MonoTODO]
315                 public static object GetActiveObject (string progID)
316                 {
317                         throw new NotImplementedException ();
318                 }
319
320 #if !MOBILE
321                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
322                 private extern static IntPtr GetCCW (object o, Type T);
323
324                 private static IntPtr GetComInterfaceForObjectInternal (object o, Type T)
325                 {
326                         if (IsComObject (o))
327                                 return ((__ComObject)o).GetInterface (T);
328                         else
329                                 return GetCCW (o, T);
330                 }
331 #endif
332
333                 public static IntPtr GetComInterfaceForObject (object o, Type T)
334                 {
335 #if !MOBILE
336                         IntPtr pItf = GetComInterfaceForObjectInternal (o, T);
337                         AddRef (pItf);
338                         return pItf;
339 #else
340                         throw new NotImplementedException ();
341 #endif
342                 }
343
344                 public static IntPtr GetComInterfaceForObject<T, TInterface> (T o) {
345                         return GetComInterfaceForObject ((object)o, typeof (T));
346                 }
347
348                 [MonoTODO]
349                 public static IntPtr GetComInterfaceForObjectInContext (object o, Type t)
350                 {
351                         throw new NotImplementedException ();
352                 }
353
354                 [MonoNotSupportedAttribute ("MSDN states user code should never need to call this method.")]
355                 public static object GetComObjectData (object obj, object key)
356                 {
357                         throw new NotSupportedException ("MSDN states user code should never need to call this method.");
358                 }
359
360 #if !MOBILE
361                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
362                 private extern static int GetComSlotForMethodInfoInternal (MemberInfo m);
363 #endif
364
365                 public static int GetComSlotForMethodInfo (MemberInfo m)
366                 {
367 #if !MOBILE
368                         if (m == null)
369                                 throw new ArgumentNullException ("m");
370                         if (!(m is MethodInfo))
371                                 throw new ArgumentException ("The MemberInfo must be an interface method.", "m");
372                         if (!m.DeclaringType.IsInterface)
373                                 throw new ArgumentException ("The MemberInfo must be an interface method.", "m");
374                         return GetComSlotForMethodInfoInternal (m);
375 #else
376                         throw new NotImplementedException ();
377 #endif
378                 }
379
380                 [MonoTODO]
381                 public static int GetEndComSlot (Type t)
382                 {
383                         throw new NotImplementedException ();
384                 }
385
386                 [MonoTODO]
387                 public static int GetExceptionCode()
388                 {
389                         throw new NotImplementedException ();
390                 }
391
392                 [MonoTODO]
393                 [ComVisible (true)]
394                 public static IntPtr GetExceptionPointers()
395                 {
396                         throw new NotImplementedException ();
397                 }
398
399                 public static IntPtr GetHINSTANCE (Module m)
400                 {
401                         if (m == null)
402                                 throw new ArgumentNullException ("m");
403
404                         return m.GetHINSTANCE ();
405                 }
406 #endif // !FULL_AOT_RUNTIME
407
408 #if !FULL_AOT_RUNTIME
409                 public static int GetHRForException (Exception e)
410                 {
411 #if FEATURE_COMINTEROP
412                         var errorInfo = new ManagedErrorInfo(e);
413                         SetErrorInfo (0, errorInfo);
414
415                         return e._HResult;
416 #else                   
417                         return -1;
418 #endif
419                 }
420
421                 [MonoTODO]
422                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
423                 public static int GetHRForLastWin32Error()
424                 {
425                         throw new NotImplementedException ();
426                 }
427
428                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
429                 private extern static IntPtr GetIDispatchForObjectInternal (object o);
430
431                 public static IntPtr GetIDispatchForObject (object o)
432                 {
433                         IntPtr pUnk = GetIDispatchForObjectInternal (o);
434                         // Internal method does not AddRef
435                         AddRef (pUnk);
436                         return pUnk;
437                 }
438
439                 [MonoTODO]
440                 public static IntPtr GetIDispatchForObjectInContext (object o)
441                 {
442                         throw new NotImplementedException ();
443                 }
444
445                 [MonoTODO]
446                 public static IntPtr GetITypeInfoForType (Type t)
447                 {
448                         throw new NotImplementedException ();
449                 }
450
451                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
452                 private extern static IntPtr GetIUnknownForObjectInternal (object o);
453
454                 public static IntPtr GetIUnknownForObject (object o)
455                 {
456                         IntPtr pUnk = GetIUnknownForObjectInternal (o);
457                         // Internal method does not AddRef
458                         AddRef (pUnk);
459                         return pUnk;
460                 }
461
462                 [MonoTODO]
463                 public static IntPtr GetIUnknownForObjectInContext (object o)
464                 {
465                         throw new NotImplementedException ();
466                 }
467
468                 [MonoTODO]
469                 [Obsolete ("This method has been deprecated")]
470                 public static IntPtr GetManagedThunkForUnmanagedMethodPtr (IntPtr pfnMethodToWrap, IntPtr pbSignature, int cbSignature)
471                 {
472                         throw new NotImplementedException ();
473                 }
474
475                 [MonoTODO]
476                 public static MemberInfo GetMethodInfoForComSlot (Type t, int slot, ref ComMemberType memberType)
477                 {
478                         throw new NotImplementedException ();
479                 }
480
481                 public static void GetNativeVariantForObject (object obj, IntPtr pDstNativeVariant)
482                 {
483                         Variant vt = new Variant();
484                         vt.SetValue(obj);
485                         Marshal.StructureToPtr(vt, pDstNativeVariant, false);
486                 }
487
488                 public static void GetNativeVariantForObject<T> (T obj, IntPtr pDstNativeVariant) {
489                         GetNativeVariantForObject ((object)obj, pDstNativeVariant);
490                 }
491
492 #if !MOBILE
493                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
494                 private static extern object GetObjectForCCW (IntPtr pUnk);
495 #endif
496
497                 public static object GetObjectForIUnknown (IntPtr pUnk)
498                 {
499 #if !MOBILE
500                         object obj = GetObjectForCCW (pUnk);
501                         // was not a CCW
502                         if (obj == null) {
503                                 ComInteropProxy proxy = ComInteropProxy.GetProxy (pUnk, typeof (__ComObject));
504                                 obj = proxy.GetTransparentProxy ();
505                         }
506                         return obj;
507 #else
508                         throw new NotImplementedException ();
509 #endif
510                 }
511
512                 public static object GetObjectForNativeVariant (IntPtr pSrcNativeVariant)
513                 {
514                         Variant vt = (Variant)Marshal.PtrToStructure(pSrcNativeVariant, typeof(Variant));
515                         return vt.GetValue();
516                 }
517
518                 public static T GetObjectForNativeVariant<T> (IntPtr pSrcNativeVariant) {
519                         Variant vt = (Variant)Marshal.PtrToStructure(pSrcNativeVariant, typeof(Variant));
520                         return (T)vt.GetValue();
521                 }
522
523                 public static object[] GetObjectsForNativeVariants (IntPtr aSrcNativeVariant, int cVars)
524                 {
525                         if (cVars < 0)
526                                 throw new ArgumentOutOfRangeException ("cVars", "cVars cannot be a negative number.");
527                         object[] objects = new object[cVars];
528                         for (int i = 0; i < cVars; i++)
529                                 objects[i] = GetObjectForNativeVariant ((IntPtr)(aSrcNativeVariant.ToInt64 () +
530                                         i * SizeOf (typeof(Variant))));
531                         return objects;
532                 }
533
534                 public static T[] GetObjectsForNativeVariants<T> (IntPtr aSrcNativeVariant, int cVars) {
535                         if (cVars < 0)
536                                 throw new ArgumentOutOfRangeException ("cVars", "cVars cannot be a negative number.");
537                         T[] objects = new T[cVars];
538                         for (int i = 0; i < cVars; i++)
539                                 objects[i] = GetObjectForNativeVariant<T> ((IntPtr)(aSrcNativeVariant.ToInt64 () +
540                                         i * SizeOf (typeof(Variant))));
541                         return objects;
542                 }
543
544                 [MonoTODO]
545                 public static int GetStartComSlot (Type t)
546                 {
547                         throw new NotImplementedException ();
548                 }
549
550                 [MonoTODO]
551                 [Obsolete ("This method has been deprecated")]
552                 public static Thread GetThreadFromFiberCookie (int cookie)
553                 {
554                         throw new NotImplementedException ();
555                 }
556
557                 public static object GetTypedObjectForIUnknown (IntPtr pUnk, Type t)
558                 {
559                         ComInteropProxy proxy = new ComInteropProxy (pUnk, t);
560                         __ComObject co = (__ComObject)proxy.GetTransparentProxy ();
561                         foreach (Type itf in t.GetInterfaces ()) {
562                                 if ((itf.Attributes & TypeAttributes.Import) == TypeAttributes.Import) {
563                                         if (co.GetInterface (itf) == IntPtr.Zero)
564                                                 return null;
565                                 }
566                         }
567                         return co;
568                 }
569
570                 [MonoTODO]
571                 public static Type GetTypeForITypeInfo (IntPtr piTypeInfo)
572                 {
573                         throw new NotImplementedException ();
574                 }
575
576                 public static Type GetTypeFromCLSID (Guid clsid)
577                 {
578                         throw new NotImplementedException ();                   
579                 }
580
581 #if !FULL_AOT_RUNTIME
582                 [Obsolete]
583                 [MonoTODO]
584                 public static string GetTypeInfoName (UCOMITypeInfo pTI)
585                 {
586                         throw new NotImplementedException ();
587                 }
588
589                 public static string GetTypeInfoName (ITypeInfo typeInfo)
590                 {
591                         throw new NotImplementedException ();
592                 }
593
594                 [Obsolete]
595                 [MonoTODO]
596                 public static Guid GetTypeLibGuid (UCOMITypeLib pTLB)
597                 {
598                         throw new NotImplementedException ();
599                 }
600
601                 [MonoTODO]
602                 public static Guid GetTypeLibGuid (ITypeLib typelib)
603                 {
604                         throw new NotImplementedException ();
605                 }
606
607                 [MonoTODO]
608                 public static Guid GetTypeLibGuidForAssembly (Assembly asm)
609                 {
610                         throw new NotImplementedException ();
611                 }
612
613                 [Obsolete]
614                 [MonoTODO]
615                 public static int GetTypeLibLcid (UCOMITypeLib pTLB)
616                 {
617                         throw new NotImplementedException ();
618                 }
619
620                 [MonoTODO]
621                 public static int GetTypeLibLcid (ITypeLib typelib)
622                 {
623                         throw new NotImplementedException ();
624                 }
625
626                 [Obsolete]
627                 [MonoTODO]
628                 public static string GetTypeLibName (UCOMITypeLib pTLB)
629                 {
630                         throw new NotImplementedException ();
631                 }
632
633                 [MonoTODO]
634                 public static string GetTypeLibName (ITypeLib typelib)
635                 {
636                         throw new NotImplementedException ();
637                 }
638
639                 [MonoTODO]
640                 public static void GetTypeLibVersionForAssembly (Assembly inputAssembly, out int majorVersion, out int minorVersion)
641                 {
642                         throw new NotImplementedException ();
643                 }
644
645                 public static object GetUniqueObjectForIUnknown (IntPtr unknown)
646                 {
647                         throw new NotImplementedException ();
648                 }
649 #endif
650
651                 [MonoTODO]
652                 [Obsolete ("This method has been deprecated")]
653                 public static IntPtr GetUnmanagedThunkForManagedMethodPtr (IntPtr pfnMethodToWrap, IntPtr pbSignature, int cbSignature)
654                 {
655                         throw new NotImplementedException ();
656                 }
657
658 #if !MOBILE
659                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
660                 public extern static bool IsComObject (object o);
661 #else
662                 public static bool IsComObject (object o)
663                 {
664                         throw new NotImplementedException ();
665                 }
666 #endif          
667
668                 [MonoTODO]
669                 public static bool IsTypeVisibleFromCom (Type t)
670                 {
671                         throw new NotImplementedException ();
672                 }
673
674                 [MonoTODO]
675                 public static int NumParamBytes (MethodInfo m)
676                 {
677                         throw new NotImplementedException ();
678                 }
679 #endif
680
681                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
682                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
683                 public static extern int GetLastWin32Error();
684
685                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
686                 public extern static IntPtr OffsetOf (Type t, string fieldName);
687
688                 public static IntPtr OffsetOf<T> (string fieldName) {
689                         return OffsetOf (typeof (T), fieldName);
690                 }
691
692                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
693                 public extern static void Prelink (MethodInfo m);
694
695                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
696                 public extern static void PrelinkAll (Type c);
697
698                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
699                 public extern static string PtrToStringAnsi (IntPtr ptr);
700                 
701                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
702                 public extern static string PtrToStringAnsi (IntPtr ptr, int len);
703
704                 public static string PtrToStringAuto (IntPtr ptr)
705                 {
706                         return SystemDefaultCharSize == 2
707                                 ? PtrToStringUni (ptr) : PtrToStringAnsi (ptr);
708                 }
709                 
710                 public static string PtrToStringAuto (IntPtr ptr, int len)
711                 {
712                         return SystemDefaultCharSize == 2
713                                 ? PtrToStringUni (ptr, len) : PtrToStringAnsi (ptr, len);
714                 }
715
716                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
717                 public extern static string PtrToStringUni (IntPtr ptr);
718
719                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
720                 public extern static string PtrToStringUni (IntPtr ptr, int len);
721
722 #if !MOBILE
723                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
724                 public extern static string PtrToStringBSTR (IntPtr ptr);
725 #else
726                 public static string PtrToStringBSTR (IntPtr ptr)
727                 {
728                         throw new NotImplementedException ();
729                 }
730 #endif
731                 
732                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
733                 [ComVisible (true)]
734                 public extern static void PtrToStructure (IntPtr ptr, object structure);
735
736                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
737                 [ComVisible (true)]
738                 public extern static object PtrToStructure (IntPtr ptr, Type structureType);
739
740                 public static void PtrToStructure<T> (IntPtr ptr, T structure) {
741                         PtrToStructure (ptr, (object)structure);
742                 }
743
744                 public static T PtrToStructure<T> (IntPtr ptr) {
745                         return (T) PtrToStructure (ptr, typeof (T));
746                 }
747
748 #if !MOBILE
749                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
750                 private extern static int QueryInterfaceInternal (IntPtr pUnk, ref Guid iid, out IntPtr ppv);
751 #endif
752
753                 public static int QueryInterface (IntPtr pUnk, ref Guid iid, out IntPtr ppv)
754                 {
755 #if !MOBILE
756                         if (pUnk == IntPtr.Zero)
757                                 throw new ArgumentException ("Value cannot be null.", "pUnk");
758                         return QueryInterfaceInternal (pUnk, ref iid, out ppv);
759 #else
760                         throw new NotImplementedException ();
761 #endif
762                 }
763
764                 public static byte ReadByte (IntPtr ptr)
765                 {
766                         unsafe {
767                                 return *(byte*)ptr;
768                         }
769                 }
770
771                 public static byte ReadByte (IntPtr ptr, int ofs) {
772                         unsafe {
773                                 return *((byte*)ptr + ofs);
774                         }
775                 }
776
777                 [MonoTODO]
778                 [SuppressUnmanagedCodeSecurity]
779                 public static byte ReadByte ([In, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs)
780                 {
781                         throw new NotImplementedException ();
782                 }
783
784                 public unsafe static short ReadInt16 (IntPtr ptr)
785                 {
786                         byte *addr = (byte *) ptr;
787                         
788                         // The mono JIT can't inline this due to the hight number of calls
789                         // return ReadInt16 (ptr, 0);
790                         
791                         if (((uint)addr & 1) == 0) 
792                                 return *(short*)addr;
793
794                         short s;
795                         Buffer.Memcpy ((byte*)&s, (byte*)ptr, 2);
796                         return s;
797                 }
798
799                 public unsafe static short ReadInt16 (IntPtr ptr, int ofs)
800                 {
801                         byte *addr = ((byte *) ptr) + ofs;
802
803                         if (((uint) addr & 1) == 0)
804                                 return *(short*)addr;
805
806                         short s;
807                         Buffer.Memcpy ((byte*)&s, addr, 2);
808                         return s;
809                 }
810
811                 [MonoTODO]
812                 [SuppressUnmanagedCodeSecurity]
813                 public static short ReadInt16 ([In, MarshalAs(UnmanagedType.AsAny)] object ptr, int ofs)
814                 {
815                         throw new NotImplementedException ();
816                 }
817
818                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
819                 public unsafe static int ReadInt32 (IntPtr ptr)
820                 {
821                         byte *addr = (byte *) ptr;
822                         
823                         if (((uint)addr & 3) == 0) 
824                                 return *(int*)addr;
825
826                         int s;
827                         Buffer.Memcpy ((byte*)&s, addr, 4);
828                         return s;
829                 }
830
831                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
832                 public unsafe static int ReadInt32 (IntPtr ptr, int ofs)
833                 {
834                         byte *addr = ((byte *) ptr) + ofs;
835                         
836                         if ((((int) addr) & 3) == 0)
837                                 return *(int*)addr;
838                         else {
839                                 int s;
840                                 Buffer.Memcpy ((byte*)&s, addr, 4);
841                                 return s;
842                         }
843                 }
844
845                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
846                 [MonoTODO]
847                 [SuppressUnmanagedCodeSecurity]
848                 public static int ReadInt32 ([In, MarshalAs(UnmanagedType.AsAny)] object ptr, int ofs)
849                 {
850                         throw new NotImplementedException ();
851                 }
852
853                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
854                 public unsafe static long ReadInt64 (IntPtr ptr)
855                 {
856                         byte *addr = (byte *) ptr;
857                                 
858                         // The real alignment might be 4 on some platforms, but this is just an optimization,
859                         // so it doesn't matter.
860                         if (((uint) addr & 7) == 0)
861                                 return *(long*)ptr;
862
863                         long s;
864                         Buffer.Memcpy ((byte*)&s, addr, 8);
865                         return s;
866                 }
867
868                 public unsafe static long ReadInt64 (IntPtr ptr, int ofs)
869                 {
870                         byte *addr = ((byte *) ptr) + ofs;
871
872                         if (((uint) addr & 7) == 0)
873                                 return *(long*)addr;
874                         
875                         long s;
876                         Buffer.Memcpy ((byte*)&s, addr, 8);
877                         return s;
878                 }
879
880                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
881                 [MonoTODO]
882                 [SuppressUnmanagedCodeSecurity]
883                 public static long ReadInt64 ([In, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs)
884                 {
885                         throw new NotImplementedException ();
886                 }
887
888                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
889                 public static IntPtr ReadIntPtr (IntPtr ptr)
890                 {
891                         if (IntPtr.Size == 4)
892                                 return (IntPtr)ReadInt32 (ptr);
893                         else
894                                 return (IntPtr)ReadInt64 (ptr);
895                 }
896                 
897                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
898                 public static IntPtr ReadIntPtr (IntPtr ptr, int ofs)
899                 {
900                         if (IntPtr.Size == 4)
901                                 return (IntPtr)ReadInt32 (ptr, ofs);
902                         else
903                                 return (IntPtr)ReadInt64 (ptr, ofs);
904                 }
905
906                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
907                 [MonoTODO]
908                 public static IntPtr ReadIntPtr ([In, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs)
909                 {
910                         throw new NotImplementedException ();
911                 }
912
913                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
914                 public extern static IntPtr ReAllocCoTaskMem (IntPtr pv, int cb);
915
916                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
917                 public extern static IntPtr ReAllocHGlobal (IntPtr pv, IntPtr cb);
918
919 #if !MOBILE
920                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
921                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
922                 private extern static int ReleaseInternal (IntPtr pUnk);
923 #endif
924
925                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
926                 public static int Release (IntPtr pUnk)
927                 {
928 #if !MOBILE
929                         if (pUnk == IntPtr.Zero)
930                                 throw new ArgumentException ("Value cannot be null.", "pUnk");
931
932                         return ReleaseInternal (pUnk);
933 #else
934                         throw new NotImplementedException ();
935 #endif
936                 }
937
938 #if !FULL_AOT_RUNTIME
939                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
940                 private extern static int ReleaseComObjectInternal (object co);
941
942                 public static int ReleaseComObject (object o)
943                 {
944                         if (o == null)
945                                 throw new ArgumentException ("Value cannot be null.", "o");
946                         if (!IsComObject (o))
947                                 throw new ArgumentException ("Value must be a Com object.", "o");
948                         return ReleaseComObjectInternal (o);
949                 }
950
951                 [Obsolete]
952                 [MonoTODO]
953                 public static void ReleaseThreadCache()
954                 {
955                         throw new NotImplementedException ();
956                 }
957
958                 [MonoNotSupportedAttribute ("MSDN states user code should never need to call this method.")]
959                 public static bool SetComObjectData (object obj, object key, object data)
960                 {
961                         throw new NotSupportedException ("MSDN states user code should never need to call this method.");
962                 }
963 #endif
964
965                 [ComVisible (true)]
966                 public static int SizeOf (object structure)
967                 {
968                         return SizeOf (structure.GetType ());
969                 }
970
971                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
972                 public extern static int SizeOf (Type t);
973
974                 public static int SizeOf<T> () {
975                         return SizeOf (typeof (T));
976                 }
977
978                 public static int SizeOf<T> (T structure) {
979                         return SizeOf (structure.GetType ());
980                 }
981
982                 internal static uint SizeOfType (Type type)
983                 {
984                         return (uint) SizeOf (type);
985                 }
986
987                 internal static uint AlignedSizeOf<T> () where T : struct
988                 {
989                         uint size = SizeOfType (typeof (T));
990                         if (size == 1 || size == 2)
991                                 return size;
992                         if (IntPtr.Size == 8 && size == 4)
993                                 return size;
994                         return (size + 3) & (~((uint)3));
995                 }
996
997                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
998                 public extern static IntPtr StringToBSTR (string s);
999
1000                 //
1001                 // I believe this is wrong, because in Mono and in P/Invoke
1002                 // we treat "Ansi" conversions as UTF-8 conversions, while
1003                 // this one does not do this
1004                 //
1005                 public static IntPtr StringToCoTaskMemAnsi (string s)
1006                 {
1007                         int length = s.Length + 1;
1008                         IntPtr ctm = AllocCoTaskMem (length);
1009
1010                         byte[] asBytes = new byte[length];
1011                         for (int i = 0; i < s.Length; i++)
1012                                 asBytes[i] = (byte)s[i];
1013                         asBytes[s.Length] = 0;
1014
1015                         copy_to_unmanaged (asBytes, 0, ctm, length);
1016                         return ctm;
1017                 }
1018
1019                 public static IntPtr StringToCoTaskMemAuto (string s)
1020                 {
1021                         return SystemDefaultCharSize == 2
1022                                 ? StringToCoTaskMemUni (s) : StringToCoTaskMemAnsi (s);
1023                 }
1024
1025                 public static IntPtr StringToCoTaskMemUni (string s)
1026                 {
1027                         int length = s.Length + 1;
1028                         IntPtr ctm = AllocCoTaskMem (length * 2);
1029                         
1030                         char[] asChars = new char[length];
1031                         s.CopyTo (0, asChars, 0, s.Length);
1032                         asChars[s.Length] = '\0';
1033
1034                         copy_to_unmanaged (asChars, 0, ctm, length);
1035                         return ctm;
1036                 }
1037
1038                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1039                 public extern static IntPtr StringToHGlobalAnsi (string s);
1040
1041                 public static IntPtr StringToHGlobalAuto (string s)
1042                 {
1043                         return SystemDefaultCharSize == 2
1044                                 ? StringToHGlobalUni (s) : StringToHGlobalAnsi (s);
1045                 }
1046
1047                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1048                 public extern static IntPtr StringToHGlobalUni (string s);
1049
1050                 public static IntPtr SecureStringToBSTR (SecureString s)
1051                 {
1052                         if (s == null)
1053                                 throw new ArgumentNullException ("s");
1054
1055                         byte[] buffer = s.GetBuffer ();
1056                         int len = s.Length;
1057                         
1058                         // SecureString doesn't take endian-ness into account. 
1059                         // Therefore swap bytes here before we send it to c-side if little-endian.
1060                         if (BitConverter.IsLittleEndian) {
1061                                 for (int i = 0; i < buffer.Length; i += 2) {
1062                                         byte b = buffer[i];
1063                                         buffer[i] = buffer[i + 1];
1064                                         buffer[i + 1] = b;
1065                                 }
1066                         }
1067                         return BufferToBSTR (buffer, len);
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                 public static void StructureToPtr<T> (T structure, IntPtr ptr, bool fDeleteOld) {
1140                         StructureToPtr ((object)structure, ptr, fDeleteOld);
1141                 }
1142
1143                 public static void ThrowExceptionForHR (int errorCode) {
1144                         Exception ex = GetExceptionForHR (errorCode);
1145                         if (ex != null)
1146                                 throw ex;
1147                 }
1148
1149                 public static void ThrowExceptionForHR (int errorCode, IntPtr errorInfo) {
1150                         Exception ex = GetExceptionForHR (errorCode, errorInfo);
1151                         if (ex != null)
1152                                 throw ex;
1153                 }
1154
1155
1156                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1157                 public extern static IntPtr BufferToBSTR (Array ptr, int slen);
1158
1159                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1160                 public extern static IntPtr UnsafeAddrOfPinnedArrayElement (Array arr, int index);
1161
1162                 public static IntPtr UnsafeAddrOfPinnedArrayElement<T> (T[] arr, int index) {
1163                         return UnsafeAddrOfPinnedArrayElement ((Array)arr, index);
1164                 }
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                                 Buffer.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                                 Buffer.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                                 Buffer.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                                 Buffer.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                                 Buffer.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                                 Buffer.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 #if FEATURE_COMINTEROP
1526                 [DllImport ("oleaut32.dll", CharSet=CharSet.Unicode, EntryPoint = "SetErrorInfo")]
1527                 static extern int _SetErrorInfo (int dwReserved,
1528                         [MarshalAs(UnmanagedType.Interface)] IErrorInfo pIErrorInfo);
1529
1530                 [DllImport ("oleaut32.dll", CharSet=CharSet.Unicode, EntryPoint = "GetErrorInfo")]
1531                 static extern int _GetErrorInfo (int dwReserved,
1532                         [MarshalAs(UnmanagedType.Interface)] out IErrorInfo ppIErrorInfo);
1533
1534                 static bool SetErrorInfoNotAvailable;
1535                 static bool GetErrorInfoNotAvailable;
1536
1537                 internal static int SetErrorInfo (int dwReserved, IErrorInfo errorInfo)
1538                 {
1539                         int retVal = 0;
1540                         errorInfo = null;
1541
1542                         if (SetErrorInfoNotAvailable)
1543                                 return -1;
1544
1545                         try {
1546                                 retVal = _SetErrorInfo (dwReserved, errorInfo);
1547                         }
1548                         catch (Exception) {
1549                                 // ignore any exception - probably there's no suitable SetErrorInfo
1550                                 // method available.
1551                                 SetErrorInfoNotAvailable = true;
1552                         }
1553                         return retVal;
1554                 }
1555
1556                 internal static int GetErrorInfo (int dwReserved, out IErrorInfo errorInfo)
1557                 {
1558                         int retVal = 0;
1559                         errorInfo = null;
1560
1561                         if (GetErrorInfoNotAvailable)
1562                                 return -1;
1563
1564                         try {
1565                                 retVal = _GetErrorInfo (dwReserved, out errorInfo);
1566                         }
1567                         catch (Exception) {
1568                                 // ignore any exception - probably there's no suitable GetErrorInfo
1569                                 // method available.
1570                                 GetErrorInfoNotAvailable = true;
1571                         }
1572                         return retVal;
1573                 }
1574 #endif
1575                 public static Exception GetExceptionForHR (int errorCode)
1576                 {
1577                         return GetExceptionForHR (errorCode, IntPtr.Zero);
1578                 }
1579
1580                 public static Exception GetExceptionForHR (int errorCode, IntPtr errorInfo)
1581                 {
1582 #if FEATURE_COMINTEROP
1583                         IErrorInfo info = null;
1584                         if (errorInfo != (IntPtr)(-1)) {
1585                                 if (errorInfo == IntPtr.Zero) {
1586                                         if (GetErrorInfo (0, out info) != 0) {
1587                                                 info  = null;
1588                                         }
1589                                 } else {
1590                                         info  = Marshal.GetObjectForIUnknown (errorInfo) as IErrorInfo;
1591                                 }
1592                         }
1593
1594                         if (info is ManagedErrorInfo && ((ManagedErrorInfo) info).Exception._HResult == errorCode) {
1595                                 return ((ManagedErrorInfo) info).Exception;
1596                         }
1597
1598                         Exception e = ConvertHrToException (errorCode);
1599                         if (info != null && e != null) {
1600                                 uint helpContext;
1601                                 info.GetHelpContext (out helpContext);
1602                                 string str;
1603                                 info.GetSource (out str);
1604                                 e.Source = str;
1605                                 info.GetDescription (out str);
1606                                 e.SetMessage (str);
1607                                 info.GetHelpFile (out str);
1608
1609                                 if (helpContext == 0) {
1610                                         e.HelpLink = str;
1611                                 } else {
1612                                         e.HelpLink = string.Format ("{0}#{1}", str, helpContext);
1613                                 }
1614                         }
1615                         return e;
1616 #else
1617                         return ConvertHrToException (errorCode);
1618 #endif
1619                 }
1620
1621 #if !FULL_AOT_RUNTIME
1622                 public static int FinalReleaseComObject (object o)
1623                 {
1624                         while (ReleaseComObject (o) != 0);
1625                         return 0;
1626                 }
1627 #endif
1628
1629                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1630                 private static extern Delegate GetDelegateForFunctionPointerInternal (IntPtr ptr, Type t);
1631
1632                 public static Delegate GetDelegateForFunctionPointer (IntPtr ptr, Type t)
1633                 {
1634                         if (t == null)
1635                                 throw new ArgumentNullException ("t");
1636                         if (!t.IsSubclassOf (typeof (MulticastDelegate)) || (t == typeof (MulticastDelegate)))
1637                                 throw new ArgumentException ("Type is not a delegate", "t");
1638                         if (t.IsGenericType)
1639                                 throw new ArgumentException ("The specified Type must not be a generic type definition.");
1640                         if (ptr == IntPtr.Zero)
1641                                 throw new ArgumentNullException ("ptr");
1642
1643                         return GetDelegateForFunctionPointerInternal (ptr, t);
1644                 }
1645
1646                 public static TDelegate GetDelegateForFunctionPointer<TDelegate> (IntPtr ptr) {
1647                         return (TDelegate) (object) GetDelegateForFunctionPointer (ptr, typeof (TDelegate));
1648                 }
1649
1650                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1651                 private static extern IntPtr GetFunctionPointerForDelegateInternal (Delegate d);
1652                 
1653                 public static IntPtr GetFunctionPointerForDelegate (Delegate d)
1654                 {
1655                         if (d == null)
1656                                 throw new ArgumentNullException ("d");
1657                         
1658                         return GetFunctionPointerForDelegateInternal (d);
1659                 }
1660
1661                 public static IntPtr GetFunctionPointerForDelegate<TDelegate> (TDelegate d) {
1662                         if (d == null)
1663                                 throw new ArgumentNullException ("d");
1664                         
1665                         return GetFunctionPointerForDelegateInternal ((Delegate)(object)d);
1666                 }
1667
1668                 internal static void SetLastWin32Error (int error)
1669                 {
1670                 }
1671         }
1672 }