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