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