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