[SafeHandle] Protect Close against asynchronous exceptions
[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 // On implementing SafeHandles:
34 //     http://blogs.msdn.com/bclteam/archive/2005/03/15/396335.aspx
35 //
36 // Issues:
37 //     The System.Runtime.ConstrainedExecution.ReliabilityContractAttribute has
38 //     not been applied to any APIs here yet.
39 //
40 //     TODO: Although DangerousAddRef has been implemented, I need to
41 //     find out whether the runtime performs the P/Invoke if the
42 //     handle has been disposed already.
43 //
44 //
45
46 using System;
47 using System.Runtime.InteropServices;
48 using System.Runtime.ConstrainedExecution;
49 using System.Runtime.CompilerServices;
50 using System.Threading;
51
52 namespace System.Runtime.InteropServices
53 {
54         public abstract class SafeHandle : CriticalFinalizerObject, IDisposable {
55                 //
56                 // Warning: the offset of handle is mapped inside the runtime
57                 // if you move this, you must updated the runtime definition of
58                 // MonoSafeHandle
59                 //
60                 protected IntPtr handle;
61                 IntPtr invalid_handle_value;
62                 int refcount = 0;
63                 bool owns_handle;
64                 
65 #if NET_2_1
66                 protected SafeHandle ()
67                 {
68                         throw new NotImplementedException ();
69                 }
70 #endif
71                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
72                 protected SafeHandle (IntPtr invalidHandleValue, bool ownsHandle)
73                 {
74                         invalid_handle_value = invalidHandleValue;
75                         owns_handle = ownsHandle;
76                         refcount = 1;
77                 }
78
79                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
80                 public void Close ()
81                 {
82                         if (refcount == 0)
83                                 throw new ObjectDisposedException (GetType ().FullName);
84
85                         int newcount = 0, current = 0;
86                         bool registered = false;
87                         RuntimeHelpers.PrepareConstrainedRegions ();
88                         try {
89                                 do {
90                                         current = refcount;
91                                         newcount = current-1;
92
93                                         try {}
94                                         finally {
95                                                 if (Interlocked.CompareExchange (ref refcount, newcount, current) == current)
96                                                         registered = true;
97                                         }
98                                 } while (!registered);
99                         } finally {
100                                 if (registered && newcount == 0 && owns_handle && !IsInvalid){
101                                         ReleaseHandle ();
102                                         handle = invalid_handle_value;
103                                         refcount = -1;
104                                 }
105                         }
106                 }
107
108                 //
109                 // I do not know when we could not be able to increment the
110                 // reference count and set success to false.   It might just
111                 // be a convention used for the following code pattern:
112                 //
113                 // bool release = false
114                 // try { x.DangerousAddRef (ref release); ... }
115                 // finally { if (release) x.DangerousRelease (); }
116                 //
117                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
118                 public void DangerousAddRef (ref bool success)
119                 {
120                         if (refcount <= 0)
121                                 throw new ObjectDisposedException (GetType ().FullName);
122
123                         int newcount, current;
124                         do {
125                                 current = refcount;
126                                 newcount = current + 1;
127                                 
128                                 if (current <= 0){
129                                         //
130                                         // In MS, calling sf.Close () followed by a call
131                                         // to P/Invoke with SafeHandles throws this, but
132                                         // am left wondering: when would "success" be
133                                         // set to false?
134                                         //
135                                         throw new ObjectDisposedException (GetType ().FullName);
136                                 }
137                         } while (Interlocked.CompareExchange (ref refcount, newcount, current) != current);
138                         success = true;
139                 }
140
141                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
142                 public IntPtr DangerousGetHandle ()
143                 {
144                         if (refcount <= 0){
145                                 throw new ObjectDisposedException (GetType ().FullName);
146                         }
147
148                         return handle;
149                 }
150
151                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
152                 public void DangerousRelease ()
153                 {
154                         if (refcount <= 0)
155                                 throw new ObjectDisposedException (GetType ().FullName);
156
157                         int newcount, current;
158                         do {
159                                 current = refcount;
160                                 newcount = current-1;
161                         } while (Interlocked.CompareExchange (ref refcount, newcount, current) != current);
162
163                         if (newcount == 0 && owns_handle && !IsInvalid){
164                                 ReleaseHandle ();
165                                 handle = invalid_handle_value;
166                         }
167                 }
168
169                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
170                 public void Dispose ()
171                 {
172                         Dispose (true);
173                         GC.SuppressFinalize (this);
174                 }
175
176                 //
177                 // See documentation, this invalidates the handle without
178                 // closing it.
179                 //
180                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
181                 public void SetHandleAsInvalid ()
182                 {
183                         handle = invalid_handle_value;
184                 }
185                 
186                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
187                 protected virtual void Dispose (bool disposing)
188                 {
189                         if (disposing)
190                                 Close ();
191                         else {
192                                 //
193                                 // The docs say `never call this with disposing=false',
194                                 // the question is whether:
195                                 //   * The runtime will ever call Dipose(false) for SafeHandles (special runtime case)
196                                 //   * Whether we should just call ReleaseHandle regardless?
197                                 //
198                         }
199                 }
200
201                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
202                 protected abstract bool ReleaseHandle ();
203
204                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
205                 protected void SetHandle (IntPtr handle)
206                 {
207                         this.handle = handle;
208                 }
209
210                 public bool IsClosed {
211                         [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
212                         get {
213                                 return refcount <= 0;
214                         }
215                 }
216
217                 public abstract bool IsInvalid {
218                         [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
219                         get;
220                 }
221
222                 ~SafeHandle ()
223                 {
224                         if (owns_handle && !IsInvalid){
225                                 ReleaseHandle ();
226                                 handle = invalid_handle_value;
227                         }
228                 }
229         }
230 }