2008-12-08 Ivan N. Zlatev <contact@i-nz.net>
[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 #if NET_2_0
47 using System;
48 using System.Runtime.InteropServices;
49 using System.Runtime.ConstrainedExecution;
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                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
66                 protected SafeHandle (IntPtr invalidHandleValue, bool ownsHandle)
67                 {
68                         invalid_handle_value = invalidHandleValue;
69                         owns_handle = ownsHandle;
70                         refcount = 1;
71                 }
72
73                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
74                 public void Close ()
75                 {
76                         if (refcount == 0)
77                                 throw new ObjectDisposedException (GetType ().FullName);
78
79                         int newcount, current;
80                         do {
81                                 current = refcount;
82                                 newcount = current-1;
83                         } while (Interlocked.CompareExchange (ref refcount, newcount, current) != current);
84
85                         if (newcount == 0 && owns_handle && !IsInvalid){
86                                 ReleaseHandle ();
87                                 handle = invalid_handle_value;
88                         }
89                 }
90
91                 //
92                 // I do not know when we could not be able to increment the
93                 // reference count and set success to false.   It might just
94                 // be a convention used for the following code pattern:
95                 //
96                 // bool release = false
97                 // try { x.DangerousAddRef (ref release); ... }
98                 // finally { if (release) x.DangerousRelease (); }
99                 //
100                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
101                 public void DangerousAddRef (ref bool success)
102                 {
103                         if (refcount == 0)
104                                 throw new ObjectDisposedException (GetType ().FullName);
105
106                         int newcount, current;
107                         do {
108                                 current = refcount;
109                                 newcount = current + 1;
110                                 
111                                 if (handle == invalid_handle_value || current == 0){
112                                         //
113                                         // In MS, calling sf.Close () followed by a call
114                                         // to P/Invoke with SafeHandles throws this, but
115                                         // am left wondering: when would "success" be
116                                         // set to false?
117                                         //
118                                         throw new ObjectDisposedException (GetType ().FullName);
119                                 }
120                         } while (Interlocked.CompareExchange (ref refcount, newcount, current) != current);
121                         success = true;
122                 }
123
124                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
125                 public IntPtr DangerousGetHandle ()
126                 {
127                         if (refcount == 0){
128                                 throw new ObjectDisposedException (GetType ().FullName);
129                         }
130
131                         return handle;
132                 }
133
134                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
135                 public void DangerousRelease ()
136                 {
137                         if (refcount == 0)
138                                 throw new ObjectDisposedException (GetType ().FullName);
139
140                         int newcount, current;
141                         do {
142                                 current = refcount;
143                                 newcount = current-1;
144                         } while (Interlocked.CompareExchange (ref refcount, newcount, current) != current);
145
146                         if (newcount == 0 && owns_handle && !IsInvalid){
147                                 ReleaseHandle ();
148                                 handle = invalid_handle_value;
149                         }
150                 }
151
152                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
153                 public void Dispose ()
154                 {
155                         Dispose (true);
156                         GC.SuppressFinalize (this);
157                 }
158
159                 //
160                 // See documentation, this invalidates the handle without
161                 // closing it.
162                 //
163                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
164                 public void SetHandleAsInvalid ()
165                 {
166                         handle = invalid_handle_value;
167                 }
168                 
169                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
170                 protected virtual void Dispose (bool disposing)
171                 {
172                         if (disposing)
173                                 Close ();
174                         else {
175                                 //
176                                 // The docs say `never call this with disposing=false',
177                                 // the question is whether:
178                                 //   * The runtime will ever call Dipose(false) for SafeHandles (special runtime case)
179                                 //   * Whether we should just call ReleaseHandle regardless?
180                                 //
181                         }
182                 }
183
184                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
185                 protected abstract bool ReleaseHandle ();
186
187                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
188                 protected void SetHandle (IntPtr handle)
189                 {
190                         this.handle = handle;
191                 }
192
193                 public bool IsClosed {
194                         [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
195                         get {
196                                 return refcount == 0;
197                         }
198                 }
199
200                 public abstract bool IsInvalid {
201                         [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
202                         get;
203                 }
204
205                 ~SafeHandle ()
206                 {
207                         if (owns_handle && !IsInvalid){
208                                 ReleaseHandle ();
209                                 handle = invalid_handle_value;
210                         }
211                 }
212         }
213 }
214 #endif