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