Add Haddock `/Since: 4.5.[01].0/` comments to symbols
[packages/base.git] / GHC / ForeignPtr.hs
1 {-# LANGUAGE Unsafe #-}
2 {-# LANGUAGE NoImplicitPrelude
3 , BangPatterns
4 , MagicHash
5 , UnboxedTuples
6 #-}
7 {-# OPTIONS_HADDOCK hide #-}
8 {-# LANGUAGE DeriveDataTypeable, StandaloneDeriving #-}
9
10 -----------------------------------------------------------------------------
11 -- |
12 -- Module : GHC.ForeignPtr
13 -- Copyright : (c) The University of Glasgow, 1992-2003
14 -- License : see libraries/base/LICENSE
15 --
16 -- Maintainer : cvs-ghc@haskell.org
17 -- Stability : internal
18 -- Portability : non-portable (GHC extensions)
19 --
20 -- GHC's implementation of the 'ForeignPtr' data type.
21 --
22 -----------------------------------------------------------------------------
23
24 -- #hide
25 module GHC.ForeignPtr
26 (
27 ForeignPtr(..),
28 ForeignPtrContents(..),
29 FinalizerPtr,
30 FinalizerEnvPtr,
31 newForeignPtr_,
32 mallocForeignPtr,
33 mallocPlainForeignPtr,
34 mallocForeignPtrBytes,
35 mallocPlainForeignPtrBytes,
36 mallocForeignPtrAlignedBytes,
37 mallocPlainForeignPtrAlignedBytes,
38 addForeignPtrFinalizer,
39 addForeignPtrFinalizerEnv,
40 touchForeignPtr,
41 unsafeForeignPtrToPtr,
42 castForeignPtr,
43 newConcForeignPtr,
44 addForeignPtrConcFinalizer,
45 finalizeForeignPtr
46 ) where
47
48 import Control.Monad ( sequence_ )
49 import Foreign.Storable
50 import Data.Typeable
51
52 import GHC.Show
53 import GHC.Base
54 import GHC.IORef
55 import GHC.STRef ( STRef(..) )
56 import GHC.Ptr ( Ptr(..), FunPtr(..) )
57
58 -- |The type 'ForeignPtr' represents references to objects that are
59 -- maintained in a foreign language, i.e., that are not part of the
60 -- data structures usually managed by the Haskell storage manager.
61 -- The essential difference between 'ForeignPtr's and vanilla memory
62 -- references of type @Ptr a@ is that the former may be associated
63 -- with /finalizers/. A finalizer is a routine that is invoked when
64 -- the Haskell storage manager detects that - within the Haskell heap
65 -- and stack - there are no more references left that are pointing to
66 -- the 'ForeignPtr'. Typically, the finalizer will, then, invoke
67 -- routines in the foreign language that free the resources bound by
68 -- the foreign object.
69 --
70 -- The 'ForeignPtr' is parameterised in the same way as 'Ptr'. The
71 -- type argument of 'ForeignPtr' should normally be an instance of
72 -- class 'Storable'.
73 --
74 data ForeignPtr a = ForeignPtr Addr# ForeignPtrContents
75 deriving Typeable
76 -- we cache the Addr# in the ForeignPtr object, but attach
77 -- the finalizer to the IORef (or the MutableByteArray# in
78 -- the case of a MallocPtr). The aim of the representation
79 -- is to make withForeignPtr efficient; in fact, withForeignPtr
80 -- should be just as efficient as unpacking a Ptr, and multiple
81 -- withForeignPtrs can share an unpacked ForeignPtr. Note
82 -- that touchForeignPtr only has to touch the ForeignPtrContents
83 -- object, because that ensures that whatever the finalizer is
84 -- attached to is kept alive.
85
86 data Finalizers
87 = NoFinalizers
88 | CFinalizers (Weak# ())
89 | HaskellFinalizers [IO ()]
90
91 data ForeignPtrContents
92 = PlainForeignPtr !(IORef Finalizers)
93 | MallocPtr (MutableByteArray# RealWorld) !(IORef Finalizers)
94 | PlainPtr (MutableByteArray# RealWorld)
95
96 instance Eq (ForeignPtr a) where
97 p == q = unsafeForeignPtrToPtr p == unsafeForeignPtrToPtr q
98
99 instance Ord (ForeignPtr a) where
100 compare p q = compare (unsafeForeignPtrToPtr p) (unsafeForeignPtrToPtr q)
101
102 instance Show (ForeignPtr a) where
103 showsPrec p f = showsPrec p (unsafeForeignPtrToPtr f)
104
105
106 -- |A finalizer is represented as a pointer to a foreign function that, at
107 -- finalisation time, gets as an argument a plain pointer variant of the
108 -- foreign pointer that the finalizer is associated with.
109 --
110 -- Note that the foreign function /must/ use the @ccall@ calling convention.
111 --
112 type FinalizerPtr a = FunPtr (Ptr a -> IO ())
113 type FinalizerEnvPtr env a = FunPtr (Ptr env -> Ptr a -> IO ())
114
115 newConcForeignPtr :: Ptr a -> IO () -> IO (ForeignPtr a)
116 --
117 -- ^Turns a plain memory reference into a foreign object by
118 -- associating a finalizer - given by the monadic operation - with the
119 -- reference. The storage manager will start the finalizer, in a
120 -- separate thread, some time after the last reference to the
121 -- @ForeignPtr@ is dropped. There is no guarantee of promptness, and
122 -- in fact there is no guarantee that the finalizer will eventually
123 -- run at all.
124 --
125 -- Note that references from a finalizer do not necessarily prevent
126 -- another object from being finalized. If A's finalizer refers to B
127 -- (perhaps using 'touchForeignPtr', then the only guarantee is that
128 -- B's finalizer will never be started before A's. If both A and B
129 -- are unreachable, then both finalizers will start together. See
130 -- 'touchForeignPtr' for more on finalizer ordering.
131 --
132 newConcForeignPtr p finalizer
133 = do fObj <- newForeignPtr_ p
134 addForeignPtrConcFinalizer fObj finalizer
135 return fObj
136
137 mallocForeignPtr :: Storable a => IO (ForeignPtr a)
138 -- ^ Allocate some memory and return a 'ForeignPtr' to it. The memory
139 -- will be released automatically when the 'ForeignPtr' is discarded.
140 --
141 -- 'mallocForeignPtr' is equivalent to
142 --
143 -- > do { p <- malloc; newForeignPtr finalizerFree p }
144 --
145 -- although it may be implemented differently internally: you may not
146 -- assume that the memory returned by 'mallocForeignPtr' has been
147 -- allocated with 'Foreign.Marshal.Alloc.malloc'.
148 --
149 -- GHC notes: 'mallocForeignPtr' has a heavily optimised
150 -- implementation in GHC. It uses pinned memory in the garbage
151 -- collected heap, so the 'ForeignPtr' does not require a finalizer to
152 -- free the memory. Use of 'mallocForeignPtr' and associated
153 -- functions is strongly recommended in preference to 'newForeignPtr'
154 -- with a finalizer.
155 --
156 mallocForeignPtr = doMalloc undefined
157 where doMalloc :: Storable b => b -> IO (ForeignPtr b)
158 doMalloc a
159 | I# size < 0 = error "mallocForeignPtr: size must be >= 0"
160 | otherwise = do
161 r <- newIORef NoFinalizers
162 IO $ \s ->
163 case newAlignedPinnedByteArray# size align s of { (# s', mbarr# #) ->
164 (# s', ForeignPtr (byteArrayContents# (unsafeCoerce# mbarr#))
165 (MallocPtr mbarr# r) #)
166 }
167 where !(I# size) = sizeOf a
168 !(I# align) = alignment a
169
170 -- | This function is similar to 'mallocForeignPtr', except that the
171 -- size of the memory required is given explicitly as a number of bytes.
172 mallocForeignPtrBytes :: Int -> IO (ForeignPtr a)
173 mallocForeignPtrBytes size | size < 0 =
174 error "mallocForeignPtrBytes: size must be >= 0"
175 mallocForeignPtrBytes (I# size) = do
176 r <- newIORef NoFinalizers
177 IO $ \s ->
178 case newPinnedByteArray# size s of { (# s', mbarr# #) ->
179 (# s', ForeignPtr (byteArrayContents# (unsafeCoerce# mbarr#))
180 (MallocPtr mbarr# r) #)
181 }
182
183 -- | This function is similar to 'mallocForeignPtrBytes', except that the
184 -- size and alignment of the memory required is given explicitly as numbers of
185 -- bytes.
186 mallocForeignPtrAlignedBytes :: Int -> Int -> IO (ForeignPtr a)
187 mallocForeignPtrAlignedBytes size _align | size < 0 =
188 error "mallocForeignPtrAlignedBytes: size must be >= 0"
189 mallocForeignPtrAlignedBytes (I# size) (I# align) = do
190 r <- newIORef NoFinalizers
191 IO $ \s ->
192 case newAlignedPinnedByteArray# size align s of { (# s', mbarr# #) ->
193 (# s', ForeignPtr (byteArrayContents# (unsafeCoerce# mbarr#))
194 (MallocPtr mbarr# r) #)
195 }
196
197 -- | Allocate some memory and return a 'ForeignPtr' to it. The memory
198 -- will be released automatically when the 'ForeignPtr' is discarded.
199 --
200 -- GHC notes: 'mallocPlainForeignPtr' has a heavily optimised
201 -- implementation in GHC. It uses pinned memory in the garbage
202 -- collected heap, as for mallocForeignPtr. Unlike mallocForeignPtr, a
203 -- ForeignPtr created with mallocPlainForeignPtr carries no finalizers.
204 -- It is not possible to add a finalizer to a ForeignPtr created with
205 -- mallocPlainForeignPtr. This is useful for ForeignPtrs that will live
206 -- only inside Haskell (such as those created for packed strings).
207 -- Attempts to add a finalizer to a ForeignPtr created this way, or to
208 -- finalize such a pointer, will throw an exception.
209 --
210 mallocPlainForeignPtr :: Storable a => IO (ForeignPtr a)
211 mallocPlainForeignPtr = doMalloc undefined
212 where doMalloc :: Storable b => b -> IO (ForeignPtr b)
213 doMalloc a
214 | I# size < 0 = error "mallocForeignPtr: size must be >= 0"
215 | otherwise = IO $ \s ->
216 case newAlignedPinnedByteArray# size align s of { (# s', mbarr# #) ->
217 (# s', ForeignPtr (byteArrayContents# (unsafeCoerce# mbarr#))
218 (PlainPtr mbarr#) #)
219 }
220 where !(I# size) = sizeOf a
221 !(I# align) = alignment a
222
223 -- | This function is similar to 'mallocForeignPtrBytes', except that
224 -- the internally an optimised ForeignPtr representation with no
225 -- finalizer is used. Attempts to add a finalizer will cause an
226 -- exception to be thrown.
227 mallocPlainForeignPtrBytes :: Int -> IO (ForeignPtr a)
228 mallocPlainForeignPtrBytes size | size < 0 =
229 error "mallocPlainForeignPtrBytes: size must be >= 0"
230 mallocPlainForeignPtrBytes (I# size) = IO $ \s ->
231 case newPinnedByteArray# size s of { (# s', mbarr# #) ->
232 (# s', ForeignPtr (byteArrayContents# (unsafeCoerce# mbarr#))
233 (PlainPtr mbarr#) #)
234 }
235
236 -- | This function is similar to 'mallocForeignPtrAlignedBytes', except that
237 -- the internally an optimised ForeignPtr representation with no
238 -- finalizer is used. Attempts to add a finalizer will cause an
239 -- exception to be thrown.
240 mallocPlainForeignPtrAlignedBytes :: Int -> Int -> IO (ForeignPtr a)
241 mallocPlainForeignPtrAlignedBytes size _align | size < 0 =
242 error "mallocPlainForeignPtrAlignedBytes: size must be >= 0"
243 mallocPlainForeignPtrAlignedBytes (I# size) (I# align) = IO $ \s ->
244 case newAlignedPinnedByteArray# size align s of { (# s', mbarr# #) ->
245 (# s', ForeignPtr (byteArrayContents# (unsafeCoerce# mbarr#))
246 (PlainPtr mbarr#) #)
247 }
248
249 addForeignPtrFinalizer :: FinalizerPtr a -> ForeignPtr a -> IO ()
250 -- ^This function adds a finalizer to the given foreign object. The
251 -- finalizer will run /before/ all other finalizers for the same
252 -- object which have already been registered.
253 addForeignPtrFinalizer (FunPtr fp) (ForeignPtr p c) = case c of
254 PlainForeignPtr r -> f r >> return ()
255 MallocPtr _ r -> f r >> return ()
256 _ -> error "GHC.ForeignPtr: attempt to add a finalizer to a plain pointer"
257 where
258 f r = insertCFinalizer r fp 0# nullAddr# p
259
260 addForeignPtrFinalizerEnv ::
261 FinalizerEnvPtr env a -> Ptr env -> ForeignPtr a -> IO ()
262 -- ^ Like 'addForeignPtrFinalizerEnv' but allows the finalizer to be
263 -- passed an additional environment parameter to be passed to the
264 -- finalizer. The environment passed to the finalizer is fixed by the
265 -- second argument to 'addForeignPtrFinalizerEnv'
266 addForeignPtrFinalizerEnv (FunPtr fp) (Ptr ep) (ForeignPtr p c) = case c of
267 PlainForeignPtr r -> f r >> return ()
268 MallocPtr _ r -> f r >> return ()
269 _ -> error "GHC.ForeignPtr: attempt to add a finalizer to a plain pointer"
270 where
271 f r = insertCFinalizer r fp 1# ep p
272
273 addForeignPtrConcFinalizer :: ForeignPtr a -> IO () -> IO ()
274 -- ^This function adds a finalizer to the given @ForeignPtr@. The
275 -- finalizer will run /before/ all other finalizers for the same
276 -- object which have already been registered.
277 --
278 -- This is a variant of @addForeignPtrFinalizer@, where the finalizer
279 -- is an arbitrary @IO@ action. When it is invoked, the finalizer
280 -- will run in a new thread.
281 --
282 -- NB. Be very careful with these finalizers. One common trap is that
283 -- if a finalizer references another finalized value, it does not
284 -- prevent that value from being finalized. In particular, 'Handle's
285 -- are finalized objects, so a finalizer should not refer to a 'Handle'
286 -- (including @stdout@, @stdin@ or @stderr@).
287 --
288 addForeignPtrConcFinalizer (ForeignPtr _ c) finalizer =
289 addForeignPtrConcFinalizer_ c finalizer
290
291 addForeignPtrConcFinalizer_ :: ForeignPtrContents -> IO () -> IO ()
292 addForeignPtrConcFinalizer_ (PlainForeignPtr r) finalizer = do
293 noFinalizers <- insertHaskellFinalizer r finalizer
294 if noFinalizers
295 then IO $ \s ->
296 case r of { IORef (STRef r#) ->
297 case mkWeak# r# () (foreignPtrFinalizer r) s of { (# s1, _ #) ->
298 (# s1, () #) }}
299 else return ()
300 addForeignPtrConcFinalizer_ f@(MallocPtr fo r) finalizer = do
301 noFinalizers <- insertHaskellFinalizer r finalizer
302 if noFinalizers
303 then IO $ \s ->
304 case mkWeak# fo () (do foreignPtrFinalizer r; touch f) s of
305 (# s1, _ #) -> (# s1, () #)
306 else return ()
307
308 addForeignPtrConcFinalizer_ _ _ =
309 error "GHC.ForeignPtr: attempt to add a finalizer to plain pointer"
310
311 insertHaskellFinalizer :: IORef Finalizers -> IO () -> IO Bool
312 insertHaskellFinalizer r f = do
313 !wasEmpty <- atomicModifyIORef r $ \finalizers -> case finalizers of
314 NoFinalizers -> (HaskellFinalizers [f], True)
315 HaskellFinalizers fs -> (HaskellFinalizers (f:fs), False)
316 _ -> noMixingError
317 return wasEmpty
318
319 -- | A box around Weak#, private to this module.
320 data MyWeak = MyWeak (Weak# ())
321
322 insertCFinalizer ::
323 IORef Finalizers -> Addr# -> Int# -> Addr# -> Addr# -> IO ()
324 insertCFinalizer r fp flag ep p = do
325 MyWeak w <- ensureCFinalizerWeak r
326 IO $ \s -> case addCFinalizerToWeak# fp p flag ep w s of
327 (# s1, 1# #) -> (# s1, () #)
328
329 -- Failed to add the finalizer because some other thread
330 -- has finalized w by calling foreignPtrFinalizer. We retry now.
331 -- This won't be an infinite loop because that thread must have
332 -- replaced the content of r before calling finalizeWeak#.
333 (# s1, _ #) -> unIO (insertCFinalizer r fp flag ep p) s1
334
335 ensureCFinalizerWeak :: IORef Finalizers -> IO MyWeak
336 ensureCFinalizerWeak ref@(IORef (STRef r#)) = do
337 fin <- readIORef ref
338 case fin of
339 CFinalizers weak -> return (MyWeak weak)
340 HaskellFinalizers{} -> noMixingError
341 NoFinalizers -> IO $ \s ->
342 case mkWeakNoFinalizer# r# () s of { (# s1, w #) ->
343 case atomicModifyMutVar# r# (update w) s1 of
344 { (# s2, (weak, needKill ) #) ->
345 if needKill
346 then case finalizeWeak# w s2 of { (# s3, _, _ #) ->
347 (# s3, weak #) }
348 else (# s2, weak #) }}
349 where
350 update _ fin@(CFinalizers w) = (fin, (MyWeak w, True))
351 update w NoFinalizers = (CFinalizers w, (MyWeak w, False))
352 update _ _ = noMixingError
353
354 noMixingError :: a
355 noMixingError = error $
356 "GHC.ForeignPtr: attempt to mix Haskell and C finalizers " ++
357 "in the same ForeignPtr"
358
359 foreignPtrFinalizer :: IORef Finalizers -> IO ()
360 foreignPtrFinalizer r = do
361 fs <- atomicModifyIORef r $ \fs -> (NoFinalizers, fs) -- atomic, see #7170
362 case fs of
363 NoFinalizers -> return ()
364 CFinalizers w -> IO $ \s -> case finalizeWeak# w s of
365 (# s1, 1#, f #) -> f s1
366 (# s1, _, _ #) -> (# s1, () #)
367 HaskellFinalizers actions -> sequence_ actions
368
369 newForeignPtr_ :: Ptr a -> IO (ForeignPtr a)
370 -- ^Turns a plain memory reference into a foreign pointer that may be
371 -- associated with finalizers by using 'addForeignPtrFinalizer'.
372 newForeignPtr_ (Ptr obj) = do
373 r <- newIORef NoFinalizers
374 return (ForeignPtr obj (PlainForeignPtr r))
375
376 touchForeignPtr :: ForeignPtr a -> IO ()
377 -- ^This function ensures that the foreign object in
378 -- question is alive at the given place in the sequence of IO
379 -- actions. In particular 'Foreign.ForeignPtr.withForeignPtr'
380 -- does a 'touchForeignPtr' after it
381 -- executes the user action.
382 --
383 -- Note that this function should not be used to express dependencies
384 -- between finalizers on 'ForeignPtr's. For example, if the finalizer
385 -- for a 'ForeignPtr' @F1@ calls 'touchForeignPtr' on a second
386 -- 'ForeignPtr' @F2@, then the only guarantee is that the finalizer
387 -- for @F2@ is never started before the finalizer for @F1@. They
388 -- might be started together if for example both @F1@ and @F2@ are
389 -- otherwise unreachable, and in that case the scheduler might end up
390 -- running the finalizer for @F2@ first.
391 --
392 -- In general, it is not recommended to use finalizers on separate
393 -- objects with ordering constraints between them. To express the
394 -- ordering robustly requires explicit synchronisation using @MVar@s
395 -- between the finalizers, but even then the runtime sometimes runs
396 -- multiple finalizers sequentially in a single thread (for
397 -- performance reasons), so synchronisation between finalizers could
398 -- result in artificial deadlock. Another alternative is to use
399 -- explicit reference counting.
400 --
401 touchForeignPtr (ForeignPtr _ r) = touch r
402
403 touch :: ForeignPtrContents -> IO ()
404 touch r = IO $ \s -> case touch# r s of s' -> (# s', () #)
405
406 unsafeForeignPtrToPtr :: ForeignPtr a -> Ptr a
407 -- ^This function extracts the pointer component of a foreign
408 -- pointer. This is a potentially dangerous operations, as if the
409 -- argument to 'unsafeForeignPtrToPtr' is the last usage
410 -- occurrence of the given foreign pointer, then its finalizer(s) will
411 -- be run, which potentially invalidates the plain pointer just
412 -- obtained. Hence, 'touchForeignPtr' must be used
413 -- wherever it has to be guaranteed that the pointer lives on - i.e.,
414 -- has another usage occurrence.
415 --
416 -- To avoid subtle coding errors, hand written marshalling code
417 -- should preferably use 'Foreign.ForeignPtr.withForeignPtr' rather
418 -- than combinations of 'unsafeForeignPtrToPtr' and
419 -- 'touchForeignPtr'. However, the latter routines
420 -- are occasionally preferred in tool generated marshalling code.
421 unsafeForeignPtrToPtr (ForeignPtr fo _) = Ptr fo
422
423 castForeignPtr :: ForeignPtr a -> ForeignPtr b
424 -- ^This function casts a 'ForeignPtr'
425 -- parameterised by one type into another type.
426 castForeignPtr f = unsafeCoerce# f
427
428 -- | Causes the finalizers associated with a foreign pointer to be run
429 -- immediately.
430 finalizeForeignPtr :: ForeignPtr a -> IO ()
431 finalizeForeignPtr (ForeignPtr _ (PlainPtr _)) = return () -- no effect
432 finalizeForeignPtr (ForeignPtr _ foreignPtr) = foreignPtrFinalizer refFinalizers
433 where
434 refFinalizers = case foreignPtr of
435 (PlainForeignPtr ref) -> ref
436 (MallocPtr _ ref) -> ref
437 PlainPtr _ ->
438 error "finalizeForeignPtr PlainPtr"
439