Merge pull request #217 from QuickJack/master
[mono.git] / mcs / class / corlib / System.Runtime.InteropServices / SafeHandle.cs
1 //
2 // System.Runtime.InteropServices.SafeHandle
3 //
4 // Copyright (C) 2005 Novell, Inc (http://www.novell.com)
5 //
6 // Permission is hereby granted, free of charge, to any person obtaining
7 // a copy of this software and associated documentation files (the
8 // "Software"), to deal in the Software without restriction, including
9 // without limitation the rights to use, copy, modify, merge, publish,
10 // distribute, sublicense, and/or sell copies of the Software, and to
11 // permit persons to whom the Software is furnished to do so, subject to
12 // the following conditions:
13 // 
14 // The above copyright notice and this permission notice shall be
15 // included in all copies or substantial portions of the Software.
16 // 
17 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
18 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
20 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
21 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
22 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
23 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
24 //
25 // Notes:
26 //     This code is only API complete, but it lacks the runtime support
27 //     for CriticalFinalizerObject and any P/Invoke wrapping that might
28 //     happen.
29 //
30 //     For details, see:
31 //     http://blogs.msdn.com/cbrumme/archive/2004/02/20/77460.aspx
32 //
33 //     CER-like behavior is implemented for Close and DangerousAddRef
34 //     via the try/finally uninterruptible pattern in case of async
35 //     exceptions like ThreadAbortException.
36 //
37 // On implementing SafeHandles:
38 //     http://blogs.msdn.com/bclteam/archive/2005/03/15/396335.aspx
39 //
40 // Issues:
41 //
42 //     TODO: Although DangerousAddRef has been implemented, I need to
43 //     find out whether the runtime performs the P/Invoke if the
44 //     handle has been disposed already.
45 //
46 //
47
48 using System;
49 using System.Runtime.InteropServices;
50 using System.Runtime.ConstrainedExecution;
51 using System.Runtime.CompilerServices;
52 using System.Threading;
53
54 namespace System.Runtime.InteropServices
55 {
56         [StructLayout (LayoutKind.Sequential)]
57         public abstract class SafeHandle : CriticalFinalizerObject, IDisposable {
58                 //
59                 // Warning: the offset of handle is mapped inside the runtime
60                 // if you move this, you must updated the runtime definition of
61                 // MonoSafeHandle
62                 //
63                 protected IntPtr handle;
64                 IntPtr invalid_handle_value;
65                 int refcount = 0;
66                 bool owns_handle;
67                 
68 #if NET_2_1
69                 protected SafeHandle ()
70                 {
71                         throw new NotImplementedException ();
72                 }
73 #endif
74                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
75                 protected SafeHandle (IntPtr invalidHandleValue, bool ownsHandle)
76                 {
77                         invalid_handle_value = invalidHandleValue;
78                         owns_handle = ownsHandle;
79                         refcount = 1;
80                 }
81
82                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
83                 public void Close ()
84                 {
85                         if (refcount == 0)
86                                 throw new ObjectDisposedException (GetType ().FullName);
87
88                         int newcount = 0, current = 0;
89                         bool registered = false;
90                         RuntimeHelpers.PrepareConstrainedRegions ();
91                         try {
92                                 do {
93                                         current = refcount;
94                                         newcount = current-1;
95
96                                         // perform changes in finally to avoid async interruptions
97                                         try {}
98                                         finally {
99                                                 if (Interlocked.CompareExchange (ref refcount, newcount, current) == current)
100                                                         registered = true;
101                                         }
102                                 } while (!registered);
103                         } finally {
104                                 if (registered && newcount == 0 && owns_handle && !IsInvalid){
105                                         ReleaseHandle ();
106                                         handle = invalid_handle_value;
107                                         refcount = -1;
108                                 }
109                         }
110                 }
111
112                 //
113                 // I do not know when we could not be able to increment the
114                 // reference count and set success to false.   It might just
115                 // be a convention used for the following code pattern:
116                 //
117                 // bool release = false
118                 // try { x.DangerousAddRef (ref release); ... }
119                 // finally { if (release) x.DangerousRelease (); }
120                 //
121                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
122                 public void DangerousAddRef (ref bool success)
123                 {
124                         if (refcount <= 0)
125                                 throw new ObjectDisposedException (GetType ().FullName);
126
127                         bool registered = false;
128                         int newcount, current;
129                         do {
130                                 current = refcount;
131                                 newcount = current + 1;
132                                 
133                                 if (current <= 0){
134                                         //
135                                         // In MS, calling sf.Close () followed by a call
136                                         // to P/Invoke with SafeHandles throws this, but
137                                         // am left wondering: when would "success" be
138                                         // set to false?
139                                         //
140                                         throw new ObjectDisposedException (GetType ().FullName);
141                                 }
142
143                                 // perform changes in finally to avoid async interruptions
144                                 RuntimeHelpers.PrepareConstrainedRegions ();
145                                 try {}
146                                 finally {
147                                         if (Interlocked.CompareExchange (ref refcount, newcount, current) == current)
148                                                 registered = success = true;
149                                 }
150                         } while (!registered);
151                 }
152
153                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
154                 public IntPtr DangerousGetHandle ()
155                 {
156                         if (refcount <= 0){
157                                 throw new ObjectDisposedException (GetType ().FullName);
158                         }
159
160                         return handle;
161                 }
162
163                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
164                 public void DangerousRelease ()
165                 {
166                         if (refcount <= 0)
167                                 throw new ObjectDisposedException (GetType ().FullName);
168
169                         int newcount, current;
170                         do {
171                                 current = refcount;
172                                 newcount = current-1;
173                         } while (Interlocked.CompareExchange (ref refcount, newcount, current) != current);
174
175                         if (newcount == 0 && owns_handle && !IsInvalid){
176                                 ReleaseHandle ();
177                                 handle = invalid_handle_value;
178                         }
179                 }
180
181                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
182                 public void Dispose ()
183                 {
184                         Dispose (true);
185                         GC.SuppressFinalize (this);
186                 }
187
188                 //
189                 // See documentation, this invalidates the handle without
190                 // closing it.
191                 //
192                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
193                 public void SetHandleAsInvalid ()
194                 {
195                         handle = invalid_handle_value;
196                 }
197                 
198                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
199                 protected virtual void Dispose (bool disposing)
200                 {
201                         if (disposing)
202                                 Close ();
203                         else {
204                                 //
205                                 // The docs say `never call this with disposing=false',
206                                 // the question is whether:
207                                 //   * The runtime will ever call Dipose(false) for SafeHandles (special runtime case)
208                                 //   * Whether we should just call ReleaseHandle regardless?
209                                 //
210                         }
211                 }
212
213                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
214                 protected abstract bool ReleaseHandle ();
215
216                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
217                 protected void SetHandle (IntPtr handle)
218                 {
219                         this.handle = handle;
220                 }
221
222                 public bool IsClosed {
223                         [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
224                         get {
225                                 return refcount <= 0;
226                         }
227                 }
228
229                 public abstract bool IsInvalid {
230                         [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
231                         get;
232                 }
233
234                 ~SafeHandle ()
235                 {
236                         if (owns_handle && !IsInvalid){
237                                 ReleaseHandle ();
238                                 handle = invalid_handle_value;
239                         }
240                 }
241         }
242 }