1 {-# OPTIONS -fno-implicit-prelude #-}
2 -----------------------------------------------------------------------------
4 -- Module : GHC.ForeignPtr
5 -- Copyright : (c) The University of Glasgow, 1992-2003
6 -- License : see libraries/base/LICENSE
8 -- Maintainer : cvs-ghc@haskell.org
9 -- Stability : internal
10 -- Portability : non-portable (GHC extensions)
12 -- GHC's implementation of the 'ForeignPtr' data type.
14 -----------------------------------------------------------------------------
22 mallocForeignPtrBytes,
23 addForeignPtrFinalizer,
28 addForeignPtrConcFinalizer,
31 import Control.Monad ( sequence_ )
33 import Foreign.Storable
36 import GHC.List ( null )
39 import GHC.Ptr ( Ptr(..) )
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.
55 -- The 'ForeignPtr' is parameterised in the same way as 'Ptr'. The
56 -- type argument of 'ForeignPtr' should normally be an instance of
60 = ForeignPtr ForeignObj# !(IORef [IO ()])
61 | MallocPtr (MutableByteArray# RealWorld) !(IORef [IO ()])
63 instance Eq (ForeignPtr a) where
64 p == q = foreignPtrToPtr p == foreignPtrToPtr q
66 instance Ord (ForeignPtr a) where
67 compare p q = compare (foreignPtrToPtr p) (foreignPtrToPtr q)
69 instance Show (ForeignPtr a) where
70 showsPrec p f = showsPrec p (foreignPtrToPtr f)
73 INSTANCE_TYPEABLE1(ForeignPtr,foreignPtrTc,"ForeignPtr")
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.
79 type FinalizerPtr a = FunPtr (Ptr a -> IO ())
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
89 newForeignPtr p finalizer
90 = do fObj <- mkForeignPtr p
91 addForeignPtrFinalizer fObj finalizer
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
105 -- The finalizer, when invoked, will run in a separate thread.
107 newConcForeignPtr p finalizer
108 = do fObj <- mkForeignPtr p
109 addForeignPtrConcFinalizer fObj finalizer
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.
116 -- @mallocForeignPtr@ is equivalent to
118 -- > do { p <- malloc; newForeignPtr p free }
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)
128 case newPinnedByteArray# size s of { (# s, mbarr# #) ->
129 (# s, MallocPtr mbarr# r #)
131 where (I# size) = sizeOf a
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
139 case newPinnedByteArray# size s of { (# s, mbarr# #) ->
140 (# s, MallocPtr mbarr# r #)
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))
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.
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.
160 addForeignPtrConcFinalizer f@(ForeignPtr fo r) finalizer = do
162 writeIORef r (finalizer : fs)
165 let p = foreignPtrToPtr f in
166 case mkWeak# fo () (foreignPtrFinalizer r p) s of
167 (# s1, w #) -> (# s1, () #)
169 addForeignPtrConcFinalizer f@(MallocPtr fo r) finalizer = do
171 writeIORef r (finalizer : fs)
174 let p = foreignPtrToPtr f in
175 case mkWeak# fo () (foreignPtrFinalizer r p) s of
176 (# s1, w #) -> (# s1, () #)
179 foreign import ccall "dynamic"
180 mkFinalizer :: FinalizerPtr a -> Ptr a -> IO ()
182 foreignPtrFinalizer :: IORef [IO ()] -> Ptr a -> IO ()
183 foreignPtrFinalizer r p = do
187 mkForeignPtr :: Ptr a -> IO (ForeignPtr a) {- not exported -}
188 mkForeignPtr (Ptr obj) = do
191 case mkForeignObj# obj s# of
192 (# s1#, fo# #) -> (# s1#, ForeignPtr fo# r #)
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.
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, () #)
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.
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))
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