2 // System.Runtime.InteropServices.SafeHandle
4 // Copyright (C) 2005 Novell, Inc (http://www.novell.com)
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:
14 // The above copyright notice and this permission notice shall be
15 // included in all copies or substantial portions of the Software.
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.
26 // This code is only API complete, but it lacks the runtime support
27 // for CriticalFinalizerObject and any P/Invoke wrapping that might
31 // http://blogs.msdn.com/cbrumme/archive/2004/02/20/77460.aspx
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.
37 // On implementing SafeHandles:
38 // http://blogs.msdn.com/bclteam/archive/2005/03/15/396335.aspx
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.
49 using System.Runtime.InteropServices;
50 using System.Runtime.ConstrainedExecution;
51 using System.Runtime.CompilerServices;
52 using System.Threading;
54 namespace System.Runtime.InteropServices
56 public abstract class SafeHandle : CriticalFinalizerObject, IDisposable {
58 // Warning: the offset of handle is mapped inside the runtime
59 // if you move this, you must updated the runtime definition of
62 protected IntPtr handle;
63 IntPtr invalid_handle_value;
68 protected SafeHandle ()
70 throw new NotImplementedException ();
73 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
74 protected SafeHandle (IntPtr invalidHandleValue, bool ownsHandle)
76 invalid_handle_value = invalidHandleValue;
77 owns_handle = ownsHandle;
81 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
85 throw new ObjectDisposedException (GetType ().FullName);
87 int newcount = 0, current = 0;
88 bool registered = false;
89 RuntimeHelpers.PrepareConstrainedRegions ();
95 // perform changes in finally to avoid async interruptions
98 if (Interlocked.CompareExchange (ref refcount, newcount, current) == current)
101 } while (!registered);
103 if (registered && newcount == 0 && owns_handle && !IsInvalid){
105 handle = invalid_handle_value;
112 // I do not know when we could not be able to increment the
113 // reference count and set success to false. It might just
114 // be a convention used for the following code pattern:
116 // bool release = false
117 // try { x.DangerousAddRef (ref release); ... }
118 // finally { if (release) x.DangerousRelease (); }
120 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
121 public void DangerousAddRef (ref bool success)
124 throw new ObjectDisposedException (GetType ().FullName);
126 bool registered = false;
127 int newcount, current;
130 newcount = current + 1;
134 // In MS, calling sf.Close () followed by a call
135 // to P/Invoke with SafeHandles throws this, but
136 // am left wondering: when would "success" be
139 throw new ObjectDisposedException (GetType ().FullName);
142 // perform changes in finally to avoid async interruptions
143 RuntimeHelpers.PrepareConstrainedRegions ();
146 if (Interlocked.CompareExchange (ref refcount, newcount, current) == current)
147 registered = success = true;
149 } while (!registered);
152 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
153 public IntPtr DangerousGetHandle ()
156 throw new ObjectDisposedException (GetType ().FullName);
162 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
163 public void DangerousRelease ()
166 throw new ObjectDisposedException (GetType ().FullName);
168 int newcount, current;
171 newcount = current-1;
172 } while (Interlocked.CompareExchange (ref refcount, newcount, current) != current);
174 if (newcount == 0 && owns_handle && !IsInvalid){
176 handle = invalid_handle_value;
180 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
181 public void Dispose ()
184 GC.SuppressFinalize (this);
188 // See documentation, this invalidates the handle without
191 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
192 public void SetHandleAsInvalid ()
194 handle = invalid_handle_value;
197 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
198 protected virtual void Dispose (bool disposing)
204 // The docs say `never call this with disposing=false',
205 // the question is whether:
206 // * The runtime will ever call Dipose(false) for SafeHandles (special runtime case)
207 // * Whether we should just call ReleaseHandle regardless?
212 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
213 protected abstract bool ReleaseHandle ();
215 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
216 protected void SetHandle (IntPtr handle)
218 this.handle = handle;
221 public bool IsClosed {
222 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
224 return refcount <= 0;
228 public abstract bool IsInvalid {
229 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
235 if (owns_handle && !IsInvalid){
237 handle = invalid_handle_value;