[corlib] Make Marshal.BufferToBSTR(Array, int) non-public again (#5670)
[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                 [MonoTODO]
79                 public static void CleanupUnusedObjectsInCurrentContext ()
80                 {
81                         if (Environment.IsRunningOnWindows)
82                                 throw new PlatformNotSupportedException ();
83                 }
84
85                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
86                 public extern static IntPtr AllocCoTaskMem (int cb);
87                 
88                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
89                 internal extern static IntPtr AllocCoTaskMemSize (UIntPtr sizet);
90
91                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
92                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
93                 public extern static IntPtr AllocHGlobal (IntPtr cb);
94
95                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
96                 public static IntPtr AllocHGlobal (int cb)
97                 {
98                         return AllocHGlobal ((IntPtr)cb);
99                 }
100
101                 [MonoTODO]
102                 public static object BindToMoniker (string monikerName)
103                 {
104                         throw new NotImplementedException ();
105                 }
106
107                 [MonoTODO]
108                 public static void ChangeWrapperHandleStrength (object otp, bool fIsWeak)
109                 {
110                         throw new NotImplementedException ();
111                 }
112
113                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
114                 internal extern static void copy_to_unmanaged (Array source, int startIndex,
115                                                                IntPtr destination, int length);
116
117                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
118                 internal extern static void copy_from_unmanaged (IntPtr source, int startIndex,
119                                                                  Array destination, int length);
120
121                 public static void Copy (byte[] source, int startIndex, IntPtr destination, int length)
122                 {
123                         copy_to_unmanaged (source, startIndex, destination, length);
124                 }
125
126                 public static void Copy (char[] source, int startIndex, IntPtr destination, int length)
127                 {
128                         copy_to_unmanaged (source, startIndex, destination, length);
129                 }
130
131                 public static void Copy (short[] source, int startIndex, IntPtr destination, int length)
132                 {
133                         copy_to_unmanaged (source, startIndex, destination, length);
134                 }
135
136                 public static void Copy (int[] source, int startIndex, IntPtr destination, int length)
137                 {
138                         copy_to_unmanaged (source, startIndex, destination, length);
139                 }
140
141                 public static void Copy (long[] source, int startIndex, IntPtr destination, int length)
142                 {
143                         copy_to_unmanaged (source, startIndex, destination, length);
144                 }
145
146                 public static void Copy (float[] source, int startIndex, IntPtr destination, int length)
147                 {
148                         copy_to_unmanaged (source, startIndex, destination, length);
149                 }
150
151                 public static void Copy (double[] source, int startIndex, IntPtr destination, int length)
152                 {
153                         copy_to_unmanaged (source, startIndex, destination, length);
154                 }
155
156                 public static void Copy (IntPtr[] source, int startIndex, IntPtr destination, int length)
157                 {
158                         copy_to_unmanaged (source, startIndex, destination, length);
159                 }
160
161                 public static void Copy (IntPtr source, byte[] destination, int startIndex, int length)
162                 {
163                         copy_from_unmanaged (source, startIndex, destination, length);
164                 }
165
166                 public static void Copy (IntPtr source, char[] destination, int startIndex, int length)
167                 {
168                         copy_from_unmanaged (source, startIndex, destination, length);
169                 }
170
171                 public static void Copy (IntPtr source, short[] destination, int startIndex, int length)
172                 {
173                         copy_from_unmanaged (source, startIndex, destination, length);
174                 }
175
176                 public static void Copy (IntPtr source, int[] destination, int startIndex, int length)
177                 {
178                         copy_from_unmanaged (source, startIndex, destination, length);
179                 }
180
181                 public static void Copy (IntPtr source, long[] destination, int startIndex, int length)
182                 {
183                         copy_from_unmanaged (source, startIndex, destination, length);
184                 }
185
186                 public static void Copy (IntPtr source, float[] destination, int startIndex, int length)
187                 {
188                         copy_from_unmanaged (source, startIndex, destination, length);
189                 }
190
191                 public static void Copy (IntPtr source, double[] destination, int startIndex, int length)
192                 {
193                         copy_from_unmanaged (source, startIndex, destination, length);
194                 }
195
196                 public static void Copy (IntPtr source, IntPtr[] destination, int startIndex, int length)
197                 {
198                         copy_from_unmanaged (source, startIndex, destination, length);
199                 }
200
201                 public static IntPtr CreateAggregatedObject (IntPtr pOuter,
202                                                              object o)
203                 {
204                         throw new NotImplementedException ();
205                 }
206
207                 public static IntPtr CreateAggregatedObject<T> (IntPtr pOuter, T o) {
208                         return CreateAggregatedObject (pOuter, (object)o);
209                 }
210
211                 public static object CreateWrapperOfType (object o, Type t)
212                 {
213 #if FULL_AOT_RUNTIME
214                         throw new PlatformNotSupportedException ();
215 #else
216                         __ComObject co = o as __ComObject;
217                         if (co == null)
218                                 throw new ArgumentException ("o must derive from __ComObject", "o");
219                         if (t == null)
220                                 throw new ArgumentNullException ("t");
221
222                         Type[] itfs = o.GetType ().GetInterfaces ();
223                         foreach (Type itf in itfs) {
224                                 if (itf.IsImport && co.GetInterface (itf) == IntPtr.Zero)
225                                         throw new InvalidCastException ();
226                         }
227
228                         return ComInteropProxy.GetProxy (co.IUnknown, t).GetTransparentProxy ();
229 #endif
230                 }
231
232                 public static TWrapper CreateWrapperOfType<T, TWrapper> (T o) {
233                         return (TWrapper)CreateWrapperOfType ((object)o, typeof (TWrapper));
234                 }
235
236                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
237                 [ComVisible (true)]
238                 public extern static void DestroyStructure (IntPtr ptr, Type structuretype);
239
240                 public static void DestroyStructure<T> (IntPtr ptr) {
241                         DestroyStructure (ptr, typeof (T));
242                 }
243
244                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
245                 public extern static void FreeBSTR (IntPtr ptr);
246
247                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
248                 public extern static void FreeCoTaskMem (IntPtr ptr);
249
250                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
251                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
252                 public extern static void FreeHGlobal (IntPtr hglobal);
253
254                 static void ClearBSTR (IntPtr ptr)
255                 {
256                         int len = ReadInt32 (ptr, -4);
257
258                         for (int i = 0; i < len; i++)
259                                 WriteByte (ptr, i, 0);
260                 }
261                 
262                 public static void ZeroFreeBSTR (IntPtr s)
263                 {
264                         ClearBSTR (s);
265                         FreeBSTR (s);
266                 }
267
268                 static void ClearAnsi (IntPtr ptr)
269                 {
270                         for (int i = 0; ReadByte (ptr, i) != 0; i++)
271                                 WriteByte (ptr, i, 0);
272                 }
273
274                 static void ClearUnicode (IntPtr ptr)
275                 {
276                         for (int i = 0; ReadInt16 (ptr, i) != 0; i += 2)
277                                 WriteInt16 (ptr, i, 0);
278                 }
279                 
280                 public static void ZeroFreeCoTaskMemAnsi (IntPtr s)
281                 {
282                         ClearAnsi (s);
283                         FreeCoTaskMem (s);
284                 }
285
286                 public static void ZeroFreeCoTaskMemUnicode (IntPtr s)
287                 {
288                         ClearUnicode (s);
289                         FreeCoTaskMem (s);
290                 }
291
292                 public static void ZeroFreeCoTaskMemUTF8 (IntPtr s)
293                 {
294                         ClearAnsi (s);
295                         FreeCoTaskMem (s);
296                 }
297                 
298                 public static void ZeroFreeGlobalAllocAnsi (IntPtr s)
299                 {
300                         ClearAnsi (s);
301                         FreeHGlobal (s);
302                 }
303
304                 public static void ZeroFreeGlobalAllocUnicode (IntPtr s)
305                 {
306                         ClearUnicode (s);
307                         FreeHGlobal (s);
308                 }
309
310 #if !FULL_AOT_RUNTIME
311                 public static Guid GenerateGuidForType (Type type)
312                 {
313                         return type.GUID;
314                 }
315
316                 public static string GenerateProgIdForType (Type type)
317                 {
318                         IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (type);
319
320                         foreach (var a in attrs)
321                         {
322                                 var dt = a.Constructor.DeclaringType;
323                                 string name = dt.Name;
324                                 if (name == "ProgIdAttribute")
325                                 {
326                                         var args = a.ConstructorArguments;
327                                         string text = a.ConstructorArguments[0].Value as string;
328                                         if (text == null)
329                                         {
330                                                 text = string.Empty;
331                                         }
332                                         return text;
333                                 }
334                         }
335
336                         return type.FullName;
337                 }
338
339                 [MonoTODO]
340                 public static object GetActiveObject (string progID)
341                 {
342                         throw new NotImplementedException ();
343                 }
344
345 #if !MOBILE
346                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
347                 private extern static IntPtr GetCCW (object o, Type T);
348
349                 private static IntPtr GetComInterfaceForObjectInternal (object o, Type T)
350                 {
351                         if (IsComObject (o))
352                                 return ((__ComObject)o).GetInterface (T);
353                         else
354                                 return GetCCW (o, T);
355                 }
356 #endif
357 #endif // !FULL_AOT_RUNTIME
358
359                 public static IntPtr GetComInterfaceForObject (object o, Type T)
360                 {
361 #if MOBILE
362                         throw new PlatformNotSupportedException ();
363 #else
364                         IntPtr pItf = GetComInterfaceForObjectInternal (o, T);
365                         AddRef (pItf);
366                         return pItf;
367 #endif
368                 }
369
370                 [MonoTODO]
371                 public static IntPtr GetComInterfaceForObject (object o, Type T, CustomQueryInterfaceMode mode)
372                 {
373                         throw new NotImplementedException ();
374                 }
375
376                 public static IntPtr GetComInterfaceForObject<T, TInterface> (T o) {
377                         return GetComInterfaceForObject ((object)o, typeof (T));
378                 }
379
380 #if !FULL_AOT_RUNTIME
381                 [MonoTODO]
382                 public static IntPtr GetComInterfaceForObjectInContext (object o, Type t)
383                 {
384                         throw new NotImplementedException ();
385                 }
386
387                 [MonoNotSupportedAttribute ("MSDN states user code should never need to call this method.")]
388                 public static object GetComObjectData (object obj, object key)
389                 {
390                         throw new NotSupportedException ("MSDN states user code should never need to call this method.");
391                 }
392
393 #if !MOBILE
394                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
395                 private extern static int GetComSlotForMethodInfoInternal (MemberInfo m);
396 #endif
397
398                 public static int GetComSlotForMethodInfo (MemberInfo m)
399                 {
400 #if !MOBILE
401                         if (m == null)
402                                 throw new ArgumentNullException ("m");
403                         if (!(m is MethodInfo))
404                                 throw new ArgumentException ("The MemberInfo must be an interface method.", "m");
405                         if (!m.DeclaringType.IsInterface)
406                                 throw new ArgumentException ("The MemberInfo must be an interface method.", "m");
407                         return GetComSlotForMethodInfoInternal (m);
408 #else
409                         throw new NotImplementedException ();
410 #endif
411                 }
412
413                 [MonoTODO]
414                 public static int GetEndComSlot (Type t)
415                 {
416                         throw new NotImplementedException ();
417                 }
418
419                 [MonoTODO]
420                 [ComVisible (true)]
421                 public static IntPtr GetExceptionPointers()
422                 {
423                         throw new NotImplementedException ();
424                 }
425
426                 public static IntPtr GetHINSTANCE (Module m)
427                 {
428                         if (m == null)
429                                 throw new ArgumentNullException ("m");
430
431                         return m.GetHINSTANCE ();
432                 }
433 #endif // !FULL_AOT_RUNTIME
434
435                 public static int GetExceptionCode ()
436                 {
437                         throw new PlatformNotSupportedException ();
438                 }
439
440                 public static int GetHRForException (Exception e)
441                 {
442                         if (e == null) return 0;
443
444 #if FEATURE_COMINTEROP
445                         var errorInfo = new ManagedErrorInfo(e);
446                         SetErrorInfo (0, errorInfo);
447 #endif
448
449                         return e._HResult;
450                 }
451
452                 [MonoTODO]
453                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
454                 public static int GetHRForLastWin32Error()
455                 {
456 #if FULL_AOT_RUNTIME
457                         throw new PlatformNotSupportedException ();
458 #else
459                         throw new NotImplementedException ();
460 #endif
461                 }
462
463 #if !FULL_AOT_RUNTIME
464                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
465                 private extern static IntPtr GetIDispatchForObjectInternal (object o);
466
467                 public static IntPtr GetIDispatchForObject (object o)
468                 {
469                         IntPtr pUnk = GetIDispatchForObjectInternal (o);
470                         // Internal method does not AddRef
471                         AddRef (pUnk);
472                         return pUnk;
473                 }
474
475                 [MonoTODO]
476                 public static IntPtr GetIDispatchForObjectInContext (object o)
477                 {
478                         throw new NotImplementedException ();
479                 }
480
481                 [MonoTODO]
482                 public static IntPtr GetITypeInfoForType (Type t)
483                 {
484                         throw new NotImplementedException ();
485                 }
486
487                 [MonoTODO]
488                 public static IntPtr GetIUnknownForObjectInContext (object o)
489                 {
490                         throw new NotImplementedException ();
491                 }
492
493                 [MonoTODO]
494                 [Obsolete ("This method has been deprecated")]
495                 public static IntPtr GetManagedThunkForUnmanagedMethodPtr (IntPtr pfnMethodToWrap, IntPtr pbSignature, int cbSignature)
496                 {
497                         throw new NotImplementedException ();
498                 }
499
500                 [MonoTODO]
501                 public static MemberInfo GetMethodInfoForComSlot (Type t, int slot, ref ComMemberType memberType)
502                 {
503                         throw new NotImplementedException ();
504                 }
505
506                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
507                 private extern static IntPtr GetIUnknownForObjectInternal (object o);
508
509 #endif // !FULL_AOT_RUNTIME
510
511                 public static IntPtr GetIUnknownForObject (object o)
512                 {
513 #if FULL_AOT_RUNTIME
514                         throw new PlatformNotSupportedException ();
515 #else
516                         IntPtr pUnk = GetIUnknownForObjectInternal (o);
517                         // Internal method does not AddRef
518                         AddRef (pUnk);
519                         return pUnk;
520 #endif
521                 }
522
523                 public static void GetNativeVariantForObject (object obj, IntPtr pDstNativeVariant)
524                 {
525 #if FULL_AOT_RUNTIME
526                         throw new PlatformNotSupportedException ();
527 #else
528                         Variant vt = new Variant();
529                         vt.SetValue(obj);
530                         Marshal.StructureToPtr(vt, pDstNativeVariant, false);
531 #endif
532                 }
533
534                 public static void GetNativeVariantForObject<T> (T obj, IntPtr pDstNativeVariant) {
535                         GetNativeVariantForObject ((object)obj, pDstNativeVariant);
536                 }
537
538 #if !MOBILE && !FULL_AOT_RUNTIME
539                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
540                 private static extern object GetObjectForCCW (IntPtr pUnk);
541 #endif
542
543                 public static object GetObjectForIUnknown (IntPtr pUnk)
544                 {
545 #if MOBILE || FULL_AOT_RUNTIME
546                         throw new PlatformNotSupportedException ();
547 #else
548                         object obj = GetObjectForCCW (pUnk);
549                         // was not a CCW
550                         if (obj == null) {
551                                 ComInteropProxy proxy = ComInteropProxy.GetProxy (pUnk, typeof (__ComObject));
552                                 obj = proxy.GetTransparentProxy ();
553                         }
554                         return obj;
555 #endif
556                 }
557
558                 public static object GetObjectForNativeVariant (IntPtr pSrcNativeVariant)
559                 {
560 #if FULL_AOT_RUNTIME
561                         throw new PlatformNotSupportedException ();
562 #else
563                         Variant vt = (Variant)Marshal.PtrToStructure(pSrcNativeVariant, typeof(Variant));
564                         return vt.GetValue();
565 #endif
566                 }
567
568                 public static T GetObjectForNativeVariant<T> (IntPtr pSrcNativeVariant)
569                 {
570 #if FULL_AOT_RUNTIME
571                         throw new PlatformNotSupportedException ();
572 #else
573                         Variant vt = (Variant)Marshal.PtrToStructure(pSrcNativeVariant, typeof(Variant));
574                         return (T)vt.GetValue();
575 #endif
576                 }
577
578                 public static object[] GetObjectsForNativeVariants (IntPtr aSrcNativeVariant, int cVars)
579                 {
580 #if FULL_AOT_RUNTIME
581                         throw new PlatformNotSupportedException ();
582 #else
583                         if (cVars < 0)
584                                 throw new ArgumentOutOfRangeException ("cVars", "cVars cannot be a negative number.");
585                         object[] objects = new object[cVars];
586                         for (int i = 0; i < cVars; i++)
587                                 objects[i] = GetObjectForNativeVariant ((IntPtr)(aSrcNativeVariant.ToInt64 () +
588                                         i * SizeOf (typeof(Variant))));
589                         return objects;
590 #endif
591                 }
592
593                 public static T[] GetObjectsForNativeVariants<T> (IntPtr aSrcNativeVariant, int cVars)
594                 {
595 #if FULL_AOT_RUNTIME
596                         throw new PlatformNotSupportedException ();
597 #else
598                         if (cVars < 0)
599                                 throw new ArgumentOutOfRangeException ("cVars", "cVars cannot be a negative number.");
600                         T[] objects = new T[cVars];
601                         for (int i = 0; i < cVars; i++)
602                                 objects[i] = GetObjectForNativeVariant<T> ((IntPtr)(aSrcNativeVariant.ToInt64 () +
603                                         i * SizeOf (typeof(Variant))));
604                         return objects;
605 #endif
606                 }
607
608                 [MonoTODO]
609                 public static int GetStartComSlot (Type t)
610                 {
611 #if FULL_AOT_RUNTIME
612                         throw new PlatformNotSupportedException ();
613 #else
614                         throw new NotImplementedException ();
615 #endif
616                 }
617
618 #if !FULL_AOT_RUNTIME
619                 [MonoTODO]
620                 [Obsolete ("This method has been deprecated")]
621                 public static Thread GetThreadFromFiberCookie (int cookie)
622                 {
623                         throw new NotImplementedException ();
624                 }
625
626                 public static object GetTypedObjectForIUnknown (IntPtr pUnk, Type t)
627                 {
628                         ComInteropProxy proxy = new ComInteropProxy (pUnk, t);
629                         __ComObject co = (__ComObject)proxy.GetTransparentProxy ();
630                         foreach (Type itf in t.GetInterfaces ()) {
631                                 if ((itf.Attributes & TypeAttributes.Import) == TypeAttributes.Import) {
632                                         if (co.GetInterface (itf) == IntPtr.Zero)
633                                                 return null;
634                                 }
635                         }
636                         return co;
637                 }
638
639                 [MonoTODO]
640                 public static Type GetTypeForITypeInfo (IntPtr piTypeInfo)
641                 {
642                         throw new NotImplementedException ();
643                 }
644
645                 [Obsolete]
646                 [MonoTODO]
647                 public static string GetTypeInfoName (UCOMITypeInfo pTI)
648                 {
649                         throw new NotImplementedException ();
650                 }
651
652                 [Obsolete]
653                 [MonoTODO]
654                 public static Guid GetTypeLibGuid (UCOMITypeLib pTLB)
655                 {
656                         throw new NotImplementedException ();
657                 }
658
659                 [MonoTODO]
660                 public static Guid GetTypeLibGuid (ITypeLib typelib)
661                 {
662                         throw new NotImplementedException ();
663                 }
664
665                 [MonoTODO]
666                 public static Guid GetTypeLibGuidForAssembly (Assembly asm)
667                 {
668                         throw new NotImplementedException ();
669                 }
670
671                 [Obsolete]
672                 [MonoTODO]
673                 public static int GetTypeLibLcid (UCOMITypeLib pTLB)
674                 {
675                         throw new NotImplementedException ();
676                 }
677
678                 [MonoTODO]
679                 public static int GetTypeLibLcid (ITypeLib typelib)
680                 {
681                         throw new NotImplementedException ();
682                 }
683
684                 [Obsolete]
685                 [MonoTODO]
686                 public static string GetTypeLibName (UCOMITypeLib pTLB)
687                 {
688                         throw new NotImplementedException ();
689                 }
690
691                 [MonoTODO]
692                 public static string GetTypeLibName (ITypeLib typelib)
693                 {
694                         throw new NotImplementedException ();
695                 }
696
697                 [MonoTODO]
698                 public static void GetTypeLibVersionForAssembly (Assembly inputAssembly, out int majorVersion, out int minorVersion)
699                 {
700                         throw new NotImplementedException ();
701                 }
702
703                 [MonoTODO]
704                 [Obsolete ("This method has been deprecated")]
705                 public static IntPtr GetUnmanagedThunkForManagedMethodPtr (IntPtr pfnMethodToWrap, IntPtr pbSignature, int cbSignature)
706                 {
707                         throw new NotImplementedException ();
708                 }
709
710                 [MonoTODO]
711                 public static bool IsTypeVisibleFromCom (Type t)
712                 {
713                         throw new NotImplementedException ();
714                 }
715
716                 [MonoTODO]
717                 public static int NumParamBytes (MethodInfo m)
718                 {
719                         throw new NotImplementedException ();
720                 }
721 #endif // !FULL_AOT_RUNTIME
722
723                 public static Type GetTypeFromCLSID (Guid clsid)
724                 {
725                         throw new PlatformNotSupportedException ();
726                 }
727
728                 public static string GetTypeInfoName (ITypeInfo typeInfo)
729                 {
730                         throw new PlatformNotSupportedException ();
731                 }
732
733                 public static object GetUniqueObjectForIUnknown (IntPtr unknown)
734                 {
735                         throw new PlatformNotSupportedException ();
736                 }
737
738 #if !MOBILE
739                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
740                 public extern static bool IsComObject (object o);
741 #else
742                 public static bool IsComObject (object o)
743                 {
744                         return false;
745                 }
746 #endif
747
748                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
749                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
750                 public static extern int GetLastWin32Error();
751
752                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
753                 public extern static IntPtr OffsetOf (Type t, string fieldName);
754
755                 public static IntPtr OffsetOf<T> (string fieldName) {
756                         return OffsetOf (typeof (T), fieldName);
757                 }
758
759                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
760                 public extern static void Prelink (MethodInfo m);
761
762                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
763                 public extern static void PrelinkAll (Type c);
764
765                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
766                 public extern static string PtrToStringAnsi (IntPtr ptr);
767                 
768                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
769                 public extern static string PtrToStringAnsi (IntPtr ptr, int len);
770
771                 public static string PtrToStringUTF8 (IntPtr ptr)
772                 {
773                         return PtrToStringAnsi (ptr);
774                 }
775                 
776                 public static string PtrToStringUTF8 (IntPtr ptr, int byteLen)
777                 {
778                         return PtrToStringAnsi (ptr, byteLen);
779                 }
780                 
781                 public static string PtrToStringAuto (IntPtr ptr)
782                 {
783                         return SystemDefaultCharSize == 2
784                                 ? PtrToStringUni (ptr) : PtrToStringAnsi (ptr);
785                 }
786                 
787                 public static string PtrToStringAuto (IntPtr ptr, int len)
788                 {
789                         return SystemDefaultCharSize == 2
790                                 ? PtrToStringUni (ptr, len) : PtrToStringAnsi (ptr, len);
791                 }
792
793                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
794                 public extern static string PtrToStringUni (IntPtr ptr);
795
796                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
797                 public extern static string PtrToStringUni (IntPtr ptr, int len);
798
799                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
800                 public extern static string PtrToStringBSTR (IntPtr ptr);
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                 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 #if FEATURE_COMINTEROP || MONO_COM
1756                 // Copied from referencesource/mscorlib/system/runtime/interopservices/marshal.cs
1757                 //====================================================================
1758                 // return the raw IUnknown* for a COM Object not related to current 
1759                 // context
1760                 // Does not call AddRef
1761                 //====================================================================
1762                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1763                 internal static extern IntPtr /* IUnknown* */ GetRawIUnknownForComObjectNoAddRef(Object o);
1764                 
1765                 // Copied from referencesource/mscorlib/system/runtime/interopservices/marshal.cs
1766                 //====================================================================
1767                 // Converts the CLR exception to an HRESULT. This function also sets
1768                 // up an IErrorInfo for the exception.
1769                 // This function is only used in WinRT and converts ObjectDisposedException
1770                 // to RO_E_CLOSED
1771                 //====================================================================
1772                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1773                 internal static extern int GetHRForException_WinRT(Exception e);
1774
1775                 // Copied from referencesource/mscorlib/system/runtime/interopservices/marshal.cs
1776                 //========================================================================
1777                 // Create activation factory and wraps it with a unique RCW
1778                 //========================================================================
1779                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1780                 internal static extern object GetNativeActivationFactory(Type type);
1781 #else
1782                 internal static IntPtr /* IUnknown* */ GetRawIUnknownForComObjectNoAddRef(Object o) {
1783                         throw new NotSupportedException();
1784                 }
1785
1786                 internal static int GetHRForException_WinRT(Exception e) {
1787                         throw new NotSupportedException();
1788                 }
1789
1790                 internal static object GetNativeActivationFactory(Type type) {
1791                         throw new NotSupportedException();
1792                 }
1793 #endif
1794         }
1795 }