[project @ 2005-06-27 22:31:41 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 newConcForeignPtr p finalizer
102   = do fObj <- newForeignPtr_ p
103        addForeignPtrConcFinalizer fObj finalizer
104        return fObj
105
106 mallocForeignPtr :: Storable a => IO (ForeignPtr a)
107 -- ^ Allocate some memory and return a 'ForeignPtr' to it.  The memory
108 -- will be released automatically when the 'ForeignPtr' is discarded.
109 --
110 -- 'mallocForeignPtr' is equivalent to
111 --
112 -- >    do { p <- malloc; newForeignPtr finalizerFree p }
113 -- 
114 -- although it may be implemented differently internally: you may not
115 -- assume that the memory returned by 'mallocForeignPtr' has been
116 -- allocated with 'Foreign.Marshal.Alloc.malloc'.
117 mallocForeignPtr = doMalloc undefined
118   where doMalloc :: Storable b => b -> IO (ForeignPtr b)
119         doMalloc a = do
120           r <- newIORef []
121           IO $ \s ->
122             case newPinnedByteArray# size s of { (# s, mbarr# #) ->
123              (# s, ForeignPtr (byteArrayContents# (unsafeCoerce# mbarr#))
124                               (MallocPtr mbarr# r) #)
125             }
126             where (I# size) = sizeOf a
127
128 -- | This function is similar to 'mallocForeignPtr', except that the
129 -- size of the memory required is given explicitly as a number of bytes.
130 mallocForeignPtrBytes :: Int -> IO (ForeignPtr a)
131 mallocForeignPtrBytes (I# size) = do 
132   r <- newIORef []
133   IO $ \s ->
134      case newPinnedByteArray# size s      of { (# s, mbarr# #) ->
135        (# s, ForeignPtr (byteArrayContents# (unsafeCoerce# mbarr#))
136                         (MallocPtr mbarr# r) #)
137      }
138
139 addForeignPtrFinalizer :: FinalizerPtr a -> ForeignPtr a -> IO ()
140 -- ^This function adds a finalizer to the given foreign object.  The
141 -- finalizer will run /before/ all other finalizers for the same
142 -- object which have already been registered.
143 addForeignPtrFinalizer finalizer fptr = 
144   addForeignPtrConcFinalizer fptr 
145         (mkFinalizer finalizer (unsafeForeignPtrToPtr fptr))
146
147 addForeignPtrConcFinalizer :: ForeignPtr a -> IO () -> IO ()
148 -- ^This function adds a finalizer to the given @ForeignPtr@.  The
149 -- finalizer will run /before/ all other finalizers for the same
150 -- object which have already been registered.
151 --
152 -- This is a variant of @addForeignPtrFinalizer@, where the finalizer
153 -- is an arbitrary @IO@ action.  When it is invoked, the finalizer
154 -- will run in a new thread.
155 --
156 -- NB. Be very careful with these finalizers.  One common trap is that
157 -- if a finalizer references another finalized value, it does not
158 -- prevent that value from being finalized.  In particular, 'Handle's
159 -- are finalized objects, so a finalizer should not refer to a 'Handle'
160 -- (including @stdout@, @stdin@ or @stderr@).
161 --
162 addForeignPtrConcFinalizer (ForeignPtr a c) finalizer = 
163   addForeignPtrConcFinalizer_ c finalizer
164
165 addForeignPtrConcFinalizer_ f@(PlainForeignPtr r) finalizer = do
166   fs <- readIORef r
167   writeIORef r (finalizer : fs)
168   if (null fs)
169      then IO $ \s ->
170               case r of { IORef (STRef r#) ->
171               case mkWeak# r# () (foreignPtrFinalizer r) s of {  (# s1, w #) ->
172               (# s1, () #) }}
173      else return ()
174 addForeignPtrConcFinalizer_ f@(MallocPtr fo r) finalizer = do 
175   fs <- readIORef r
176   writeIORef r (finalizer : fs)
177   if (null fs)
178      then  IO $ \s -> 
179                case mkWeak# fo () (do foreignPtrFinalizer r; touch f) s of
180                   (# s1, w #) -> (# s1, () #)
181      else return ()
182
183 foreign import ccall "dynamic" 
184   mkFinalizer :: FinalizerPtr a -> Ptr a -> IO ()
185
186 foreignPtrFinalizer :: IORef [IO ()] -> IO ()
187 foreignPtrFinalizer r = do fs <- readIORef r; sequence_ fs
188
189 newForeignPtr_ :: Ptr a -> IO (ForeignPtr a)
190 -- ^Turns a plain memory reference into a foreign pointer that may be
191 -- associated with finalizers by using 'addForeignPtrFinalizer'.
192 newForeignPtr_ (Ptr obj) =  do
193   r <- newIORef []
194   return (ForeignPtr obj (PlainForeignPtr r))
195
196 touchForeignPtr :: ForeignPtr a -> IO ()
197 -- ^This function ensures that the foreign object in
198 -- question is alive at the given place in the sequence of IO
199 -- actions. In particular 'Foreign.ForeignPtr.withForeignPtr'
200 -- does a 'touchForeignPtr' after it
201 -- executes the user action.
202 -- 
203 -- Note that this function should not be used to express liveness
204 -- dependencies between 'ForeignPtr's.  For example, if the finalizer
205 -- for a 'ForeignPtr' @F1@ calls 'touchForeignPtr' on a second
206 -- 'ForeignPtr' @F2@, then the only guarantee is that the finalizer
207 -- for @F2@ is never started before the finalizer for @F1@.  They
208 -- might be started together if for example both @F1@ and @F2@ are
209 -- otherwise unreachable, and in that case the scheduler might end up
210 -- running the finalizer for @F2@ first.
211 --
212 -- In general, it is not recommended to use finalizers on separate
213 -- objects with ordering constraints between them.  To express the
214 -- ordering robustly requires explicit synchronisation using @MVar@s
215 -- between the finalizers, but even then the runtime sometimes runs
216 -- multiple finalizers sequentially in a single thread (for
217 -- performance reasons), so synchronisation between finalizers could
218 -- result in artificial deadlock.
219 --
220 touchForeignPtr (ForeignPtr fo r) = touch r
221
222 touch r = IO $ \s -> case touch# r s of s -> (# s, () #)
223
224 unsafeForeignPtrToPtr :: ForeignPtr a -> Ptr a
225 -- ^This function extracts the pointer component of a foreign
226 -- pointer.  This is a potentially dangerous operations, as if the
227 -- argument to 'unsafeForeignPtrToPtr' is the last usage
228 -- occurrence of the given foreign pointer, then its finalizer(s) will
229 -- be run, which potentially invalidates the plain pointer just
230 -- obtained.  Hence, 'touchForeignPtr' must be used
231 -- wherever it has to be guaranteed that the pointer lives on - i.e.,
232 -- has another usage occurrence.
233 --
234 -- To avoid subtle coding errors, hand written marshalling code
235 -- should preferably use 'Foreign.ForeignPtr.withForeignPtr' rather
236 -- than combinations of 'unsafeForeignPtrToPtr' and
237 -- 'touchForeignPtr'.  However, the later routines
238 -- are occasionally preferred in tool generated marshalling code.
239 unsafeForeignPtrToPtr (ForeignPtr fo r) = Ptr fo
240
241 castForeignPtr :: ForeignPtr a -> ForeignPtr b
242 -- ^This function casts a 'ForeignPtr'
243 -- parameterised by one type into another type.
244 castForeignPtr f = unsafeCoerce# f
245
246 -- | Causes the finalizers associated with a foreign pointer to be run
247 -- immediately.
248 finalizeForeignPtr :: ForeignPtr a -> IO ()
249 finalizeForeignPtr (ForeignPtr _ foreignPtr) = do
250         finalizers <- readIORef refFinalizers
251         sequence_ finalizers
252         writeIORef refFinalizers []
253         where
254                 refFinalizers = case foreignPtr of
255                         (PlainForeignPtr ref) -> ref
256                         (MallocPtr  _ ref) -> ref