[project @ 2004-12-23 00:02:41 by ralf]
[ghc.git] / libraries / base / GHC / ForeignPtr.hs
1 {-# OPTIONS -fno-implicit-prelude #-}
2 -----------------------------------------------------------------------------
3 -- |
4 -- Module : GHC.ForeignPtr
5 -- Copyright : (c) The University of Glasgow, 1992-2003
6 -- License : see libraries/base/LICENSE
7 --
8 -- Maintainer : cvs-ghc@haskell.org
9 -- Stability : internal
10 -- Portability : non-portable (GHC extensions)
11 --
12 -- GHC's implementation of the 'ForeignPtr' data type.
13 --
14 -----------------------------------------------------------------------------
15
16 module GHC.ForeignPtr
17 (
18 ForeignPtr(..),
19 FinalizerPtr,
20 newForeignPtr_,
21 mallocForeignPtr,
22 mallocForeignPtrBytes,
23 addForeignPtrFinalizer,
24 touchForeignPtr,
25 unsafeForeignPtrToPtr,
26 castForeignPtr,
27 newConcForeignPtr,
28 addForeignPtrConcFinalizer,
29 finalizeForeignPtr
30 ) where
31
32 import Control.Monad ( sequence_ )
33 import Foreign.Ptr
34 import Foreign.Storable
35 import Data.Typeable
36
37 import GHC.List ( null )
38 import GHC.Base
39 import GHC.IOBase
40 import GHC.Ptr ( Ptr(..) )
41 import GHC.Err
42 import GHC.Show
43
44 -- |The type 'ForeignPtr' represents references to objects that are
45 -- maintained in a foreign language, i.e., that are not part of the
46 -- data structures usually managed by the Haskell storage manager.
47 -- The essential difference between 'ForeignPtr's and vanilla memory
48 -- references of type @Ptr a@ is that the former may be associated
49 -- with /finalizers/. A finalizer is a routine that is invoked when
50 -- the Haskell storage manager detects that - within the Haskell heap
51 -- and stack - there are no more references left that are pointing to
52 -- the 'ForeignPtr'. Typically, the finalizer will, then, invoke
53 -- routines in the foreign language that free the resources bound by
54 -- the foreign object.
55 --
56 -- The 'ForeignPtr' is parameterised in the same way as 'Ptr'. The
57 -- type argument of 'ForeignPtr' should normally be an instance of
58 -- class 'Storable'.
59 --
60 data ForeignPtr a
61 = ForeignPtr ForeignObj# !(IORef [IO ()])
62 | MallocPtr (MutableByteArray# RealWorld) !(IORef [IO ()])
63
64 instance Eq (ForeignPtr a) where
65 p == q = unsafeForeignPtrToPtr p == unsafeForeignPtrToPtr q
66
67 instance Ord (ForeignPtr a) where
68 compare p q = compare (unsafeForeignPtrToPtr p) (unsafeForeignPtrToPtr q)
69
70 instance Show (ForeignPtr a) where
71 showsPrec p f = showsPrec p (unsafeForeignPtrToPtr f)
72
73 #include "Typeable.h"
74 INSTANCE_TYPEABLE1(ForeignPtr,foreignPtrTc,"ForeignPtr")
75
76 -- |A Finalizer is represented as a pointer to a foreign function that, at
77 -- finalisation time, gets as an argument a plain pointer variant of the
78 -- foreign pointer that the finalizer is associated with.
79 --
80 type FinalizerPtr a = FunPtr (Ptr a -> IO ())
81
82 newConcForeignPtr :: Ptr a -> IO () -> IO (ForeignPtr a)
83 --
84 -- ^Turns a plain memory reference into a foreign object by
85 -- associating a finalizer - given by the monadic operation - with the
86 -- reference. The storage manager will start the finalizer, in a
87 -- separate thread, some time after the last reference to the
88 -- @ForeignPtr@ is dropped. There is no guarantee of promptness, and
89 -- in fact there is no guarantee that the finalizer will eventually
90 -- run at all.
91 --
92 newConcForeignPtr p finalizer
93 = do fObj <- newForeignPtr_ p
94 addForeignPtrConcFinalizer fObj finalizer
95 return fObj
96
97 mallocForeignPtr :: Storable a => IO (ForeignPtr a)
98 -- ^ Allocate some memory and return a 'ForeignPtr' to it. The memory
99 -- will be released automatically when the 'ForeignPtr' is discarded.
100 --
101 -- 'mallocForeignPtr' is equivalent to
102 --
103 -- > do { p <- malloc; newForeignPtr finalizerFree p }
104 --
105 -- although it may be implemented differently internally: you may not
106 -- assume that the memory returned by 'mallocForeignPtr' has been
107 -- allocated with 'Foreign.Marshal.Alloc.malloc'.
108 mallocForeignPtr = doMalloc undefined
109 where doMalloc :: Storable b => b -> IO (ForeignPtr b)
110 doMalloc a = do
111 r <- newIORef []
112 IO $ \s ->
113 case newPinnedByteArray# size s of { (# s, mbarr# #) ->
114 (# s, MallocPtr mbarr# r #)
115 }
116 where (I# size) = sizeOf a
117
118 -- | This function is similar to 'mallocForeignPtr', except that the
119 -- size of the memory required is given explicitly as a number of bytes.
120 mallocForeignPtrBytes :: Int -> IO (ForeignPtr a)
121 mallocForeignPtrBytes (I# size) = do
122 r <- newIORef []
123 IO $ \s ->
124 case newPinnedByteArray# size s of { (# s, mbarr# #) ->
125 (# s, MallocPtr mbarr# r #)
126 }
127
128 addForeignPtrFinalizer :: FinalizerPtr a -> ForeignPtr a -> IO ()
129 -- ^This function adds a finalizer to the given foreign object. The
130 -- finalizer will run /before/ all other finalizers for the same
131 -- object which have already been registered.
132 addForeignPtrFinalizer finalizer fptr =
133 addForeignPtrConcFinalizer fptr
134 (mkFinalizer finalizer (unsafeForeignPtrToPtr fptr))
135
136 addForeignPtrConcFinalizer :: ForeignPtr a -> IO () -> IO ()
137 -- ^This function adds a finalizer to the given @ForeignPtr@. The
138 -- finalizer will run /before/ all other finalizers for the same
139 -- object which have already been registered.
140 --
141 -- This is a variant of @addForeignPtrFinalizer@, where the finalizer
142 -- is an arbitrary @IO@ action. When it is invoked, the finalizer
143 -- will run in a new thread.
144 --
145 -- NB. Be very careful with these finalizers. One common trap is that
146 -- if a finalizer references another finalized value, it does not
147 -- prevent that value from being finalized. In particular, 'Handle's
148 -- are finalized objects, so a finalizer should not refer to a 'Handle'
149 -- (including @stdout@, @stdin@ or @stderr@).
150 --
151 addForeignPtrConcFinalizer f@(ForeignPtr fo r) finalizer = do
152 fs <- readIORef r
153 writeIORef r (finalizer : fs)
154 if (null fs)
155 then IO $ \s ->
156 let p = unsafeForeignPtrToPtr f in
157 case mkWeak# fo () (foreignPtrFinalizer r p) s of
158 (# s1, w #) -> (# s1, () #)
159 else return ()
160 addForeignPtrConcFinalizer f@(MallocPtr fo r) finalizer = do
161 fs <- readIORef r
162 writeIORef r (finalizer : fs)
163 if (null fs)
164 then IO $ \s ->
165 let p = unsafeForeignPtrToPtr f in
166 case mkWeak# fo () (do foreignPtrFinalizer r p
167 touchPinnedByteArray# fo) s of
168 (# s1, w #) -> (# s1, () #)
169 else return ()
170
171 foreign import ccall "dynamic"
172 mkFinalizer :: FinalizerPtr a -> Ptr a -> IO ()
173
174 foreignPtrFinalizer :: IORef [IO ()] -> Ptr a -> IO ()
175 foreignPtrFinalizer r p = do
176 fs <- readIORef r
177 sequence_ fs
178
179 newForeignPtr_ :: Ptr a -> IO (ForeignPtr a)
180 -- ^Turns a plain memory reference into a foreign pointer that may be
181 -- associated with finalizers by using 'addForeignPtrFinalizer'.
182 newForeignPtr_ (Ptr obj) = do
183 r <- newIORef []
184 IO $ \ s# ->
185 case mkForeignObj# obj s# of
186 (# s1#, fo# #) -> (# s1#, ForeignPtr fo# r #)
187
188 touchPinnedByteArray# :: MutableByteArray# RealWorld -> IO ()
189 touchPinnedByteArray# ba# = IO $ \s -> case touch# ba# s of s -> (# s, () #)
190
191 touchForeignPtr :: ForeignPtr a -> IO ()
192 -- ^This function ensures that the foreign object in
193 -- question is alive at the given place in the sequence of IO
194 -- actions. In particular 'Foreign.ForeignPtr.withForeignPtr'
195 -- does a 'touchForeignPtr' after it
196 -- executes the user action.
197 --
198 -- Note that this function should not be used to express liveness
199 -- dependencies between 'ForeignPtr's. For example, if the finalizer
200 -- for a 'ForeignPtr' @F1@ calls 'touchForeignPtr' on a second
201 -- 'ForeignPtr' @F2@, then the only guarantee is that the finalizer
202 -- for @F2@ is never started before the finalizer for @F1@. They
203 -- might be started together if for example both @F1@ and @F2@ are
204 -- otherwise unreachable, and in that case the scheduler might end up
205 -- running the finalizer for @F2@ first.
206 --
207 -- In general, it is not recommended to use finalizers on separate
208 -- objects with ordering constraints between them. To express the
209 -- ordering robustly requires explicit synchronisation using @MVar@s
210 -- between the finalizers, but even then the runtime sometimes runs
211 -- multiple finalizers sequentially in a single thread (for
212 -- performance reasons), so synchronisation between finalizers could
213 -- result in artificial deadlock.
214 --
215 touchForeignPtr (ForeignPtr fo r)
216 = IO $ \s -> case touch# fo s of s -> (# s, () #)
217 touchForeignPtr (MallocPtr fo r)
218 = touchPinnedByteArray# fo
219
220 unsafeForeignPtrToPtr :: ForeignPtr a -> Ptr a
221 -- ^This function extracts the pointer component of a foreign
222 -- pointer. This is a potentially dangerous operations, as if the
223 -- argument to 'unsafeForeignPtrToPtr' is the last usage
224 -- occurrence of the given foreign pointer, then its finalizer(s) will
225 -- be run, which potentially invalidates the plain pointer just
226 -- obtained. Hence, 'touchForeignPtr' must be used
227 -- wherever it has to be guaranteed that the pointer lives on - i.e.,
228 -- has another usage occurrence.
229 --
230 -- To avoid subtle coding errors, hand written marshalling code
231 -- should preferably use 'Foreign.ForeignPtr.withForeignPtr' rather
232 -- than combinations of 'unsafeForeignPtrToPtr' and
233 -- 'touchForeignPtr'. However, the later routines
234 -- are occasionally preferred in tool generated marshalling code.
235 unsafeForeignPtrToPtr (ForeignPtr fo r) = Ptr (foreignObjToAddr# fo)
236 unsafeForeignPtrToPtr (MallocPtr fo r) = Ptr (byteArrayContents# (unsafeCoerce# fo))
237
238 castForeignPtr :: ForeignPtr a -> ForeignPtr b
239 -- ^This function casts a 'ForeignPtr'
240 -- parameterised by one type into another type.
241 castForeignPtr f = unsafeCoerce# f
242
243 -- | Causes a the finalizers associated with a foreign pointer to be run
244 -- immediately.
245 finalizeForeignPtr :: ForeignPtr a -> IO ()
246 finalizeForeignPtr foreignPtr = do
247 finalizers <- readIORef refFinalizers
248 sequence_ finalizers
249 writeIORef refFinalizers []
250 where
251 refFinalizers = case foreignPtr of
252 (ForeignPtr _ ref) -> ref
253 (MallocPtr _ ref) -> ref