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