[project @ 2003-05-22 08:24:32 by chak]
[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         foreignPtrToPtr,
26         castForeignPtr,
27         newConcForeignPtr,
28         addForeignPtrConcFinalizer,
29   ) where
30
31 import Control.Monad    ( sequence_ )
32 import Foreign.Ptr
33 import Foreign.Storable
34 import Data.Dynamic
35
36 import GHC.List         ( null )
37 import GHC.Base
38 import GHC.IOBase
39 import GHC.Ptr          ( Ptr(..) )
40 import GHC.Err
41 import GHC.Show
42
43 -- |The type 'ForeignPtr' represents references to objects that are
44 -- maintained in a foreign language, i.e., that are not part of the
45 -- data structures usually managed by the Haskell storage manager.
46 -- The essential difference between 'ForeignPtr's and vanilla memory
47 -- references of type @Ptr a@ is that the former may be associated
48 -- with /finalisers/. A finaliser is a routine that is invoked when
49 -- the Haskell storage manager detects that - within the Haskell heap
50 -- and stack - there are no more references left that are pointing to
51 -- the 'ForeignPtr'.  Typically, the finaliser will, then, invoke
52 -- routines in the foreign language that free the resources bound by
53 -- the foreign object.
54 --
55 -- The 'ForeignPtr' is parameterised in the same way as 'Ptr'.  The
56 -- type argument of 'ForeignPtr' should normally be an instance of
57 -- class 'Storable'.
58 --
59 data ForeignPtr a 
60   = ForeignPtr ForeignObj# !(IORef [IO ()])
61   | MallocPtr (MutableByteArray# RealWorld) !(IORef [IO ()])
62
63 instance Eq (ForeignPtr a) where
64     p == q  =  foreignPtrToPtr p == foreignPtrToPtr q
65
66 instance Ord (ForeignPtr a) where
67     compare p q  =  compare (foreignPtrToPtr p) (foreignPtrToPtr q)
68
69 instance Show (ForeignPtr a) where
70     showsPrec p f = showsPrec p (foreignPtrToPtr f)
71
72 #include "Dynamic.h"
73 INSTANCE_TYPEABLE1(ForeignPtr,foreignPtrTc,"ForeignPtr")
74
75 -- |A Finaliser is represented as a pointer to a foreign function that, at
76 -- finalisation time, gets as an argument a plain pointer variant of the
77 -- foreign pointer that the finalizer is associated with.
78 -- 
79 type FinalizerPtr a = FunPtr (Ptr a -> IO ())
80
81 newForeignPtr :: Ptr a -> FinalizerPtr a -> IO (ForeignPtr a)
82 -- ^Turns a plain memory reference into a foreign object by
83 -- associating a finaliser with the reference.  The finaliser will be executed
84 -- after the last reference to the foreign object is dropped.  Note that there
85 -- is no guarantee on how soon the finaliser is executed after the last
86 -- reference was dropped; this depends on the details of the Haskell storage
87 -- manager. The only guarantee is that the finaliser runs before the program
88 -- terminates.
89 newForeignPtr p finalizer
90   = do fObj <- mkForeignPtr p
91        addForeignPtrFinalizer fObj finalizer
92        return fObj
93
94 newConcForeignPtr :: Ptr a -> IO () -> IO (ForeignPtr a)
95 -- ^Turns a plain memory reference into a foreign object
96 -- by associating a finaliser - given by the monadic operation
97 -- - with the reference.  The finaliser will be executed after
98 -- the last reference to the foreign object is dropped.  Note
99 -- that there is no guarantee on how soon the finaliser is
100 -- executed after the last reference was dropped; this depends
101 -- on the details of the Haskell storage manager. The only
102 -- guarantee is that the finaliser runs before the program
103 -- terminates.
104 --
105 -- The finalizer, when invoked, will run in a separate thread.
106 --
107 newConcForeignPtr p finalizer
108   = do fObj <- mkForeignPtr p
109        addForeignPtrConcFinalizer fObj finalizer
110        return fObj
111
112 mallocForeignPtr :: Storable a => IO (ForeignPtr a)
113 -- ^ allocates some memory and returns a ForeignPtr to it.  The memory
114 -- will be released automatically when the ForeignPtr is discarded.
115 --
116 -- @mallocForeignPtr@ is equivalent to
117 --
118 -- >    do { p <- malloc; newForeignPtr p free }
119 -- 
120 -- although it may be implemented differently internally.  You may not
121 -- assume that the memory returned by 'mallocForeignPtr' has been
122 -- allocated with C's @malloc()@.
123 mallocForeignPtr = doMalloc undefined
124   where doMalloc :: Storable a => a -> IO (ForeignPtr a)
125         doMalloc a = do
126           r <- newIORef []
127           IO $ \s ->
128             case newPinnedByteArray# size s of { (# s, mbarr# #) ->
129              (# s, MallocPtr mbarr# r #)
130             }
131             where (I# size) = sizeOf a
132
133 -- | similar to 'mallocForeignPtr', except that the size of the memory required
134 -- is given explicitly as a number of bytes.
135 mallocForeignPtrBytes :: Int -> IO (ForeignPtr a)
136 mallocForeignPtrBytes (I# size) = do 
137   r <- newIORef []
138   IO $ \s ->
139      case newPinnedByteArray# size s      of { (# s, mbarr# #) ->
140        (# s, MallocPtr mbarr# r #)
141      }
142
143 addForeignPtrFinalizer :: ForeignPtr a -> FinalizerPtr a -> IO ()
144 -- ^This function adds a finaliser to the given foreign object.  The
145 -- finalizer will run /before/ all other finalizers for the same
146 -- object which have already been registered.
147 addForeignPtrFinalizer fptr finalizer = 
148   addForeignPtrConcFinalizer fptr 
149         (mkFinalizer finalizer (foreignPtrToPtr fptr))
150
151 addForeignPtrConcFinalizer :: ForeignPtr a -> IO () -> IO ()
152 -- ^This function adds a finaliser to the given @ForeignPtr@.  The
153 -- finalizer will run /before/ all other finalizers for the same
154 -- object which have already been registered.
155 --
156 -- This is a variant of @addForeignPtrFinalizer@, where the finalizer
157 -- is an arbitrary @IO@ action.  When it is invoked, the finalizer
158 -- will run in a new thread.
159 --
160 addForeignPtrConcFinalizer f@(ForeignPtr fo r) finalizer = do
161   fs <- readIORef r
162   writeIORef r (finalizer : fs)
163   if (null fs)
164      then IO $ \s ->
165               let p = foreignPtrToPtr f in
166               case mkWeak# fo () (foreignPtrFinalizer r p) s of 
167                  (# s1, w #) -> (# s1, () #)
168      else return ()
169 addForeignPtrConcFinalizer f@(MallocPtr fo r) finalizer = do 
170   fs <- readIORef r
171   writeIORef r (finalizer : fs)
172   if (null fs)
173      then  IO $ \s -> 
174                let p = foreignPtrToPtr f in
175                case mkWeak# fo () (foreignPtrFinalizer r p) s of 
176                   (# s1, w #) -> (# s1, () #)
177      else return ()
178
179 foreign import ccall "dynamic" 
180   mkFinalizer :: FinalizerPtr a -> Ptr a -> IO ()
181
182 foreignPtrFinalizer :: IORef [IO ()] -> Ptr a -> IO ()
183 foreignPtrFinalizer r p = do
184   fs <- readIORef r
185   sequence_ fs
186
187 mkForeignPtr :: Ptr a -> IO (ForeignPtr a) {- not exported -}
188 mkForeignPtr (Ptr obj) =  do
189   r <- newIORef []
190   IO $ \ s# ->
191     case mkForeignObj# obj s# of
192       (# s1#, fo# #) -> (# s1#,  ForeignPtr fo# r #)
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 '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    = IO $ \s -> case touch# fo s of s -> (# s, () #)
217
218 foreignPtrToPtr :: 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 'foreignPtrToPtr' 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 'withForeignPtr' rather
230 -- than combinations of 'foreignPtrToPtr' and
231 -- 'touchForeignPtr'.  However, the later routines
232 -- are occasionally preferred in tool generated marshalling code.
233 foreignPtrToPtr (ForeignPtr fo r) = Ptr (foreignObjToAddr# fo)
234 foreignPtrToPtr (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