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