[project @ 2004-03-24 16:59:51 by simonmar]
[ghc-base.git] / GHC / ForeignPtr.hs
1 {-# OPTIONS -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 module GHC.ForeignPtr
17   (
18         ForeignPtr(..),
19         FinalizerPtr,
20         newForeignPtr_,
21         mallocForeignPtr,
22         mallocForeignPtrBytes,
23         addForeignPtrFinalizer, 
24         touchForeignPtr,
25         unsafeForeignPtrToPtr,
26         castForeignPtr,
27         newConcForeignPtr,
28         addForeignPtrConcFinalizer,
29         finalizeForeignPtr
30   ) where
31
32 import Control.Monad    ( sequence_ )
33 import Foreign.Ptr
34 import Foreign.Storable
35 import Data.Typeable
36
37 import GHC.List         ( null )
38 import GHC.Base
39 import GHC.IOBase
40 import GHC.Ptr          ( Ptr(..) )
41 import GHC.Err
42 import GHC.Show
43
44 -- |The type 'ForeignPtr' represents references to objects that are
45 -- maintained in a foreign language, i.e., that are not part of the
46 -- data structures usually managed by the Haskell storage manager.
47 -- The essential difference between 'ForeignPtr's and vanilla memory
48 -- references of type @Ptr a@ is that the former may be associated
49 -- with /finalisers/. A finaliser is a routine that is invoked when
50 -- the Haskell storage manager detects that - within the Haskell heap
51 -- and stack - there are no more references left that are pointing to
52 -- the 'ForeignPtr'.  Typically, the finaliser will, then, invoke
53 -- routines in the foreign language that free the resources bound by
54 -- the foreign object.
55 --
56 -- The 'ForeignPtr' is parameterised in the same way as 'Ptr'.  The
57 -- type argument of 'ForeignPtr' should normally be an instance of
58 -- class 'Storable'.
59 --
60 data ForeignPtr a 
61   = ForeignPtr ForeignObj# !(IORef [IO ()])
62   | MallocPtr (MutableByteArray# RealWorld) !(IORef [IO ()])
63
64 instance Eq (ForeignPtr a) where
65     p == q  =  unsafeForeignPtrToPtr p == unsafeForeignPtrToPtr q
66
67 instance Ord (ForeignPtr a) where
68     compare p q  =  compare (unsafeForeignPtrToPtr p) (unsafeForeignPtrToPtr q)
69
70 instance Show (ForeignPtr a) where
71     showsPrec p f = showsPrec p (unsafeForeignPtrToPtr f)
72
73 #include "Typeable.h"
74 INSTANCE_TYPEABLE1(ForeignPtr,foreignPtrTc,"ForeignPtr")
75
76 -- |A Finaliser is represented as a pointer to a foreign function that, at
77 -- finalisation time, gets as an argument a plain pointer variant of the
78 -- foreign pointer that the finalizer is associated with.
79 -- 
80 type FinalizerPtr a = FunPtr (Ptr a -> IO ())
81
82 newConcForeignPtr :: Ptr a -> IO () -> IO (ForeignPtr a)
83 -- ^Turns a plain memory reference into a foreign object
84 -- by associating a finaliser - given by the monadic operation
85 -- - with the reference.  The finaliser will be executed after
86 -- the last reference to the foreign object is dropped.  Note
87 -- that there is no guarantee on how soon the finaliser is
88 -- executed after the last reference was dropped; this depends
89 -- on the details of the Haskell storage manager. The only
90 -- guarantee is that the finaliser runs before the program
91 -- terminates.
92 --
93 -- The finalizer, when invoked, will run in a separate thread.
94 --
95 newConcForeignPtr p finalizer
96   = do fObj <- newForeignPtr_ p
97        addForeignPtrConcFinalizer fObj finalizer
98        return fObj
99
100 mallocForeignPtr :: Storable a => IO (ForeignPtr a)
101 -- ^ Allocate some memory and return a 'ForeignPtr' to it.  The memory
102 -- will be released automatically when the 'ForeignPtr' is discarded.
103 --
104 -- 'mallocForeignPtr' is equivalent to
105 --
106 -- >    do { p <- malloc; newForeignPtr finalizerFree p }
107 -- 
108 -- although it may be implemented differently internally: you may not
109 -- assume that the memory returned by 'mallocForeignPtr' has been
110 -- allocated with 'Foreign.Marshal.Alloc.malloc'.
111 mallocForeignPtr = doMalloc undefined
112   where doMalloc :: Storable a => a -> IO (ForeignPtr a)
113         doMalloc a = do
114           r <- newIORef []
115           IO $ \s ->
116             case newPinnedByteArray# size s of { (# s, mbarr# #) ->
117              (# s, MallocPtr mbarr# r #)
118             }
119             where (I# size) = sizeOf a
120
121 -- | This function is similar to 'mallocForeignPtr', except that the
122 -- size of the memory required is given explicitly as a number of bytes.
123 mallocForeignPtrBytes :: Int -> IO (ForeignPtr a)
124 mallocForeignPtrBytes (I# size) = do 
125   r <- newIORef []
126   IO $ \s ->
127      case newPinnedByteArray# size s      of { (# s, mbarr# #) ->
128        (# s, MallocPtr mbarr# r #)
129      }
130
131 addForeignPtrFinalizer :: FinalizerPtr a -> ForeignPtr a -> IO ()
132 -- ^This function adds a finaliser to the given foreign object.  The
133 -- finalizer will run /before/ all other finalizers for the same
134 -- object which have already been registered.
135 addForeignPtrFinalizer finalizer fptr = 
136   addForeignPtrConcFinalizer fptr 
137         (mkFinalizer finalizer (unsafeForeignPtrToPtr fptr))
138
139 addForeignPtrConcFinalizer :: ForeignPtr a -> IO () -> IO ()
140 -- ^This function adds a finaliser to the given @ForeignPtr@.  The
141 -- finalizer will run /before/ all other finalizers for the same
142 -- object which have already been registered.
143 --
144 -- This is a variant of @addForeignPtrFinalizer@, where the finalizer
145 -- is an arbitrary @IO@ action.  When it is invoked, the finalizer
146 -- will run in a new thread.
147 --
148 -- NB. Be very careful with these finalizers.  One common trap is that
149 -- if a finalizer references another finalized value, it does not
150 -- prevent that value from being finalized.  In particular, 'Handle's
151 -- are finalized objects, so a finalizer should not refer to a 'Handle'
152 -- (including @stdout@, @stdin@ or @stderr@).
153 --
154 addForeignPtrConcFinalizer f@(ForeignPtr fo r) finalizer = do
155   fs <- readIORef r
156   writeIORef r (finalizer : fs)
157   if (null fs)
158      then IO $ \s ->
159               let p = unsafeForeignPtrToPtr f in
160               case mkWeak# fo () (foreignPtrFinalizer r p) s of 
161                  (# s1, w #) -> (# s1, () #)
162      else return ()
163 addForeignPtrConcFinalizer f@(MallocPtr fo r) finalizer = do 
164   fs <- readIORef r
165   writeIORef r (finalizer : fs)
166   if (null fs)
167      then  IO $ \s -> 
168                let p = unsafeForeignPtrToPtr f in
169                case mkWeak# fo () (do foreignPtrFinalizer r p
170                                       touchPinnedByteArray# fo) s of 
171                   (# s1, w #) -> (# s1, () #)
172      else return ()
173
174 foreign import ccall "dynamic" 
175   mkFinalizer :: FinalizerPtr a -> Ptr a -> IO ()
176
177 foreignPtrFinalizer :: IORef [IO ()] -> Ptr a -> IO ()
178 foreignPtrFinalizer r p = do
179   fs <- readIORef r
180   sequence_ fs
181
182 newForeignPtr_ :: Ptr a -> IO (ForeignPtr a)
183 -- ^Turns a plain memory reference into a foreign pointer that may be
184 -- associated with finalizers by using 'addForeignPtrFinalizer'.
185 newForeignPtr_ (Ptr obj) =  do
186   r <- newIORef []
187   IO $ \ s# ->
188     case mkForeignObj# obj s# of
189       (# s1#, fo# #) -> (# s1#,  ForeignPtr fo# r #)
190
191 touchPinnedByteArray# :: MutableByteArray# RealWorld -> IO ()
192 touchPinnedByteArray# ba# = IO $ \s -> case touch# ba# s of s -> (# s, () #)
193
194 touchForeignPtr :: ForeignPtr a -> IO ()
195 -- ^This function ensures that the foreign object in
196 -- question is alive at the given place in the sequence of IO
197 -- actions. In particular 'Foreign.ForeignPtr.withForeignPtr'
198 -- does a 'touchForeignPtr' after it
199 -- executes the user action.
200 -- 
201 -- This function can be used to express liveness
202 -- dependencies between 'ForeignPtr's: for
203 -- example, if the finalizer for one
204 -- 'ForeignPtr' touches a second
205 -- 'ForeignPtr', then it is ensured that the
206 -- second 'ForeignPtr' will stay alive at
207 -- least as long as the first.  This can be useful when you
208 -- want to manipulate /interior pointers/ to
209 -- a foreign structure: you can use
210 -- 'touchForeignObj' to express the
211 -- requirement that the exterior pointer must not be finalized
212 -- until the interior pointer is no longer referenced.
213 touchForeignPtr (ForeignPtr fo r)
214    = IO $ \s -> case touch# fo s of s -> (# s, () #)
215 touchForeignPtr (MallocPtr fo r)
216    = touchPinnedByteArray# fo
217
218 unsafeForeignPtrToPtr :: ForeignPtr a -> Ptr a
219 -- ^This function extracts the pointer component of a foreign
220 -- pointer.  This is a potentially dangerous operations, as if the
221 -- argument to 'unsafeForeignPtrToPtr' is the last usage
222 -- occurence of the given foreign pointer, then its finaliser(s) will
223 -- be run, which potentially invalidates the plain pointer just
224 -- obtained.  Hence, 'touchForeignPtr' must be used
225 -- wherever it has to be guaranteed that the pointer lives on - i.e.,
226 -- has another usage occurrence.
227 --
228 -- To avoid subtle coding errors, hand written marshalling code
229 -- should preferably use 'Foreign.ForeignPtr.withForeignPtr' rather
230 -- than combinations of 'unsafeForeignPtrToPtr' and
231 -- 'touchForeignPtr'.  However, the later routines
232 -- are occasionally preferred in tool generated marshalling code.
233 unsafeForeignPtrToPtr (ForeignPtr fo r) = Ptr (foreignObjToAddr# fo)
234 unsafeForeignPtrToPtr (MallocPtr  fo r) = Ptr (byteArrayContents# (unsafeCoerce# fo))
235
236 castForeignPtr :: ForeignPtr a -> ForeignPtr b
237 -- ^This function casts a 'ForeignPtr'
238 -- parameterised by one type into another type.
239 castForeignPtr f = unsafeCoerce# f
240
241 -- | Causes a the finalizers associated with a foreign pointer to be run
242 -- immediately.
243 finalizeForeignPtr :: ForeignPtr a -> IO ()
244 finalizeForeignPtr foreignPtr = do
245         finalizers <- readIORef refFinalizers
246         sequence_ finalizers
247         writeIORef refFinalizers []
248         where
249                 refFinalizers = case foreignPtr of
250                         (ForeignPtr _ ref) -> ref
251                         (MallocPtr  _ ref) -> ref