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