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