Remove redundant imports, now that NoImplicitPrelude does not imply RebindableSyntax
[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.IORef
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
153           | I# size < 0 = error "mallocForeignPtr: size must be >= 0"
154           | otherwise = do
155           r <- newIORef (NoFinalizers, [])
156           IO $ \s ->
157             case newAlignedPinnedByteArray# size align s of { (# s', mbarr# #) ->
158              (# s', ForeignPtr (byteArrayContents# (unsafeCoerce# mbarr#))
159                                (MallocPtr mbarr# r) #)
160             }
161             where !(I# size)  = sizeOf a
162                   !(I# align) = alignment a
163
164 -- | This function is similar to 'mallocForeignPtr', except that the
165 -- size of the memory required is given explicitly as a number of bytes.
166 mallocForeignPtrBytes :: Int -> IO (ForeignPtr a)
167 mallocForeignPtrBytes size | size < 0 =
168   error "mallocForeignPtrBytes: size must be >= 0"
169 mallocForeignPtrBytes (I# size) = do 
170   r <- newIORef (NoFinalizers, [])
171   IO $ \s ->
172      case newPinnedByteArray# size s      of { (# s', mbarr# #) ->
173        (# s', ForeignPtr (byteArrayContents# (unsafeCoerce# mbarr#))
174                          (MallocPtr mbarr# r) #)
175      }
176
177 -- | Allocate some memory and return a 'ForeignPtr' to it.  The memory
178 -- will be released automatically when the 'ForeignPtr' is discarded.
179 --
180 -- GHC notes: 'mallocPlainForeignPtr' has a heavily optimised
181 -- implementation in GHC.  It uses pinned memory in the garbage
182 -- collected heap, as for mallocForeignPtr. Unlike mallocForeignPtr, a
183 -- ForeignPtr created with mallocPlainForeignPtr carries no finalizers.
184 -- It is not possible to add a finalizer to a ForeignPtr created with
185 -- mallocPlainForeignPtr. This is useful for ForeignPtrs that will live
186 -- only inside Haskell (such as those created for packed strings).
187 -- Attempts to add a finalizer to a ForeignPtr created this way, or to
188 -- finalize such a pointer, will throw an exception.
189 -- 
190 mallocPlainForeignPtr :: Storable a => IO (ForeignPtr a)
191 mallocPlainForeignPtr = doMalloc undefined
192   where doMalloc :: Storable b => b -> IO (ForeignPtr b)
193         doMalloc a
194           | I# size < 0 = error "mallocForeignPtr: size must be >= 0"
195           | otherwise = IO $ \s ->
196             case newAlignedPinnedByteArray# size align s of { (# s', mbarr# #) ->
197              (# s', ForeignPtr (byteArrayContents# (unsafeCoerce# mbarr#))
198                                (PlainPtr mbarr#) #)
199             }
200             where !(I# size)  = sizeOf a
201                   !(I# align) = alignment a
202
203 -- | This function is similar to 'mallocForeignPtrBytes', except that
204 -- the internally an optimised ForeignPtr representation with no
205 -- finalizer is used. Attempts to add a finalizer will cause an
206 -- exception to be thrown.
207 mallocPlainForeignPtrBytes :: Int -> IO (ForeignPtr a)
208 mallocPlainForeignPtrBytes size | size < 0 =
209   error "mallocPlainForeignPtrBytes: size must be >= 0"
210 mallocPlainForeignPtrBytes (I# size) = IO $ \s ->
211     case newPinnedByteArray# size s      of { (# s', mbarr# #) ->
212        (# s', ForeignPtr (byteArrayContents# (unsafeCoerce# mbarr#))
213                          (PlainPtr mbarr#) #)
214      }
215
216 addForeignPtrFinalizer :: FinalizerPtr a -> ForeignPtr a -> IO ()
217 -- ^This function adds a finalizer to the given foreign object.  The
218 -- finalizer will run /before/ all other finalizers for the same
219 -- object which have already been registered.
220 addForeignPtrFinalizer (FunPtr fp) (ForeignPtr p c) = case c of
221   PlainForeignPtr r -> f r >> return ()
222   MallocPtr     _ r -> f r >> return ()
223   _ -> error "GHC.ForeignPtr: attempt to add a finalizer to a plain pointer"
224  where
225     f r =
226       noMixing CFinalizers r $
227         IO $ \s ->
228           case r of { IORef (STRef r#) ->
229           case mkWeakForeignEnv# r# () fp p 0# nullAddr# s of { (# s1, w #) ->
230           (# s1, finalizeForeign w #) }}
231
232 addForeignPtrFinalizerEnv ::
233   FinalizerEnvPtr env a -> Ptr env -> ForeignPtr a -> IO ()
234 -- ^ Like 'addForeignPtrFinalizerEnv' but allows the finalizer to be
235 -- passed an additional environment parameter to be passed to the
236 -- finalizer.  The environment passed to the finalizer is fixed by the
237 -- second argument to 'addForeignPtrFinalizerEnv'
238 addForeignPtrFinalizerEnv (FunPtr fp) (Ptr ep) (ForeignPtr p c) = case c of
239   PlainForeignPtr r -> f r >> return ()
240   MallocPtr     _ r -> f r >> return ()
241   _ -> error "GHC.ForeignPtr: attempt to add a finalizer to a plain pointer"
242  where
243     f r =
244       noMixing CFinalizers r $
245         IO $ \s ->
246           case r of { IORef (STRef r#) ->
247           case mkWeakForeignEnv# r# () fp p 1# ep s of { (# s1, w #) ->
248           (# s1, finalizeForeign w #) }}
249
250 finalizeForeign :: Weak# () -> IO ()
251 finalizeForeign w = IO $ \s ->
252   case finalizeWeak# w s of
253     (# s1, 0#, _ #) -> (# s1, () #)
254     (# s1, _ , f #) -> f s1
255
256 addForeignPtrConcFinalizer :: ForeignPtr a -> IO () -> IO ()
257 -- ^This function adds a finalizer to the given @ForeignPtr@.  The
258 -- finalizer will run /before/ all other finalizers for the same
259 -- object which have already been registered.
260 --
261 -- This is a variant of @addForeignPtrFinalizer@, where the finalizer
262 -- is an arbitrary @IO@ action.  When it is invoked, the finalizer
263 -- will run in a new thread.
264 --
265 -- NB. Be very careful with these finalizers.  One common trap is that
266 -- if a finalizer references another finalized value, it does not
267 -- prevent that value from being finalized.  In particular, 'Handle's
268 -- are finalized objects, so a finalizer should not refer to a 'Handle'
269 -- (including @stdout@, @stdin@ or @stderr@).
270 --
271 addForeignPtrConcFinalizer (ForeignPtr _ c) finalizer = 
272   addForeignPtrConcFinalizer_ c finalizer
273
274 addForeignPtrConcFinalizer_ :: ForeignPtrContents -> IO () -> IO ()
275 addForeignPtrConcFinalizer_ (PlainForeignPtr r) finalizer = do
276   noFinalizers <- noMixing HaskellFinalizers r (return finalizer)
277   if noFinalizers
278      then IO $ \s ->
279               case r of { IORef (STRef r#) ->
280               case mkWeak# r# () (foreignPtrFinalizer r) s of {  (# s1, _ #) ->
281               (# s1, () #) }}
282      else return ()
283 addForeignPtrConcFinalizer_ f@(MallocPtr fo r) finalizer = do
284   noFinalizers <- noMixing HaskellFinalizers r (return finalizer)
285   if noFinalizers
286      then  IO $ \s -> 
287                case mkWeak# fo () (do foreignPtrFinalizer r; touch f) s of
288                   (# s1, _ #) -> (# s1, () #)
289      else return ()
290
291 addForeignPtrConcFinalizer_ _ _ =
292   error "GHC.ForeignPtr: attempt to add a finalizer to plain pointer"
293
294 noMixing ::
295   Finalizers -> IORef (Finalizers, [IO ()]) -> IO (IO ()) -> IO Bool
296 noMixing ftype0 r mkF = do
297   (ftype, fs) <- readIORef r
298   if ftype /= NoFinalizers && ftype /= ftype0
299      then error ("GHC.ForeignPtr: attempt to mix Haskell and C finalizers " ++
300                  "in the same ForeignPtr")
301      else do
302        f <- mkF
303        writeIORef r (ftype0, f : fs)
304        return (null fs)
305
306 foreignPtrFinalizer :: IORef (Finalizers, [IO ()]) -> IO ()
307 foreignPtrFinalizer r = do (_, fs) <- readIORef r; sequence_ fs
308
309 newForeignPtr_ :: Ptr a -> IO (ForeignPtr a)
310 -- ^Turns a plain memory reference into a foreign pointer that may be
311 -- associated with finalizers by using 'addForeignPtrFinalizer'.
312 newForeignPtr_ (Ptr obj) =  do
313   r <- newIORef (NoFinalizers, [])
314   return (ForeignPtr obj (PlainForeignPtr r))
315
316 touchForeignPtr :: ForeignPtr a -> IO ()
317 -- ^This function ensures that the foreign object in
318 -- question is alive at the given place in the sequence of IO
319 -- actions. In particular 'Foreign.ForeignPtr.withForeignPtr'
320 -- does a 'touchForeignPtr' after it
321 -- executes the user action.
322 -- 
323 -- Note that this function should not be used to express dependencies
324 -- between finalizers on 'ForeignPtr's.  For example, if the finalizer
325 -- for a 'ForeignPtr' @F1@ calls 'touchForeignPtr' on a second
326 -- 'ForeignPtr' @F2@, then the only guarantee is that the finalizer
327 -- for @F2@ is never started before the finalizer for @F1@.  They
328 -- might be started together if for example both @F1@ and @F2@ are
329 -- otherwise unreachable, and in that case the scheduler might end up
330 -- running the finalizer for @F2@ first.
331 --
332 -- In general, it is not recommended to use finalizers on separate
333 -- objects with ordering constraints between them.  To express the
334 -- ordering robustly requires explicit synchronisation using @MVar@s
335 -- between the finalizers, but even then the runtime sometimes runs
336 -- multiple finalizers sequentially in a single thread (for
337 -- performance reasons), so synchronisation between finalizers could
338 -- result in artificial deadlock.  Another alternative is to use
339 -- explicit reference counting.
340 --
341 touchForeignPtr (ForeignPtr _ r) = touch r
342
343 touch :: ForeignPtrContents -> IO ()
344 touch r = IO $ \s -> case touch# r s of s' -> (# s', () #)
345
346 unsafeForeignPtrToPtr :: ForeignPtr a -> Ptr a
347 -- ^This function extracts the pointer component of a foreign
348 -- pointer.  This is a potentially dangerous operations, as if the
349 -- argument to 'unsafeForeignPtrToPtr' is the last usage
350 -- occurrence of the given foreign pointer, then its finalizer(s) will
351 -- be run, which potentially invalidates the plain pointer just
352 -- obtained.  Hence, 'touchForeignPtr' must be used
353 -- wherever it has to be guaranteed that the pointer lives on - i.e.,
354 -- has another usage occurrence.
355 --
356 -- To avoid subtle coding errors, hand written marshalling code
357 -- should preferably use 'Foreign.ForeignPtr.withForeignPtr' rather
358 -- than combinations of 'unsafeForeignPtrToPtr' and
359 -- 'touchForeignPtr'.  However, the latter routines
360 -- are occasionally preferred in tool generated marshalling code.
361 unsafeForeignPtrToPtr (ForeignPtr fo _) = Ptr fo
362
363 castForeignPtr :: ForeignPtr a -> ForeignPtr b
364 -- ^This function casts a 'ForeignPtr'
365 -- parameterised by one type into another type.
366 castForeignPtr f = unsafeCoerce# f
367
368 -- | Causes the finalizers associated with a foreign pointer to be run
369 -- immediately.
370 finalizeForeignPtr :: ForeignPtr a -> IO ()
371 finalizeForeignPtr (ForeignPtr _ (PlainPtr _)) = return () -- no effect
372 finalizeForeignPtr (ForeignPtr _ foreignPtr) = do
373         (ftype, finalizers) <- readIORef refFinalizers
374         sequence_ finalizers
375         writeIORef refFinalizers (ftype, [])
376         where
377                 refFinalizers = case foreignPtr of
378                         (PlainForeignPtr ref) -> ref
379                         (MallocPtr     _ ref) -> ref
380                         PlainPtr _            ->
381                             error "finalizeForeignPtr PlainPtr"
382