Merge remote branch 'upstream/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         public abstract class SafeHandle : CriticalFinalizerObject, IDisposable {
57                 //
58                 // Warning: the offset of handle is mapped inside the runtime
59                 // if you move this, you must updated the runtime definition of
60                 // MonoSafeHandle
61                 //
62                 protected IntPtr handle;
63                 IntPtr invalid_handle_value;
64                 int refcount = 0;
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                         invalid_handle_value = invalidHandleValue;
77                         owns_handle = ownsHandle;
78                         refcount = 1;
79                 }
80
81                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
82                 public void Close ()
83                 {
84                         if (refcount == 0)
85                                 throw new ObjectDisposedException (GetType ().FullName);
86
87                         int newcount = 0, current = 0;
88                         bool registered = false;
89                         RuntimeHelpers.PrepareConstrainedRegions ();
90                         try {
91                                 do {
92                                         current = refcount;
93                                         newcount = current-1;
94
95                                         // perform changes in finally to avoid async interruptions
96                                         try {}
97                                         finally {
98                                                 if (Interlocked.CompareExchange (ref refcount, newcount, current) == current)
99                                                         registered = true;
100                                         }
101                                 } while (!registered);
102                         } finally {
103                                 if (registered && newcount == 0 && owns_handle && !IsInvalid){
104                                         ReleaseHandle ();
105                                         handle = invalid_handle_value;
106                                         refcount = -1;
107                                 }
108                         }
109                 }
110
111                 //
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:
115                 //
116                 // bool release = false
117                 // try { x.DangerousAddRef (ref release); ... }
118                 // finally { if (release) x.DangerousRelease (); }
119                 //
120                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
121                 public void DangerousAddRef (ref bool success)
122                 {
123                         if (refcount <= 0)
124                                 throw new ObjectDisposedException (GetType ().FullName);
125
126                         bool registered = false;
127                         int newcount, current;
128                         do {
129                                 current = refcount;
130                                 newcount = current + 1;
131                                 
132                                 if (current <= 0){
133                                         //
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
137                                         // set to false?
138                                         //
139                                         throw new ObjectDisposedException (GetType ().FullName);
140                                 }
141
142                                 // perform changes in finally to avoid async interruptions
143                                 RuntimeHelpers.PrepareConstrainedRegions ();
144                                 try {}
145                                 finally {
146                                         if (Interlocked.CompareExchange (ref refcount, newcount, current) == current)
147                                                 registered = success = true;
148                                 }
149                         } while (!registered);
150                 }
151
152                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
153                 public IntPtr DangerousGetHandle ()
154                 {
155                         if (refcount <= 0){
156                                 throw new ObjectDisposedException (GetType ().FullName);
157                         }
158
159                         return handle;
160                 }
161
162                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
163                 public void DangerousRelease ()
164                 {
165                         if (refcount <= 0)
166                                 throw new ObjectDisposedException (GetType ().FullName);
167
168                         int newcount, current;
169                         do {
170                                 current = refcount;
171                                 newcount = current-1;
172                         } while (Interlocked.CompareExchange (ref refcount, newcount, current) != current);
173
174                         if (newcount == 0 && owns_handle && !IsInvalid){
175                                 ReleaseHandle ();
176                                 handle = invalid_handle_value;
177                         }
178                 }
179
180                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
181                 public void Dispose ()
182                 {
183                         Dispose (true);
184                         GC.SuppressFinalize (this);
185                 }
186
187                 //
188                 // See documentation, this invalidates the handle without
189                 // closing it.
190                 //
191                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
192                 public void SetHandleAsInvalid ()
193                 {
194                         handle = invalid_handle_value;
195                 }
196                 
197                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
198                 protected virtual void Dispose (bool disposing)
199                 {
200                         if (disposing)
201                                 Close ();
202                         else {
203                                 //
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?
208                                 //
209                         }
210                 }
211
212                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
213                 protected abstract bool ReleaseHandle ();
214
215                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
216                 protected void SetHandle (IntPtr handle)
217                 {
218                         this.handle = handle;
219                 }
220
221                 public bool IsClosed {
222                         [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
223                         get {
224                                 return refcount <= 0;
225                         }
226                 }
227
228                 public abstract bool IsInvalid {
229                         [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
230                         get;
231                 }
232
233                 ~SafeHandle ()
234                 {
235                         if (owns_handle && !IsInvalid){
236                                 ReleaseHandle ();
237                                 handle = invalid_handle_value;
238                         }
239                 }
240         }
241 }