[corlib] SafeHandle dispose can be called multiple times after closing. Fixes #25850
[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                 int refcount;
65                 bool owns_handle;
66                 
67 #if NET_2_1
68                 protected SafeHandle ()
69                 {
70                         throw new NotImplementedException ();
71                 }
72 #endif
73                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
74                 protected SafeHandle (IntPtr invalidHandleValue, bool ownsHandle)
75                 {
76                         handle = invalidHandleValue;
77
78                         if (!ownsHandle) {
79                                 GC.SuppressFinalize (this);
80                         } else {
81                                 owns_handle = true;
82                         }
83
84                         refcount = 1;
85                 }
86
87                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
88                 public void Close ()
89                 {
90                         if (refcount <= 0) {
91                                 if (refcount == 0)
92                                         throw new ObjectDisposedException (GetType ().FullName);
93
94                                 return;
95                         }
96
97                         int newcount = 0, current = 0;
98                         bool registered = false;
99                         RuntimeHelpers.PrepareConstrainedRegions ();
100                         try {
101                                 do {
102                                         current = refcount;
103                                         newcount = current-1;
104
105                                         // perform changes in finally to avoid async interruptions
106                                         try {}
107                                         finally {
108                                                 if (Interlocked.CompareExchange (ref refcount, newcount, current) == current)
109                                                         registered = true;
110                                         }
111                                 } while (!registered);
112                         } finally {
113                                 if (registered && newcount == 0) {
114                                         if (owns_handle && !IsInvalid)
115                                                 ReleaseHandle ();
116                                         refcount = -1;
117                                 }
118                         }
119                 }
120
121                 //
122                 // I do not know when we could not be able to increment the
123                 // reference count and set success to false.   It might just
124                 // be a convention used for the following code pattern:
125                 //
126                 // bool release = false
127                 // try { x.DangerousAddRef (ref release); ... }
128                 // finally { if (release) x.DangerousRelease (); }
129                 //
130                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
131                 public void DangerousAddRef (ref bool success)
132                 {
133                         if (refcount <= 0)
134                                 throw new ObjectDisposedException (GetType ().FullName);
135
136                         bool registered = false;
137                         int newcount, current;
138                         do {
139                                 current = refcount;
140                                 newcount = current + 1;
141                                 
142                                 if (current <= 0){
143                                         //
144                                         // In MS, calling sf.Close () followed by a call
145                                         // to P/Invoke with SafeHandles throws this, but
146                                         // am left wondering: when would "success" be
147                                         // set to false?
148                                         //
149                                         throw new ObjectDisposedException (GetType ().FullName);
150                                 }
151
152                                 // perform changes in finally to avoid async interruptions
153                                 RuntimeHelpers.PrepareConstrainedRegions ();
154                                 try {}
155                                 finally {
156                                         if (Interlocked.CompareExchange (ref refcount, newcount, current) == current)
157                                                 registered = success = true;
158                                 }
159                         } while (!registered);
160                 }
161
162                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
163                 public IntPtr DangerousGetHandle ()
164                 {
165                         return handle;
166                 }
167
168                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
169                 public void DangerousRelease ()
170                 {
171                         if (refcount <= 0)
172                                 throw new ObjectDisposedException (GetType ().FullName);
173
174                         int newcount, current;
175                         do {
176                                 current = refcount;
177                                 newcount = current-1;
178                         } while (Interlocked.CompareExchange (ref refcount, newcount, current) != current);
179
180                         if (newcount == 0 && owns_handle && !IsInvalid){
181                                 ReleaseHandle ();
182                         }
183                 }
184
185                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
186                 public void Dispose ()
187                 {
188                         Dispose (true);
189                         GC.SuppressFinalize (this);
190                 }
191
192                 //
193                 // See documentation, this invalidates the handle without
194                 // closing it.
195                 //
196                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
197                 public void SetHandleAsInvalid ()
198                 {
199                         refcount = -1;
200                 }
201                 
202                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
203                 protected virtual void Dispose (bool disposing)
204                 {
205                         if (disposing) {
206                                 Close ();
207                         } else {
208                                 if (owns_handle && !IsInvalid){
209                                         ReleaseHandle ();
210                                 }
211                         }
212                 }
213
214                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
215                 protected abstract bool ReleaseHandle ();
216
217                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
218                 protected void SetHandle (IntPtr handle)
219                 {
220                         this.handle = handle;
221                 }
222
223                 public bool IsClosed {
224                         [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
225                         get {
226                                 return refcount <= 0;
227                         }
228                 }
229
230                 public abstract bool IsInvalid {
231                         [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
232                         get;
233                 }
234
235                 ~SafeHandle ()
236                 {
237                         Dispose (false);
238                 }
239         }
240 }