[sgen] Clear the card table in the finishing pause
[mono.git] / mcs / class / corlib / System / __ComObject.cs
1 //
2 // System.__ComObject
3 //
4 // Authors:
5 //   Sebastien Pouliot <sebastien@ximian.com>
6 //   Kornél Pál <http://www.kornelpal.hu/>
7 //   Jonathan Chambers <joncham@gmail.com>
8 //
9 // Copyright (C) 2004 Novell (http://www.novell.com)
10 // Copyright (C) 2005 Kornél Pál
11 // Copyright (C) 2006 Jonathan Chambers
12 //
13
14 //
15 // Permission is hereby granted, free of charge, to any person obtaining
16 // a copy of this software and associated documentation files (the
17 // "Software"), to deal in the Software without restriction, including
18 // without limitation the rights to use, copy, modify, merge, publish,
19 // distribute, sublicense, and/or sell copies of the Software, and to
20 // permit persons to whom the Software is furnished to do so, subject to
21 // the following conditions:
22 //
23 // The above copyright notice and this permission notice shall be
24 // included in all copies or substantial portions of the Software.
25 //
26 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
27 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
28 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
29 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
30 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
31 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
32 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
33 //
34
35 #if !FULL_AOT_RUNTIME
36 using Mono.Interop;
37 using System.Collections;
38 using System.Runtime.InteropServices;
39 using System.Runtime.CompilerServices;
40 using System.Threading;
41
42 namespace System
43 {
44         // This is a private class that is used as a generic wrapper class
45         // for COM objects that have no specific wrapper class.
46         //
47         // It has no public methods, it's functionality is exposed trough
48         // System.Runtime.InteropServices.Marshal class and can be casted to
49         // any interface that is implemented by the wrapped COM object.
50         //
51         // This class is referenced in .NET Framework SDK Documentation so
52         // many times that obj.GetType().FullName == "System.__ComObject" and
53         // Type.GetType("System.__ComObject") may be used.
54
55         [StructLayout (LayoutKind.Sequential)]
56         internal class __ComObject : MarshalByRefObject
57         {
58 #pragma warning disable 169     
59                 #region Sync with object-internals.h
60                 IntPtr iunknown;
61                 IntPtr hash_table;
62                 SynchronizationContext synchronization_context;
63                 #endregion
64 #pragma warning restore 169
65
66                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
67                 internal static extern __ComObject CreateRCW (Type t);
68
69                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
70                 private extern void ReleaseInterfaces ();
71
72                 ~__ComObject ()
73                 {       
74                         if (synchronization_context != null)
75                                 synchronization_context.Post ((state) => ReleaseInterfaces (), this);
76                         else
77                                 ReleaseInterfaces ();                           
78                 }
79
80                 public __ComObject ()
81                 {
82                         Initialize (GetType ());
83                 }
84
85                 internal __ComObject (Type t) {
86                         Initialize (t);
87                 }
88
89                 internal __ComObject (IntPtr pItf)
90                 {
91                         InitializeApartmentDetails ();
92                         Guid iid = IID_IUnknown;
93                         int hr = Marshal.QueryInterface (pItf, ref iid, out iunknown);
94                         Marshal.ThrowExceptionForHR (hr);
95                 }
96
97                 internal void Initialize (Type t)
98                 {
99                         InitializeApartmentDetails ();
100                         // Guard multiple invocation.
101                         if (iunknown != IntPtr.Zero)
102                                 return;
103
104                         System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor (t.TypeHandle);
105                         
106                         ObjectCreationDelegate ocd = ExtensibleClassFactory.GetObjectCreationCallback (t);
107                         if (ocd != null) {
108                                 iunknown = ocd (IntPtr.Zero);
109                                 if (iunknown == IntPtr.Zero)
110                                         throw new COMException (string.Format("ObjectCreationDelegate for type {0} failed to return a valid COM object", t));
111                         }
112                         else {
113                                 int hr = CoCreateInstance (GetCLSID (t), IntPtr.Zero, 0x1 | 0x4 | 0x10, IID_IUnknown, out iunknown);
114                                 Marshal.ThrowExceptionForHR (hr);
115                         }
116                 }
117
118                 private void InitializeApartmentDetails ()
119                 {
120                         // Only synchronization_context if thread is STA.
121                         if (Thread.CurrentThread.GetApartmentState() != ApartmentState.STA)
122                                 return;
123                         
124                         synchronization_context = SynchronizationContext.Current;
125
126                         // Check whether the current context is a plain SynchronizationContext object
127                         // and handle this as if no context was set at all.
128                         if (synchronization_context != null &&
129                                 synchronization_context.GetType () == typeof(SynchronizationContext))
130                                 synchronization_context = null;                 
131                 }
132
133                 private static Guid GetCLSID (Type t)
134                 {
135                         if (t.IsImport)
136                                 return t.GUID;
137
138                         // look at supertypes
139                         Type super = t.BaseType;
140                         while (super != typeof (object)) {
141                                 if (super.IsImport)
142                                         return super.GUID;
143                                 super = super.BaseType;
144                         }
145                         throw new COMException ("Could not find base COM type for type " + t.ToString());
146                 }
147
148                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
149                 internal extern IntPtr GetInterfaceInternal (Type t, bool throwException);
150
151                 internal IntPtr GetInterface (Type t, bool throwException) {
152                         CheckIUnknown ();
153                         return GetInterfaceInternal (t, throwException);
154                 }
155
156                 internal IntPtr GetInterface(Type t)
157                 {
158                         return GetInterface (t, true);
159                 }
160
161                 private void CheckIUnknown ()
162                 {
163                         if (iunknown == IntPtr.Zero)
164                                 throw new InvalidComObjectException ("COM object that has been separated from its underlying RCW cannot be used.");
165                 }
166
167                 internal IntPtr IUnknown
168                 {
169                         get
170                         {
171                                 if (iunknown == IntPtr.Zero)
172                                         throw new InvalidComObjectException ("COM object that has been separated from its underlying RCW cannot be used.");
173                                 return iunknown;
174                         }
175                 }
176
177                 internal IntPtr IDispatch
178                 {
179                         get
180                         {
181                                 IntPtr pUnk = GetInterface (typeof (IDispatch));
182                                 if (pUnk == IntPtr.Zero)
183                                         throw new InvalidComObjectException ("COM object that has been separated from its underlying RCW cannot be used.");
184                                 return pUnk;
185                         }
186                 }
187
188                 internal static Guid IID_IUnknown
189                 {
190                         get
191                         {
192                                 return new Guid("00000000-0000-0000-C000-000000000046");
193                         }
194                 }
195
196                 internal static Guid IID_IDispatch
197                 {
198                         get
199                         {
200                                 return new Guid ("00020400-0000-0000-C000-000000000046");
201                         }
202                 }
203
204                 public override bool Equals (object obj)
205                 {
206                         CheckIUnknown ();
207                         if (obj == null)
208                                 return false;
209
210                         __ComObject co = obj as __ComObject;
211                         if ((object)co == null)
212                                 return false;
213                         return (iunknown == co.IUnknown);
214                 }
215
216                 public override int GetHashCode ()
217                 {
218                         CheckIUnknown ();
219                         // not what MS seems to do, 
220                         // but IUnknown is identity in COM
221                         return iunknown.ToInt32 ();
222                 }
223
224                 [DllImport ("ole32.dll", CallingConvention = CallingConvention.StdCall, ExactSpelling = true, PreserveSig = true)]
225                 static extern int CoCreateInstance (
226                    [In, MarshalAs (UnmanagedType.LPStruct)] Guid rclsid,
227                    IntPtr pUnkOuter,
228                    uint dwClsContext,
229                   [In, MarshalAs (UnmanagedType.LPStruct)] Guid riid,
230                         out IntPtr pUnk);
231         }
232 }
233 #endif