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