[project @ 2005-07-27 10:04:26 by simonmar]
[ghc.git] / libraries / base / GHC / ForeignPtr.hs
1 {-# OPTIONS_GHC -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 -- #hide
17 module GHC.ForeignPtr
18 (
19 ForeignPtr(..),
20 FinalizerPtr,
21 newForeignPtr_,
22 mallocForeignPtr,
23 mallocForeignPtrBytes,
24 addForeignPtrFinalizer,
25 touchForeignPtr,
26 unsafeForeignPtrToPtr,
27 castForeignPtr,
28 newConcForeignPtr,
29 addForeignPtrConcFinalizer,
30 finalizeForeignPtr
31 ) where
32
33 import Control.Monad ( sequence_ )
34 import Foreign.Ptr
35 import Foreign.Storable
36
37 import GHC.Base
38 import GHC.IOBase
39 import GHC.STRef ( STRef(..) )
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 = ForeignPtr Addr# ForeignPtrContents
61 -- we cache the Addr# in the ForeignPtr object, but attach
62 -- the finalizer to the IORef (or the MutableByteArray# in
63 -- the case of a MallocPtr). The aim of the representation
64 -- is to make withForeignPtr efficient; in fact, withForeignPtr
65 -- should be just as efficient as unpacking a Ptr, and multiple
66 -- withForeignPtrs can share an unpacked ForeignPtr. Note
67 -- that touchForeignPtr only has to touch the ForeignPtrContents
68 -- object, because that ensures that whatever the finalizer is
69 -- attached to is kept alive.
70
71 data ForeignPtrContents
72 = PlainNoFinalizer
73 | PlainWithFinalizer !(IORef [IO ()])
74 | MallocPtrNoFinalizer (MutableByteArray# RealWorld)
75 | MallocPtrWithFinalizer (MutableByteArray# RealWorld) !(IORef [IO ()])
76 -- we optimise the no-finalizer case, which is especially common
77 -- with a MallocPtr. mallocForeignPtr doesn't have to create an
78 -- IORef, or set up a weak pointer.
79
80 instance Eq (ForeignPtr a) where
81 p == q = unsafeForeignPtrToPtr p == unsafeForeignPtrToPtr q
82
83 instance Ord (ForeignPtr a) where
84 compare p q = compare (unsafeForeignPtrToPtr p) (unsafeForeignPtrToPtr q)
85
86 instance Show (ForeignPtr a) where
87 showsPrec p f = showsPrec p (unsafeForeignPtrToPtr f)
88
89 -- |A Finalizer is represented as a pointer to a foreign function that, at
90 -- finalisation time, gets as an argument a plain pointer variant of the
91 -- foreign pointer that the finalizer is associated with.
92 --
93 type FinalizerPtr a = FunPtr (Ptr a -> IO ())
94
95 newConcForeignPtr :: Ptr a -> IO () -> IO (ForeignPtr a)
96 --
97 -- ^Turns a plain memory reference into a foreign object by
98 -- associating a finalizer - given by the monadic operation - with the
99 -- reference. The storage manager will start the finalizer, in a
100 -- separate thread, some time after the last reference to the
101 -- @ForeignPtr@ is dropped. There is no guarantee of promptness, and
102 -- in fact there is no guarantee that the finalizer will eventually
103 -- run at all.
104 --
105 -- Note that references from a finalizer do not necessarily prevent
106 -- another object from being finalized. If A's finalizer refers to B
107 -- (perhaps using 'touchForeignPtr', then the only guarantee is that
108 -- B's finalizer will never be started before A's. If both A and B
109 -- are unreachable, then both finalizers will start together. See
110 -- 'touchForeignPtr' for more on finalizer ordering.
111 --
112 newConcForeignPtr p finalizer
113 = do fObj <- newForeignPtr_ p
114 addForeignPtrConcFinalizer fObj finalizer
115 return fObj
116
117 mallocForeignPtr :: Storable a => IO (ForeignPtr a)
118 -- ^ Allocate some memory and return a 'ForeignPtr' to it. The memory
119 -- will be released automatically when the 'ForeignPtr' is discarded.
120 --
121 -- 'mallocForeignPtr' is equivalent to
122 --
123 -- > do { p <- malloc; newForeignPtr finalizerFree p }
124 --
125 -- although it may be implemented differently internally: you may not
126 -- assume that the memory returned by 'mallocForeignPtr' has been
127 -- allocated with 'Foreign.Marshal.Alloc.malloc'.
128 mallocForeignPtr = doMalloc undefined
129 where doMalloc :: Storable b => b -> IO (ForeignPtr b)
130 doMalloc a = do
131 IO $ \s ->
132 case newPinnedByteArray# size s of { (# s, mbarr# #) ->
133 (# s, ForeignPtr (byteArrayContents# (unsafeCoerce# mbarr#))
134 (MallocPtrNoFinalizer mbarr#) #)
135 }
136 where (I# size) = sizeOf a
137
138 -- | This function is similar to 'mallocForeignPtr', except that the
139 -- size of the memory required is given explicitly as a number of bytes.
140 mallocForeignPtrBytes :: Int -> IO (ForeignPtr a)
141 mallocForeignPtrBytes (I# size) = do
142 IO $ \s ->
143 case newPinnedByteArray# size s of { (# s, mbarr# #) ->
144 (# s, ForeignPtr (byteArrayContents# (unsafeCoerce# mbarr#))
145 (MallocPtrNoFinalizer mbarr#) #)
146 }
147
148 addForeignPtrFinalizer :: FinalizerPtr a -> ForeignPtr a -> IO ()
149 -- ^This function adds a finalizer to the given foreign object. The
150 -- finalizer will run /before/ all other finalizers for the same
151 -- object which have already been registered.
152 addForeignPtrFinalizer finalizer fptr =
153 addForeignPtrConcFinalizer fptr
154 (mkFinalizer finalizer (unsafeForeignPtrToPtr fptr))
155
156 addForeignPtrConcFinalizer :: ForeignPtr a -> IO () -> IO ()
157 -- ^This function adds a finalizer to the given @ForeignPtr@. The
158 -- finalizer will run /before/ all other finalizers for the same
159 -- object which have already been registered.
160 --
161 -- This is a variant of @addForeignPtrFinalizer@, where the finalizer
162 -- is an arbitrary @IO@ action. When it is invoked, the finalizer
163 -- will run in a new thread.
164 --
165 -- NB. Be very careful with these finalizers. One common trap is that
166 -- if a finalizer references another finalized value, it does not
167 -- prevent that value from being finalized. In particular, 'Handle's
168 -- are finalized objects, so a finalizer should not refer to a 'Handle'
169 -- (including @stdout@, @stdin@ or @stderr@).
170 --
171 addForeignPtrConcFinalizer (ForeignPtr a c) finalizer =
172 addForeignPtrConcFinalizer_ c finalizer
173
174 addForeignPtrConcFinalizer_ PlainNoFinalizer finalizer = do
175 r <- newIORef []
176 IO $ \s -> case r of { IORef (STRef r#) ->
177 case mkWeak# r# () (foreignPtrFinalizer r) s of { (# s1, w #) ->
178 (# s1, () #) }}
179 addForeignPtrConcFinalizer_ (PlainWithFinalizer r) finalizer
180
181 addForeignPtrConcFinalizer_ f@(PlainWithFinalizer r) finalizer = do
182 fs <- readIORef r
183 writeIORef r (finalizer : fs)
184
185 addForeignPtrConcFinalizer_ f@(MallocPtrNoFinalizer fo) finalizer = do
186 r <- newIORef []
187 IO $ \s -> case mkWeak# fo () (do foreignPtrFinalizer r; touch f) s of
188 (# s1, w #) -> (# s1, () #)
189 addForeignPtrConcFinalizer_ (MallocPtrWithFinalizer fo r) finalizer
190
191 addForeignPtrConcFinalizer_ f@(MallocPtrWithFinalizer fo r) finalizer = do
192 fs <- readIORef r
193 writeIORef r (finalizer : fs)
194
195 foreign import ccall "dynamic"
196 mkFinalizer :: FinalizerPtr a -> Ptr a -> IO ()
197
198 foreignPtrFinalizer :: IORef [IO ()] -> IO ()
199 foreignPtrFinalizer r = do fs <- readIORef r; sequence_ fs
200
201 newForeignPtr_ :: Ptr a -> IO (ForeignPtr a)
202 -- ^Turns a plain memory reference into a foreign pointer that may be
203 -- associated with finalizers by using 'addForeignPtrFinalizer'.
204 newForeignPtr_ (Ptr obj) = return (ForeignPtr obj PlainNoFinalizer)
205
206 touchForeignPtr :: ForeignPtr a -> IO ()
207 -- ^This function ensures that the foreign object in
208 -- question is alive at the given place in the sequence of IO
209 -- actions. In particular 'Foreign.ForeignPtr.withForeignPtr'
210 -- does a 'touchForeignPtr' after it
211 -- executes the user action.
212 --
213 -- Note that this function should not be used to express dependencies
214 -- between finalizers on 'ForeignPtr's. For example, if the finalizer
215 -- for a 'ForeignPtr' @F1@ calls 'touchForeignPtr' on a second
216 -- 'ForeignPtr' @F2@, then the only guarantee is that the finalizer
217 -- for @F2@ is never started before the finalizer for @F1@. They
218 -- might be started together if for example both @F1@ and @F2@ are
219 -- otherwise unreachable, and in that case the scheduler might end up
220 -- running the finalizer for @F2@ first.
221 --
222 -- In general, it is not recommended to use finalizers on separate
223 -- objects with ordering constraints between them. To express the
224 -- ordering robustly requires explicit synchronisation using @MVar@s
225 -- between the finalizers, but even then the runtime sometimes runs
226 -- multiple finalizers sequentially in a single thread (for
227 -- performance reasons), so synchronisation between finalizers could
228 -- result in artificial deadlock. Another alternative is to use
229 -- explicit reference counting.
230 --
231 touchForeignPtr (ForeignPtr fo r) = touch r
232
233 touch r = IO $ \s -> case touch# r s of s -> (# s, () #)
234
235 unsafeForeignPtrToPtr :: ForeignPtr a -> Ptr a
236 -- ^This function extracts the pointer component of a foreign
237 -- pointer. This is a potentially dangerous operations, as if the
238 -- argument to 'unsafeForeignPtrToPtr' is the last usage
239 -- occurrence of the given foreign pointer, then its finalizer(s) will
240 -- be run, which potentially invalidates the plain pointer just
241 -- obtained. Hence, 'touchForeignPtr' must be used
242 -- wherever it has to be guaranteed that the pointer lives on - i.e.,
243 -- has another usage occurrence.
244 --
245 -- To avoid subtle coding errors, hand written marshalling code
246 -- should preferably use 'Foreign.ForeignPtr.withForeignPtr' rather
247 -- than combinations of 'unsafeForeignPtrToPtr' and
248 -- 'touchForeignPtr'. However, the later routines
249 -- are occasionally preferred in tool generated marshalling code.
250 unsafeForeignPtrToPtr (ForeignPtr fo r) = Ptr fo
251
252 castForeignPtr :: ForeignPtr a -> ForeignPtr b
253 -- ^This function casts a 'ForeignPtr'
254 -- parameterised by one type into another type.
255 castForeignPtr f = unsafeCoerce# f
256
257 -- | Causes the finalizers associated with a foreign pointer to be run
258 -- immediately.
259 finalizeForeignPtr :: ForeignPtr a -> IO ()
260 finalizeForeignPtr (ForeignPtr _ contents) = do
261 case contents of
262 PlainNoFinalizer -> return ()
263 PlainWithFinalizer r -> runFinalizers r
264 MallocPtrNoFinalizer _ -> return ()
265 MallocPtrWithFinalizer _ r -> runFinalizers r
266 where
267 runFinalizers r = do
268 fs <- readIORef r
269 sequence_ fs
270 writeIORef r []