3 // Copyright (c) Microsoft Corporation. All rights reserved.
6 /*============================================================
11 ** A specially designed handle wrapper to ensure we never leak
12 ** an OS handle. The runtime treats this class specially during
13 ** P/Invoke marshaling and finalization. Users should write
14 ** subclasses of SafeHandle for each distinct handle type.
17 ===========================================================*/
19 namespace System.Runtime.InteropServices {
22 using System.Reflection;
23 using System.Threading;
24 using System.Security.Permissions;
26 using System.Runtime.CompilerServices;
28 using System.Runtime.ConstrainedExecution;
29 using System.Runtime.Versioning;
32 Problems addressed by the SafeHandle class:
33 1) Critical finalization - ensure we never leak OS resources in SQL. Done
34 without running truly arbitrary & unbounded amounts of managed code.
35 2) Reduced graph promotion - during finalization, keep object graph small
36 3) GC.KeepAlive behavior - P/Invoke vs. finalizer thread ---- (HandleRef)
37 4) Elimination of security ----s w/ explicit calls to Close (HandleProtector)
38 5) Enforcement of the above via the type system - Don't use IntPtr anymore.
39 6) Allows the handle lifetime to be controlled externally via a boolean.
41 Subclasses of SafeHandle will implement the ReleaseHandle abstract method
42 used to execute any code required to free the handle. This method will be
43 prepared as a constrained execution region at instance construction time
44 (along with all the methods in its statically determinable call graph). This
45 implies that we won't get any inconvenient jit allocation errors or rude
46 thread abort interrupts while releasing the handle but the user must still
47 write careful code to avoid injecting fault paths of their own (see the CER
48 spec for more details). In particular, any sub-methods you call should be
49 decorated with a reliability contract of the appropriate level. In most cases
51 ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)
52 Also, any P/Invoke methods should use the SuppressUnmanagedCodeSecurity
53 attribute to avoid a runtime security check that can also inject failures
54 (even if the check is guaranteed to pass).
56 The GC will run ReleaseHandle methods after any normal finalizers have been
57 run for objects that were collected at the same time. This ensures classes
58 like FileStream can run a normal finalizer to flush out existing buffered
59 data. This is key - it means adding this class to a class like FileStream does
60 not alter our current semantics w.r.t. finalization today.
62 Subclasses must also implement the IsInvalid property so that the
63 infrastructure can tell when critical finalization is actually required.
64 Again, this method is prepared ahead of time. It's envisioned that direct
65 subclasses of SafeHandle will provide an IsInvalid implementation that suits
66 the general type of handle they support (null is invalid, -1 is invalid etc.)
67 and then these classes will be further derived for specific safe handle types.
69 Most classes using SafeHandle should not provide a finalizer. If they do
70 need to do so (ie, for flushing out file buffers, needing to write some data
71 back into memory, etc), then they can provide a finalizer that will be
72 guaranteed to run before the SafeHandle's critical finalizer.
74 Note that SafeHandle's ReleaseHandle is called from a constrained execution
75 region, and is eagerly prepared before we create your class. This means you
76 should only call methods with an appropriate reliability contract from your
79 Subclasses are expected to be written as follows (note that
80 SuppressUnmanagedCodeSecurity should always be used on any P/Invoke methods
81 invoked as part of ReleaseHandle, in order to switch the security check from
82 runtime to jit time and thus remove a possible failure path from the
83 invocation of the method):
85 internal sealed MySafeHandleSubclass : SafeHandle {
86 // Called by P/Invoke when returning SafeHandles
87 private MySafeHandleSubclass() : base(IntPtr.Zero, true)
91 // If & only if you need to support user-supplied handles
92 internal MySafeHandleSubclass(IntPtr preexistingHandle, bool ownsHandle) : base(IntPtr.Zero, ownsHandle)
94 SetHandle(preexistingHandle);
97 // Do not provide a finalizer - SafeHandle's critical finalizer will
98 // call ReleaseHandle for you.
100 public override bool IsInvalid {
101 get { return handle == IntPtr.Zero; }
104 override protected bool ReleaseHandle()
106 return MyNativeMethods.CloseHandle(handle);
110 Then elsewhere to create one of these SafeHandles, define a method
111 with the following type of signature (CreateFile follows this model).
112 Note that when returning a SafeHandle like this, P/Invoke will call your
113 class's default constructor. Also, you probably want to define CloseHandle
114 somewhere, and remember to apply a reliability contract to it.
116 [SuppressUnmanagedCodeSecurity]
117 internal static class MyNativeMethods {
118 [DllImport("kernel32")]
119 private static extern MySafeHandleSubclass CreateHandle(int someState);
121 [DllImport("kernel32", SetLastError=true), ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
122 private static extern bool CloseHandle(IntPtr handle);
125 Drawbacks with this implementation:
126 1) Requires some magic to run the critical finalizer.
127 2) Requires more memory than just an IntPtr.
128 3) If you use DangerousAddRef and forget to call DangerousRelease, you can leak a SafeHandle. Use CER's & don't do that.
132 // This class should not be serializable - it's a handle. We require unmanaged
133 // code permission to subclass SafeHandle to prevent people from writing a
134 // subclass and suddenly being able to run arbitrary native code with the
135 // same signature as CloseHandle. This is technically a little redundant, but
136 // we'll do this to ensure we've cut off all attack vectors. Similarly, all
137 // methods have a link demand to ensure untrusted code cannot directly edit
138 // or alter a handle.
139 [System.Security.SecurityCritical] // auto-generated_required
141 [SecurityPermission(SecurityAction.InheritanceDemand, UnmanagedCode=true)]
143 public abstract partial class SafeHandle : CriticalFinalizerObject, IDisposable
145 // ! Do not add or rearrange fields as the EE depends on this layout.
146 //------------------------------------------------------------------
148 // FxCop thinks this field is marshaled and so it raises a CA2101 error unless
149 // we specify this. In practice this is never presented to Win32.
150 [MarshalAs(UnmanagedType.LPWStr)]
151 private String _stackTrace; // Where we allocated this SafeHandle.
153 protected IntPtr handle; // this must be protected so derived classes can use out params.
154 private int _state; // Combined ref count and closed/disposed flags (so we can atomically modify them).
155 private bool _ownsHandle; // Whether we can release this handle.
156 #pragma warning disable 414
157 private bool _fullyInitialized; // Whether constructor completed.
158 #pragma warning restore 414
160 // Creates a SafeHandle class. Users must then set the Handle property.
161 // To prevent the SafeHandle from being freed, write a subclass that
162 // doesn't define a finalizer.
163 [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
164 protected SafeHandle(IntPtr invalidHandleValue, bool ownsHandle)
166 handle = invalidHandleValue;
167 _state = 4; // Ref count 1 and not closed or disposed.
168 _ownsHandle = ownsHandle;
171 GC.SuppressFinalize(this);
174 if (BCLDebug.SafeHandleStackTracesEnabled)
175 _stackTrace = Environment.GetStackTrace(null, false);
177 _stackTrace = "For a stack trace showing who allocated this SafeHandle, set SafeHandleStackTraces to 1 and rerun your app.";
180 // Set this last to prevent SafeHandle's finalizer from freeing an
181 // invalid handle. This means we don't have to worry about
182 // ThreadAbortExceptions interrupting this constructor or the managed
183 // constructors on subclasses that call this constructor.
184 _fullyInitialized = true;
187 #if FEATURE_CORECLR || MOBILE
188 // Migrating InheritanceDemands requires this default ctor, so we can mark it critical
189 protected SafeHandle()
191 BCLDebug.Assert(false, "SafeHandle's protected default ctor should never be used!");
192 throw new NotImplementedException();
196 [System.Security.SecuritySafeCritical] // auto-generated
202 [ResourceExposure(ResourceScope.None)]
203 [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
204 [MethodImplAttribute(MethodImplOptions.InternalCall)]
205 extern void InternalFinalize();
207 [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
208 protected void SetHandle(IntPtr handle) {
209 this.handle = handle;
212 // This method is necessary for getting an IntPtr out of a SafeHandle.
213 // Used to tell whether a call to create the handle succeeded by comparing
214 // the handle against a known invalid value, and for backwards
215 // compatibility to support the handle properties returning IntPtrs on
216 // many of our Framework classes.
217 // Note that this method is dangerous for two reasons:
218 // 1) If the handle has been marked invalid with SetHandleasInvalid,
219 // DangerousGetHandle will still return the original handle value.
220 // 2) The handle returned may be recycled at any point. At best this means
221 // the handle might stop working suddenly. At worst, if the handle or
222 // the resource the handle represents is exposed to untrusted code in
223 // any way, this can lead to a handle recycling security attack (i.e. an
224 // untrusted caller can query data on the handle you've just returned
225 // and get back information for an entirely unrelated resource).
226 [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
227 [ResourceExposure(ResourceScope.None)]
228 public IntPtr DangerousGetHandle()
233 public bool IsClosed {
234 [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
235 get { return (_state & 1) == 1; }
238 public abstract bool IsInvalid {
239 [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
243 [System.Security.SecurityCritical] // auto-generated
244 [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
245 public void Close() {
249 [System.Security.SecuritySafeCritical] // auto-generated
250 [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
251 public void Dispose() {
255 [System.Security.SecurityCritical] // auto-generated
256 [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
257 protected virtual void Dispose(bool disposing)
265 [ResourceExposure(ResourceScope.None)]
266 [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
267 [MethodImplAttribute(MethodImplOptions.InternalCall)]
268 private extern void InternalDispose();
270 // This should only be called for cases when you know for a fact that
271 // your handle is invalid and you want to record that information.
272 // An example is calling a syscall and getting back ERROR_INVALID_HANDLE.
273 // This method will normally leak handles!
274 [System.Security.SecurityCritical] // auto-generated
275 [ResourceExposure(ResourceScope.None)]
276 [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
277 [MethodImplAttribute(MethodImplOptions.InternalCall)]
278 public extern void SetHandleAsInvalid();
280 // Implement this abstract method in your derived class to specify how to
281 // free the handle. Be careful not write any code that's subject to faults
282 // in this method (the runtime will prepare the infrastructure for you so
283 // that no jit allocations etc. will occur, but don't allocate memory unless
284 // you can deal with the failure and still free the handle).
285 // The boolean returned should be true for success and false if the runtime
286 // should fire a SafeHandleCriticalFailure MDA (CustomerDebugProbe) if that
288 [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
289 protected abstract bool ReleaseHandle();
291 // Add a reason why this handle should not be relinquished (i.e. have
292 // ReleaseHandle called on it). This method has dangerous in the name since
293 // it must always be used carefully (e.g. called within a CER) to avoid
294 // leakage of the handle. It returns a boolean indicating whether the
295 // increment was actually performed to make it easy for program logic to
296 // back out in failure cases (i.e. is a call to DangerousRelease needed).
297 // It is passed back via a ref parameter rather than as a direct return so
298 // that callers need not worry about the atomicity of calling the routine
299 // and assigning the return value to a variable (the variable should be
300 // explicitly set to false prior to the call). The only failure cases are
301 // when the method is interrupted prior to processing by a thread abort or
302 // when the handle has already been (or is in the process of being)
304 [System.Security.SecurityCritical] // auto-generated
305 [ResourceExposure(ResourceScope.None)]
306 [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
307 [MethodImplAttribute(MethodImplOptions.InternalCall)]
308 public extern void DangerousAddRef(ref bool success);
310 // Partner to DangerousAddRef. This should always be successful when used in
311 // a correct manner (i.e. matching a successful DangerousAddRef and called
312 // from a region such as a CER where a thread abort cannot interrupt
313 // processing). In the same way that unbalanced DangerousAddRef calls can
314 // cause resource leakage, unbalanced DangerousRelease calls may cause
315 // invalid handle states to become visible to other threads. This
316 // constitutes a potential security hole (via handle recycling) as well as a
317 // correctness problem -- so don't ever expose Dangerous* calls out to
319 [System.Security.SecurityCritical] // auto-generated
320 [ResourceExposure(ResourceScope.None)]
321 [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
322 [MethodImplAttribute(MethodImplOptions.InternalCall)]
323 public extern void DangerousRelease();