Merge pull request #2408 from tastywheattasteslikechicken/MoreInterfaceSupport
[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 #if !MOBILE
793                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
794                 public extern static string PtrToStringBSTR (IntPtr ptr);
795 #else
796                 public static string PtrToStringBSTR (IntPtr ptr)
797                 {
798                         throw new NotImplementedException ();
799                 }
800 #endif
801                 
802                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
803                 [ComVisible (true)]
804                 public extern static void PtrToStructure (IntPtr ptr, object structure);
805
806                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
807                 [ComVisible (true)]
808                 public extern static object PtrToStructure (IntPtr ptr, Type structureType);
809
810                 public static void PtrToStructure<T> (IntPtr ptr, T structure) {
811                         PtrToStructure (ptr, (object)structure);
812                 }
813
814                 public static T PtrToStructure<T> (IntPtr ptr) {
815                         return (T) PtrToStructure (ptr, typeof (T));
816                 }
817
818 #if !MOBILE
819                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
820                 private extern static int QueryInterfaceInternal (IntPtr pUnk, ref Guid iid, out IntPtr ppv);
821 #endif
822
823                 public static int QueryInterface (IntPtr pUnk, ref Guid iid, out IntPtr ppv)
824                 {
825 #if !MOBILE
826                         if (pUnk == IntPtr.Zero)
827                                 throw new ArgumentException ("Value cannot be null.", "pUnk");
828                         return QueryInterfaceInternal (pUnk, ref iid, out ppv);
829 #else
830                         throw new NotImplementedException ();
831 #endif
832                 }
833
834                 public static byte ReadByte (IntPtr ptr)
835                 {
836                         unsafe {
837                                 return *(byte*)ptr;
838                         }
839                 }
840
841                 public static byte ReadByte (IntPtr ptr, int ofs) {
842                         unsafe {
843                                 return *((byte*)ptr + ofs);
844                         }
845                 }
846
847                 [MonoTODO]
848                 [SuppressUnmanagedCodeSecurity]
849                 public static byte ReadByte ([In, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs)
850                 {
851                         throw new NotImplementedException ();
852                 }
853
854                 public unsafe static short ReadInt16 (IntPtr ptr)
855                 {
856                         byte *addr = (byte *) ptr;
857                         
858                         // The mono JIT can't inline this due to the hight number of calls
859                         // return ReadInt16 (ptr, 0);
860                         
861                         if (((uint)addr & 1) == 0) 
862                                 return *(short*)addr;
863
864                         short s;
865                         Buffer.Memcpy ((byte*)&s, (byte*)ptr, 2);
866                         return s;
867                 }
868
869                 public unsafe static short ReadInt16 (IntPtr ptr, int ofs)
870                 {
871                         byte *addr = ((byte *) ptr) + ofs;
872
873                         if (((uint) addr & 1) == 0)
874                                 return *(short*)addr;
875
876                         short s;
877                         Buffer.Memcpy ((byte*)&s, addr, 2);
878                         return s;
879                 }
880
881                 [MonoTODO]
882                 [SuppressUnmanagedCodeSecurity]
883                 public static short ReadInt16 ([In, MarshalAs(UnmanagedType.AsAny)] object ptr, int ofs)
884                 {
885                         throw new NotImplementedException ();
886                 }
887
888                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
889                 public unsafe static int ReadInt32 (IntPtr ptr)
890                 {
891                         byte *addr = (byte *) ptr;
892                         
893                         if (((uint)addr & 3) == 0) 
894                                 return *(int*)addr;
895
896                         int s;
897                         Buffer.Memcpy ((byte*)&s, addr, 4);
898                         return s;
899                 }
900
901                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
902                 public unsafe static int ReadInt32 (IntPtr ptr, int ofs)
903                 {
904                         byte *addr = ((byte *) ptr) + ofs;
905                         
906                         if ((((int) addr) & 3) == 0)
907                                 return *(int*)addr;
908                         else {
909                                 int s;
910                                 Buffer.Memcpy ((byte*)&s, addr, 4);
911                                 return s;
912                         }
913                 }
914
915                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
916                 [MonoTODO]
917                 [SuppressUnmanagedCodeSecurity]
918                 public static int ReadInt32 ([In, MarshalAs(UnmanagedType.AsAny)] object ptr, int ofs)
919                 {
920                         throw new NotImplementedException ();
921                 }
922
923                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
924                 public unsafe static long ReadInt64 (IntPtr ptr)
925                 {
926                         byte *addr = (byte *) ptr;
927                                 
928                         // The real alignment might be 4 on some platforms, but this is just an optimization,
929                         // so it doesn't matter.
930                         if (((uint) addr & 7) == 0)
931                                 return *(long*)ptr;
932
933                         long s;
934                         Buffer.Memcpy ((byte*)&s, addr, 8);
935                         return s;
936                 }
937
938                 public unsafe static long ReadInt64 (IntPtr ptr, int ofs)
939                 {
940                         byte *addr = ((byte *) ptr) + ofs;
941
942                         if (((uint) addr & 7) == 0)
943                                 return *(long*)addr;
944                         
945                         long s;
946                         Buffer.Memcpy ((byte*)&s, addr, 8);
947                         return s;
948                 }
949
950                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
951                 [MonoTODO]
952                 [SuppressUnmanagedCodeSecurity]
953                 public static long ReadInt64 ([In, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs)
954                 {
955                         throw new NotImplementedException ();
956                 }
957
958                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
959                 public static IntPtr ReadIntPtr (IntPtr ptr)
960                 {
961                         if (IntPtr.Size == 4)
962                                 return (IntPtr)ReadInt32 (ptr);
963                         else
964                                 return (IntPtr)ReadInt64 (ptr);
965                 }
966                 
967                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
968                 public static IntPtr ReadIntPtr (IntPtr ptr, int ofs)
969                 {
970                         if (IntPtr.Size == 4)
971                                 return (IntPtr)ReadInt32 (ptr, ofs);
972                         else
973                                 return (IntPtr)ReadInt64 (ptr, ofs);
974                 }
975
976                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
977                 [MonoTODO]
978                 public static IntPtr ReadIntPtr ([In, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs)
979                 {
980                         throw new NotImplementedException ();
981                 }
982
983                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
984                 public extern static IntPtr ReAllocCoTaskMem (IntPtr pv, int cb);
985
986                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
987                 public extern static IntPtr ReAllocHGlobal (IntPtr pv, IntPtr cb);
988
989 #if !MOBILE
990                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
991                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
992                 private extern static int ReleaseInternal (IntPtr pUnk);
993 #endif
994
995                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
996                 public static int Release (IntPtr pUnk)
997                 {
998 #if !MOBILE
999                         if (pUnk == IntPtr.Zero)
1000                                 throw new ArgumentException ("Value cannot be null.", "pUnk");
1001
1002                         return ReleaseInternal (pUnk);
1003 #else
1004                         throw new NotImplementedException ();
1005 #endif
1006                 }
1007
1008 #if !FULL_AOT_RUNTIME
1009                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
1010                 private extern static int ReleaseComObjectInternal (object co);
1011 #endif
1012
1013                 public static int ReleaseComObject (object o)
1014                 {
1015 #if FULL_AOT_RUNTIME
1016                         throw new PlatformNotSupportedException ();
1017 #else
1018                         if (o == null)
1019                                 throw new ArgumentException ("Value cannot be null.", "o");
1020                         if (!IsComObject (o))
1021                                 throw new ArgumentException ("Value must be a Com object.", "o");
1022                         return ReleaseComObjectInternal (o);
1023 #endif
1024                 }
1025
1026 #if !FULL_AOT_RUNTIME
1027                 [Obsolete]
1028                 [MonoTODO]
1029                 public static void ReleaseThreadCache()
1030                 {
1031                         throw new NotImplementedException ();
1032                 }
1033
1034                 [MonoNotSupportedAttribute ("MSDN states user code should never need to call this method.")]
1035                 public static bool SetComObjectData (object obj, object key, object data)
1036                 {
1037                         throw new NotSupportedException ("MSDN states user code should never need to call this method.");
1038                 }
1039 #endif
1040
1041                 [ComVisible (true)]
1042                 public static int SizeOf (object structure)
1043                 {
1044                         return SizeOf (structure.GetType ());
1045                 }
1046
1047                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1048                 public extern static int SizeOf (Type t);
1049
1050                 public static int SizeOf<T> () {
1051                         return SizeOf (typeof (T));
1052                 }
1053
1054                 public static int SizeOf<T> (T structure) {
1055                         return SizeOf (structure.GetType ());
1056                 }
1057
1058                 internal static uint SizeOfType (Type type)
1059                 {
1060                         return (uint) SizeOf (type);
1061                 }
1062
1063                 internal static uint AlignedSizeOf<T> () where T : struct
1064                 {
1065                         uint size = SizeOfType (typeof (T));
1066                         if (size == 1 || size == 2)
1067                                 return size;
1068                         if (IntPtr.Size == 8 && size == 4)
1069                                 return size;
1070                         return (size + 3) & (~((uint)3));
1071                 }
1072
1073                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1074                 public extern static IntPtr StringToBSTR (string s);
1075
1076                 public static IntPtr StringToCoTaskMemAnsi (string s)
1077                 {
1078                         return StringToAllocatedMemoryUTF8 (s);
1079                 }
1080
1081                 public static IntPtr StringToCoTaskMemAuto (string s)
1082                 {
1083                         return SystemDefaultCharSize == 2
1084                                 ? StringToCoTaskMemUni (s) : StringToCoTaskMemAnsi (s);
1085                 }
1086
1087                 public static IntPtr StringToCoTaskMemUni (string s)
1088                 {
1089                         int length = s.Length + 1;
1090                         IntPtr ctm = AllocCoTaskMem (length * 2);
1091                         
1092                         char[] asChars = new char[length];
1093                         s.CopyTo (0, asChars, 0, s.Length);
1094                         asChars[s.Length] = '\0';
1095
1096                         copy_to_unmanaged (asChars, 0, ctm, length);
1097                         return ctm;
1098                 }
1099
1100                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1101                 public extern static IntPtr StringToHGlobalAnsi (string s);
1102
1103                 unsafe public static IntPtr StringToAllocatedMemoryUTF8(String s)
1104                 {
1105                         const int MAX_UTF8_CHAR_SIZE = 3;
1106                         if (s == null)
1107                                 return IntPtr.Zero;
1108
1109                         int nb = (s.Length + 1) * MAX_UTF8_CHAR_SIZE;
1110
1111                         // Overflow checking
1112                         if (nb < s.Length)
1113                                 throw new ArgumentOutOfRangeException("s");
1114                         
1115                         IntPtr pMem = AllocCoTaskMemSize(new UIntPtr((uint)nb +1));
1116                         
1117                         if (pMem == IntPtr.Zero)
1118                                 throw new OutOfMemoryException();
1119
1120                         byte* pbMem = (byte*)pMem;
1121                         int nbWritten = s.GetBytesFromEncoding(pbMem, nb, Encoding.UTF8);
1122                         pbMem[nbWritten] = 0;
1123                         return pMem;
1124                 }
1125                 
1126                 public static IntPtr StringToHGlobalAuto (string s)
1127                 {
1128                         return SystemDefaultCharSize == 2
1129                                 ? StringToHGlobalUni (s) : StringToHGlobalAnsi (s);
1130                 }
1131
1132                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1133                 public extern static IntPtr StringToHGlobalUni (string s);
1134
1135                 public static IntPtr SecureStringToBSTR (SecureString s)
1136                 {
1137                         if (s == null)
1138                                 throw new ArgumentNullException ("s");
1139
1140                         byte[] buffer = s.GetBuffer ();
1141                         int len = s.Length;
1142                         
1143                         // SecureString doesn't take endian-ness into account. 
1144                         // Therefore swap bytes here before we send it to c-side if little-endian.
1145                         if (BitConverter.IsLittleEndian) {
1146                                 for (int i = 0; i < buffer.Length; i += 2) {
1147                                         byte b = buffer[i];
1148                                         buffer[i] = buffer[i + 1];
1149                                         buffer[i + 1] = b;
1150                                 }
1151                         }
1152                         return BufferToBSTR (buffer, len);
1153         }
1154
1155                 public static IntPtr SecureStringToCoTaskMemAnsi (SecureString s)
1156                 {
1157                         if (s == null)
1158                                 throw new ArgumentNullException ("s");
1159                         int len = s.Length;
1160                         IntPtr ctm = AllocCoTaskMem (len + 1);
1161                         byte [] copy = new byte [len+1];
1162
1163                         try {
1164                                 byte [] buffer = s.GetBuffer ();
1165                                 int i = 0, j = 0;
1166                                 for (; i < len; i++, j += 2){
1167                                         copy [i] = buffer [j+1];
1168                                         buffer [j] = 0;
1169                                         buffer [j+1] = 0;
1170                                 }
1171                                 copy [i] = 0;
1172                                 copy_to_unmanaged (copy, 0, ctm, len+1);
1173                         } finally {
1174                                 // Ensure that we clear the buffer.
1175                                 for (int i = len; i > 0; ){
1176                                         i--;
1177                                         copy [i] = 0;
1178                                 }
1179                         }
1180                         return ctm;
1181                 }
1182
1183                 public static IntPtr SecureStringToCoTaskMemUnicode (SecureString s)
1184                 {
1185                         if (s == null)
1186                                 throw new ArgumentNullException ("s");
1187                         int len = s.Length;
1188                         IntPtr ctm = AllocCoTaskMem (len * 2 + 2);
1189                         byte [] buffer = null;
1190                         try {
1191                                 buffer = s.GetBuffer ();
1192                                 for (int i = 0; i < len; i++)
1193                                         WriteInt16 (ctm, i * 2, (short) ((buffer [(i*2)] << 8) | (buffer [i*2+1])));
1194                                 WriteInt16 (ctm, buffer.Length, 0);
1195                         } finally {
1196                                 if (buffer != null)
1197                                         for (int i = buffer.Length; i > 0; ){
1198                                                 i--;
1199                                                 buffer [i] = 0;
1200                                         }
1201                         }
1202                         return ctm;
1203                 }
1204
1205                 public static IntPtr SecureStringToGlobalAllocAnsi (SecureString s)
1206                 {
1207                         if (s == null)
1208                                 throw new ArgumentNullException ("s");
1209                         return SecureStringToCoTaskMemAnsi (s);
1210                 }
1211
1212                 public static IntPtr SecureStringToGlobalAllocUnicode (SecureString s)
1213                 {
1214                         if (s == null)
1215                                 throw new ArgumentNullException ("s");
1216                         return SecureStringToCoTaskMemUnicode (s);
1217                 }
1218
1219                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
1220                 [ComVisible (true)]
1221                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1222                 public extern static void StructureToPtr (object structure, IntPtr ptr, bool fDeleteOld);
1223
1224                 public static void StructureToPtr<T> (T structure, IntPtr ptr, bool fDeleteOld) {
1225                         StructureToPtr ((object)structure, ptr, fDeleteOld);
1226                 }
1227
1228                 public static void ThrowExceptionForHR (int errorCode) {
1229                         Exception ex = GetExceptionForHR (errorCode);
1230                         if (ex != null)
1231                                 throw ex;
1232                 }
1233
1234                 public static void ThrowExceptionForHR (int errorCode, IntPtr errorInfo) {
1235                         Exception ex = GetExceptionForHR (errorCode, errorInfo);
1236                         if (ex != null)
1237                                 throw ex;
1238                 }
1239
1240
1241                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1242                 public extern static IntPtr BufferToBSTR (Array ptr, int slen);
1243
1244                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1245                 public extern static IntPtr UnsafeAddrOfPinnedArrayElement (Array arr, int index);
1246
1247                 public static IntPtr UnsafeAddrOfPinnedArrayElement<T> (T[] arr, int index) {
1248                         return UnsafeAddrOfPinnedArrayElement ((Array)arr, index);
1249                 }
1250
1251                 public static void WriteByte (IntPtr ptr, byte val)
1252                 {
1253                         unsafe {
1254                                 *(byte*)ptr = val;
1255                         }
1256                 }
1257
1258                 public static void WriteByte (IntPtr ptr, int ofs, byte val) {
1259                         unsafe {
1260                                 *(byte*)(IntPtr.Add (ptr, ofs)) = val;
1261                         }
1262                 }
1263
1264                 [MonoTODO]
1265                 [SuppressUnmanagedCodeSecurity]
1266                 public static void WriteByte ([In, Out, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs, byte val)
1267                 {
1268                         throw new NotImplementedException ();
1269                 }
1270
1271                 public static unsafe void WriteInt16 (IntPtr ptr, short val)
1272                 {
1273                         byte *addr = (byte *) ptr;
1274                         
1275                         if (((uint)addr & 1) == 0)
1276                                 *(short*)addr = val;
1277                         else
1278                                 Buffer.Memcpy (addr, (byte*)&val, 2);
1279                 }
1280
1281                 public static unsafe void WriteInt16 (IntPtr ptr, int ofs, short val)
1282                 {
1283                         byte *addr = ((byte *) ptr) + ofs;
1284
1285                         if (((uint)addr & 1) == 0)
1286                                 *(short*)addr = val;
1287                         else {
1288                                 Buffer.Memcpy (addr, (byte*)&val, 2);
1289                         }
1290                 }
1291
1292                 [MonoTODO]
1293                 [SuppressUnmanagedCodeSecurity]
1294                 public static void WriteInt16 ([In, Out, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs, short val)
1295                 {
1296                         throw new NotImplementedException ();
1297                 }
1298
1299                 public static void WriteInt16 (IntPtr ptr, char val)
1300                 {
1301                         WriteInt16 (ptr, 0, (short)val);
1302                 }
1303
1304                 public static void WriteInt16 (IntPtr ptr, int ofs, char val)
1305                 {
1306                         WriteInt16 (ptr, ofs, (short)val);
1307                 }
1308
1309                 [MonoTODO]
1310                 public static void WriteInt16([In, Out] object ptr, int ofs, char val)
1311                 {
1312                         throw new NotImplementedException ();
1313                 }
1314
1315                 public static unsafe void WriteInt32 (IntPtr ptr, int val)
1316                 {
1317                         byte *addr = (byte *) ptr;
1318                         
1319                         if (((uint)addr & 3) == 0) 
1320                                 *(int*)addr = val;
1321                         else {
1322                                 Buffer.Memcpy (addr, (byte*)&val, 4);
1323                         }
1324                 }
1325
1326                 public unsafe static void WriteInt32 (IntPtr ptr, int ofs, int val)
1327                 {
1328                         byte *addr = ((byte *) ptr) + ofs;
1329
1330                         if (((uint)addr & 3) == 0) 
1331                                 *(int*)addr = val;
1332                         else {
1333                                 Buffer.Memcpy (addr, (byte*)&val, 4);
1334                         }
1335                 }
1336
1337                 [MonoTODO]
1338                 [SuppressUnmanagedCodeSecurity]
1339                 public static void WriteInt32([In, Out, MarshalAs(UnmanagedType.AsAny)] object ptr, int ofs, int val)
1340                 {
1341                         throw new NotImplementedException ();
1342                 }
1343
1344                 public static unsafe void WriteInt64 (IntPtr ptr, long val)
1345                 {
1346                         byte *addr = (byte *) ptr;
1347                         
1348                         // The real alignment might be 4 on some platforms, but this is just an optimization,
1349                         // so it doesn't matter.
1350                         if (((uint)addr & 7) == 0) 
1351                                 *(long*)addr = val;
1352                         else 
1353                                 Buffer.Memcpy (addr, (byte*)&val, 8);
1354                 }
1355
1356                 public static unsafe void WriteInt64 (IntPtr ptr, int ofs, long val)
1357                 {
1358                         byte *addr = ((byte *) ptr) + ofs;
1359
1360                         // The real alignment might be 4 on some platforms, but this is just an optimization,
1361                         // so it doesn't matter.
1362                         if (((uint)addr & 7) == 0) 
1363                                 *(long*)addr = val;
1364                         else 
1365                                 Buffer.Memcpy (addr, (byte*)&val, 8);
1366                 }
1367
1368                 [MonoTODO]
1369                 [SuppressUnmanagedCodeSecurity]
1370                 public static void WriteInt64 ([In, Out, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs, long val)
1371                 {
1372                         throw new NotImplementedException ();
1373                 }
1374
1375                 public static void WriteIntPtr (IntPtr ptr, IntPtr val)
1376                 {
1377                         if (IntPtr.Size == 4)
1378                                 WriteInt32 (ptr, (int)val);
1379                         else
1380                                 WriteInt64 (ptr, (long)val);
1381                 }
1382
1383                 public static void WriteIntPtr (IntPtr ptr, int ofs, IntPtr val)
1384                 {
1385                         if (IntPtr.Size == 4)
1386                                 WriteInt32 (ptr, ofs, (int)val);
1387                         else
1388                                 WriteInt64 (ptr, ofs, (long)val);
1389                 }
1390
1391                 [MonoTODO]
1392                 public static void WriteIntPtr([In, Out, MarshalAs(UnmanagedType.AsAny)] object ptr, int ofs, IntPtr val)
1393                 {
1394                         throw new NotImplementedException ();
1395                 }
1396
1397                 private static Exception ConvertHrToException (int errorCode)
1398                 {
1399                         const int MSEE_E_APPDOMAINUNLOADED = unchecked ((int)0x80131014L);
1400                         const int COR_E_APPLICATION = unchecked ((int)0x80131600L);
1401                         const int E_INVALIDARG = unchecked ((int)0x80070057);
1402                         const int COR_E_ARGUMENTOUTOFRANGE = unchecked ((int)0x80131502L);
1403                         const int COR_E_ARITHMETIC = unchecked ((int)0x80070216);
1404                         const int COR_E_ARRAYTYPEMISMATCH = unchecked ((int)0x80131503L);
1405                         const int COR_E_BADIMAGEFORMAT = unchecked ((int)0x8007000BL);
1406                         const int ERROR_BAD_FORMAT = unchecked ((int)0x0B);
1407                         //const int COR_E_COMEMULATE_ERROR = unchecked ((int)?);
1408                         const int COR_E_CONTEXTMARSHAL = unchecked ((int)0x80131504L);
1409                         //const int COR_E_CORE = unchecked ((int)?);
1410                         const int NTE_FAIL = unchecked ((int)0x80090020L);
1411                         const int COR_E_DIRECTORYNOTFOUND = unchecked ((int)0x80070003L);
1412                         const int ERROR_PATH_NOT_FOUND = unchecked ((int)0x03);
1413                         const int COR_E_DIVIDEBYZERO = unchecked ((int)0x80020012L);
1414                         const int COR_E_DUPLICATEWAITOBJECT = unchecked ((int)0x80131529L);
1415                         const int COR_E_ENDOFSTREAM = unchecked ((int)0x80070026L);
1416                         const int COR_E_TYPELOAD = unchecked ((int)0x80131522L);
1417                         const int COR_E_EXCEPTION = unchecked ((int)0x80131500L);
1418                         const int COR_E_EXECUTIONENGINE = unchecked ((int)0x80131506L);
1419                         const int COR_E_FIELDACCESS = unchecked ((int)0x80131507L);
1420                         const int COR_E_FILENOTFOUND = unchecked ((int)0x80070002L);
1421                         const int ERROR_FILE_NOT_FOUND = unchecked ((int)0x02);
1422                         const int COR_E_FORMAT = unchecked ((int)0x80131537L);
1423                         const int COR_E_INDEXOUTOFRANGE = unchecked ((int)0x80131508L);
1424                         const int COR_E_INVALIDCAST = unchecked ((int)0x80004002L);
1425                         const int COR_E_INVALIDCOMOBJECT = unchecked ((int)0x80131527L);
1426                         const int COR_E_INVALIDFILTERCRITERIA = unchecked ((int)0x80131601L);
1427                         const int COR_E_INVALIDOLEVARIANTTYPE = unchecked ((int)0x80131531L);
1428                         const int COR_E_INVALIDOPERATION = unchecked ((int)0x80131509L);
1429                         const int COR_E_IO = unchecked ((int)0x80131620L);
1430                         const int COR_E_MEMBERACCESS = unchecked ((int)0x8013151AL);
1431                         const int COR_E_METHODACCESS = unchecked ((int)0x80131510L);
1432                         const int COR_E_MISSINGFIELD = unchecked ((int)0x80131511L);
1433                         const int COR_E_MISSINGMANIFESTRESOURCE = unchecked ((int)0x80131532L);
1434                         const int COR_E_MISSINGMEMBER = unchecked ((int)0x80131512L);
1435                         const int COR_E_MISSINGMETHOD = unchecked ((int)0x80131513L);
1436                         const int COR_E_MULTICASTNOTSUPPORTED = unchecked ((int)0x80131514L);
1437                         const int COR_E_NOTFINITENUMBER = unchecked ((int)0x80131528L);
1438                         const int E_NOTIMPL = unchecked ((int)0x80004001L);
1439                         const int COR_E_NOTSUPPORTED = unchecked ((int)0x80131515L);
1440                         const int COR_E_NULLREFERENCE = unchecked ((int)0x80004003L);
1441                         const int E_OUTOFMEMORY = unchecked ((int)0x8007000EL);
1442                         const int COR_E_OVERFLOW = unchecked ((int)0x80131516L);
1443                         const int COR_E_PATHTOOLONG = unchecked ((int)0x800700CEL);
1444                         const int ERROR_FILENAME_EXCED_RANGE = unchecked ((int)0xCE);
1445                         const int COR_E_RANK = unchecked ((int)0x80131517L);
1446                         const int COR_E_REFLECTIONTYPELOAD = unchecked ((int)0x80131602L);
1447                         const int COR_E_REMOTING = unchecked ((int)0x8013150BL);
1448                         const int COR_E_SAFEARRAYTYPEMISMATCH = unchecked ((int)0x80131533L);
1449                         const int COR_E_SECURITY = unchecked ((int)0x8013150AL);
1450                         const int COR_E_SERIALIZATION = unchecked ((int)0x8013150CL);
1451                         const int COR_E_STACKOVERFLOW = unchecked ((int)0x800703E9L);
1452                         const int ERROR_STACK_OVERFLOW = unchecked ((int)0x03E9);
1453                         const int COR_E_SYNCHRONIZATIONLOCK = unchecked ((int)0x80131518L);
1454                         const int COR_E_SYSTEM = unchecked ((int)0x80131501L);
1455                         const int COR_E_TARGET = unchecked ((int)0x80131603L);
1456                         const int COR_E_TARGETINVOCATION = unchecked ((int)0x80131604L);
1457                         const int COR_E_TARGETPARAMCOUNT = unchecked ((int)0x8002000EL);
1458                         //const int COR_E_THREADABORTED = unchecked ((int)0x80131530L);
1459                         const int COR_E_THREADINTERRUPTED = unchecked ((int)0x80131519L);
1460                         const int COR_E_THREADSTATE = unchecked ((int)0x80131520L);
1461                         //const int COR_E_THREADSTOP = unchecked ((int)0x80131521L);
1462                         const int COR_E_TYPEINITIALIZATION = unchecked ((int)0x80131534L);
1463                         const int COR_E_VERIFICATION = unchecked ((int)0x8013150DL);
1464                         //const int COR_E_WEAKREFERENCE = unchecked ((int)?);
1465                         //const int COR_E_VTABLECALLSNOTSUPPORTED = unchecked ((int));
1466
1467                         switch (errorCode) {
1468                                 case MSEE_E_APPDOMAINUNLOADED:
1469                                         return new AppDomainUnloadedException ();
1470                                 case COR_E_APPLICATION:
1471                                         return new ApplicationException ();
1472                                 case E_INVALIDARG:
1473                                         return new ArgumentException ();
1474                                 case COR_E_ARGUMENTOUTOFRANGE:
1475                                         return new ArgumentOutOfRangeException ();
1476                                 case COR_E_ARITHMETIC:
1477                                         return new ArithmeticException ();
1478                                 case COR_E_ARRAYTYPEMISMATCH:
1479                                         return new ArrayTypeMismatchException ();
1480                                 case COR_E_BADIMAGEFORMAT:
1481                                 case ERROR_BAD_FORMAT:
1482                                         return new BadImageFormatException ();
1483 //                              case COR_E_COMEMULATE_ERROR:
1484 //                                      return new COMEmulateException ();
1485                                 case COR_E_CONTEXTMARSHAL:
1486                                         return new ContextMarshalException ();
1487 //                              case COR_E_CORE:
1488 //                                      return new CoreException ();
1489                                 case NTE_FAIL:
1490                                         return new System.Security.Cryptography.CryptographicException ();
1491                                 case COR_E_DIRECTORYNOTFOUND:
1492                                 case ERROR_PATH_NOT_FOUND:
1493                                         return new System.IO.DirectoryNotFoundException ();
1494                                 case COR_E_DIVIDEBYZERO:
1495                                         return new DivideByZeroException ();
1496                                 case COR_E_DUPLICATEWAITOBJECT:
1497                                         return new DuplicateWaitObjectException ();
1498                                 case COR_E_ENDOFSTREAM:
1499                                         return new System.IO.EndOfStreamException ();
1500                                 case COR_E_EXCEPTION:
1501                                         return new Exception ();
1502                                 case COR_E_EXECUTIONENGINE:
1503                                         return new ExecutionEngineException ();
1504                                 case COR_E_FIELDACCESS:
1505                                         return new FieldAccessException ();
1506                                 case COR_E_FILENOTFOUND:
1507                                 case ERROR_FILE_NOT_FOUND:
1508                                         return new System.IO.FileNotFoundException ();
1509                                 case COR_E_FORMAT:
1510                                         return new FormatException ();
1511                                 case COR_E_INDEXOUTOFRANGE:
1512                                         return new IndexOutOfRangeException ();
1513                                 case COR_E_INVALIDCAST:
1514                                 // E_NOINTERFACE has same value as COR_E_INVALIDCAST
1515                                         return new InvalidCastException ();
1516                                 case COR_E_INVALIDCOMOBJECT:
1517                                         return new InvalidComObjectException ();
1518                                 case COR_E_INVALIDFILTERCRITERIA:
1519                                         return new InvalidFilterCriteriaException ();
1520                                 case COR_E_INVALIDOLEVARIANTTYPE:
1521                                         return new InvalidOleVariantTypeException ();
1522                                 case COR_E_INVALIDOPERATION:
1523                                         return new InvalidOperationException ();
1524                                 case COR_E_IO:
1525                                         return new System.IO.IOException ();
1526                                 case COR_E_MEMBERACCESS:
1527                                         return new MemberAccessException ();
1528                                 case COR_E_METHODACCESS:
1529                                         return new MethodAccessException ();
1530                                 case COR_E_MISSINGFIELD:
1531                                         return new MissingFieldException ();
1532                                 case COR_E_MISSINGMANIFESTRESOURCE:
1533                                         return new System.Resources.MissingManifestResourceException ();
1534                                 case COR_E_MISSINGMEMBER:
1535                                         return new MissingMemberException ();
1536                                 case COR_E_MISSINGMETHOD:
1537                                         return new MissingMethodException ();
1538                                 case COR_E_MULTICASTNOTSUPPORTED:
1539                                         return new MulticastNotSupportedException ();
1540                                 case COR_E_NOTFINITENUMBER:
1541                                         return new NotFiniteNumberException ();
1542                                 case E_NOTIMPL:
1543                                         return new NotImplementedException ();
1544                                 case COR_E_NOTSUPPORTED:
1545                                         return new NotSupportedException ();
1546                                 case COR_E_NULLREFERENCE:
1547                                 // E_POINTER has the same value as COR_E_NULLREFERENCE
1548                                         return new NullReferenceException ();
1549                                 case E_OUTOFMEMORY:
1550                                 // COR_E_OUTOFMEMORY has the same value as E_OUTOFMEMORY
1551                                         return new OutOfMemoryException ();
1552                                 case COR_E_OVERFLOW:
1553                                         return new OverflowException ();
1554                                 case COR_E_PATHTOOLONG:
1555                                 case ERROR_FILENAME_EXCED_RANGE:
1556                                         return new System.IO.PathTooLongException ();
1557                                 case COR_E_RANK:
1558                                         return new RankException ();
1559                                 case COR_E_REFLECTIONTYPELOAD:
1560                                         return new System.Reflection.ReflectionTypeLoadException (new Type[] { }, new Exception[] { });
1561                                 case COR_E_REMOTING:
1562                                         return new System.Runtime.Remoting.RemotingException ();
1563                                 case COR_E_SAFEARRAYTYPEMISMATCH:
1564                                         return new SafeArrayTypeMismatchException ();
1565                                 case COR_E_SECURITY:
1566                                         return new SecurityException ();
1567                                 case COR_E_SERIALIZATION:
1568                                         return new System.Runtime.Serialization.SerializationException ();
1569                                 case COR_E_STACKOVERFLOW:
1570                                 case ERROR_STACK_OVERFLOW:
1571                                         return new StackOverflowException ();
1572                                 case COR_E_SYNCHRONIZATIONLOCK:
1573                                         return new SynchronizationLockException ();
1574                                 case COR_E_SYSTEM:
1575                                         return new SystemException ();
1576                                 case COR_E_TARGET:
1577                                         return new TargetException ();
1578                                 case COR_E_TARGETINVOCATION:
1579                                         return new System.Reflection.TargetInvocationException (null);
1580                                 case COR_E_TARGETPARAMCOUNT:
1581                                         return new TargetParameterCountException ();
1582 //                              case COR_E_THREADABORTED:
1583 //                                      ThreadAbortException c'tor is inaccessible
1584 //                                      return new System.Threading.ThreadAbortException ();
1585                                 case COR_E_THREADINTERRUPTED:
1586                                         return new ThreadInterruptedException ();
1587                                 case COR_E_THREADSTATE:
1588                                         return new ThreadStateException ();
1589 //                              case COR_E_THREADSTOP:
1590 //                                      ThreadStopException does not exist
1591 //                                      return new System.Threading.ThreadStopException ();
1592                                 case COR_E_TYPELOAD:
1593                                         return new TypeLoadException ();
1594                                 // MSDN lists COR_E_TYPELOAD twice with different exceptions.
1595                                 // return new EntryPointNotFoundException ();
1596                                 case COR_E_TYPEINITIALIZATION:
1597                                         return new TypeInitializationException("", null);
1598                                 case COR_E_VERIFICATION:
1599                                         return new VerificationException ();
1600 //                              case COR_E_WEAKREFERENCE:
1601 //                                      return new WeakReferenceException ();
1602 //                              case COR_E_VTABLECALLSNOTSUPPORTED:
1603 //                                      return new VTableCallsNotSupportedException ();
1604                         }
1605                         if (errorCode < 0)
1606                                 return new COMException ("", errorCode);
1607                         return null;
1608                 }
1609
1610 #if FEATURE_COMINTEROP
1611                 [DllImport ("oleaut32.dll", CharSet=CharSet.Unicode, EntryPoint = "SetErrorInfo")]
1612                 static extern int _SetErrorInfo (int dwReserved,
1613                         [MarshalAs(UnmanagedType.Interface)] IErrorInfo pIErrorInfo);
1614
1615                 [DllImport ("oleaut32.dll", CharSet=CharSet.Unicode, EntryPoint = "GetErrorInfo")]
1616                 static extern int _GetErrorInfo (int dwReserved,
1617                         [MarshalAs(UnmanagedType.Interface)] out IErrorInfo ppIErrorInfo);
1618
1619                 static bool SetErrorInfoNotAvailable;
1620                 static bool GetErrorInfoNotAvailable;
1621
1622                 internal static int SetErrorInfo (int dwReserved, IErrorInfo errorInfo)
1623                 {
1624                         int retVal = 0;
1625                         errorInfo = null;
1626
1627                         if (SetErrorInfoNotAvailable)
1628                                 return -1;
1629
1630                         try {
1631                                 retVal = _SetErrorInfo (dwReserved, errorInfo);
1632                         }
1633                         catch (Exception) {
1634                                 // ignore any exception - probably there's no suitable SetErrorInfo
1635                                 // method available.
1636                                 SetErrorInfoNotAvailable = true;
1637                         }
1638                         return retVal;
1639                 }
1640
1641                 internal static int GetErrorInfo (int dwReserved, out IErrorInfo errorInfo)
1642                 {
1643                         int retVal = 0;
1644                         errorInfo = null;
1645
1646                         if (GetErrorInfoNotAvailable)
1647                                 return -1;
1648
1649                         try {
1650                                 retVal = _GetErrorInfo (dwReserved, out errorInfo);
1651                         }
1652                         catch (Exception) {
1653                                 // ignore any exception - probably there's no suitable GetErrorInfo
1654                                 // method available.
1655                                 GetErrorInfoNotAvailable = true;
1656                         }
1657                         return retVal;
1658                 }
1659 #endif
1660                 public static Exception GetExceptionForHR (int errorCode)
1661                 {
1662                         return GetExceptionForHR (errorCode, IntPtr.Zero);
1663                 }
1664
1665                 public static Exception GetExceptionForHR (int errorCode, IntPtr errorInfo)
1666                 {
1667 #if FEATURE_COMINTEROP
1668                         IErrorInfo info = null;
1669                         if (errorInfo != (IntPtr)(-1)) {
1670                                 if (errorInfo == IntPtr.Zero) {
1671                                         if (GetErrorInfo (0, out info) != 0) {
1672                                                 info  = null;
1673                                         }
1674                                 } else {
1675                                         info  = Marshal.GetObjectForIUnknown (errorInfo) as IErrorInfo;
1676                                 }
1677                         }
1678
1679                         if (info is ManagedErrorInfo && ((ManagedErrorInfo) info).Exception._HResult == errorCode) {
1680                                 return ((ManagedErrorInfo) info).Exception;
1681                         }
1682
1683                         Exception e = ConvertHrToException (errorCode);
1684                         if (info != null && e != null) {
1685                                 uint helpContext;
1686                                 info.GetHelpContext (out helpContext);
1687                                 string str;
1688                                 info.GetSource (out str);
1689                                 e.Source = str;
1690                                 info.GetDescription (out str);
1691                                 e.SetMessage (str);
1692                                 info.GetHelpFile (out str);
1693
1694                                 if (helpContext == 0) {
1695                                         e.HelpLink = str;
1696                                 } else {
1697                                         e.HelpLink = string.Format ("{0}#{1}", str, helpContext);
1698                                 }
1699                         }
1700                         return e;
1701 #else
1702                         return ConvertHrToException (errorCode);
1703 #endif
1704                 }
1705
1706                 public static int FinalReleaseComObject (object o)
1707                 {
1708                         while (ReleaseComObject (o) != 0);
1709                         return 0;
1710                 }
1711
1712                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1713                 private static extern Delegate GetDelegateForFunctionPointerInternal (IntPtr ptr, Type t);
1714
1715                 public static Delegate GetDelegateForFunctionPointer (IntPtr ptr, Type t)
1716                 {
1717                         if (t == null)
1718                                 throw new ArgumentNullException ("t");
1719                         if (!t.IsSubclassOf (typeof (MulticastDelegate)) || (t == typeof (MulticastDelegate)))
1720                                 throw new ArgumentException ("Type is not a delegate", "t");
1721                         if (t.IsGenericType)
1722                                 throw new ArgumentException ("The specified Type must not be a generic type definition.");
1723                         if (ptr == IntPtr.Zero)
1724                                 throw new ArgumentNullException ("ptr");
1725
1726                         return GetDelegateForFunctionPointerInternal (ptr, t);
1727                 }
1728
1729                 public static TDelegate GetDelegateForFunctionPointer<TDelegate> (IntPtr ptr) {
1730                         return (TDelegate) (object) GetDelegateForFunctionPointer (ptr, typeof (TDelegate));
1731                 }
1732
1733                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1734                 private static extern IntPtr GetFunctionPointerForDelegateInternal (Delegate d);
1735                 
1736                 public static IntPtr GetFunctionPointerForDelegate (Delegate d)
1737                 {
1738                         if (d == null)
1739                                 throw new ArgumentNullException ("d");
1740                         
1741                         return GetFunctionPointerForDelegateInternal (d);
1742                 }
1743
1744                 public static IntPtr GetFunctionPointerForDelegate<TDelegate> (TDelegate d) {
1745                         if (d == null)
1746                                 throw new ArgumentNullException ("d");
1747                         
1748                         return GetFunctionPointerForDelegateInternal ((Delegate)(object)d);
1749                 }
1750
1751                 internal static void SetLastWin32Error (int error)
1752                 {
1753                 }
1754
1755                 // Copied from referencesource/mscorlib/system/runtime/interopservices/marshal.cs
1756                 //====================================================================
1757                 // return the raw IUnknown* for a COM Object not related to current 
1758                 // context
1759                 // Does not call AddRef
1760                 //====================================================================
1761                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1762                 internal static extern IntPtr /* IUnknown* */ GetRawIUnknownForComObjectNoAddRef(Object o);
1763                 
1764                 // Copied from referencesource/mscorlib/system/runtime/interopservices/marshal.cs
1765                 //====================================================================
1766                 // Converts the CLR exception to an HRESULT. This function also sets
1767                 // up an IErrorInfo for the exception.
1768                 // This function is only used in WinRT and converts ObjectDisposedException
1769                 // to RO_E_CLOSED
1770                 //====================================================================
1771                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1772                 internal static extern int GetHRForException_WinRT(Exception e);
1773
1774                 // Copied from referencesource/mscorlib/system/runtime/interopservices/marshal.cs
1775                 //========================================================================
1776                 // Create activation factory and wraps it with a unique RCW
1777                 //========================================================================
1778                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1779                 internal static extern object GetNativeActivationFactory(Type type);
1780         }
1781 }