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