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,
25 unsafeForeignPtrToPtr,
28 addForeignPtrConcFinalizer,
32 import Control.Monad ( sequence_ )
34 import Foreign.Storable
37 import GHC.List ( null )
40 import GHC.Ptr ( Ptr(..) )
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.
56 -- The 'ForeignPtr' is parameterised in the same way as 'Ptr'. The
57 -- type argument of 'ForeignPtr' should normally be an instance of
61 = ForeignPtr ForeignObj# !(IORef [IO ()])
62 | MallocPtr (MutableByteArray# RealWorld) !(IORef [IO ()])
64 instance Eq (ForeignPtr a) where
65 p == q = unsafeForeignPtrToPtr p == unsafeForeignPtrToPtr q
67 instance Ord (ForeignPtr a) where
68 compare p q = compare (unsafeForeignPtrToPtr p) (unsafeForeignPtrToPtr q)
70 instance Show (ForeignPtr a) where
71 showsPrec p f = showsPrec p (unsafeForeignPtrToPtr f)
74 INSTANCE_TYPEABLE1(ForeignPtr,foreignPtrTc,"ForeignPtr")
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.
80 type FinalizerPtr a = FunPtr (Ptr a -> IO ())
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
93 -- The finalizer, when invoked, will run in a separate thread.
95 newConcForeignPtr p finalizer
96 = do fObj <- newForeignPtr_ p
97 addForeignPtrConcFinalizer fObj finalizer
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.
104 -- 'mallocForeignPtr' is equivalent to
106 -- > do { p <- malloc; newForeignPtr finalizerFree p }
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)
116 case newPinnedByteArray# size s of { (# s, mbarr# #) ->
117 (# s, MallocPtr mbarr# r #)
119 where (I# size) = sizeOf a
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
127 case newPinnedByteArray# size s of { (# s, mbarr# #) ->
128 (# s, MallocPtr mbarr# r #)
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))
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.
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.
148 addForeignPtrConcFinalizer f@(ForeignPtr fo r) finalizer = do
150 writeIORef r (finalizer : fs)
153 let p = unsafeForeignPtrToPtr f in
154 case mkWeak# fo () (foreignPtrFinalizer r p) s of
155 (# s1, w #) -> (# s1, () #)
157 addForeignPtrConcFinalizer f@(MallocPtr fo r) finalizer = do
159 writeIORef r (finalizer : fs)
162 let p = unsafeForeignPtrToPtr f in
163 case mkWeak# fo () (do foreignPtrFinalizer r p
164 touchPinnedByteArray# fo) s of
165 (# s1, w #) -> (# s1, () #)
168 foreign import ccall "dynamic"
169 mkFinalizer :: FinalizerPtr a -> Ptr a -> IO ()
171 foreignPtrFinalizer :: IORef [IO ()] -> Ptr a -> IO ()
172 foreignPtrFinalizer r p = do
176 newForeignPtr_ :: Ptr a -> IO (ForeignPtr a)
177 -- ^Turns a plain memory reference into a foreign pointer that may be
178 -- associated with finalizers by using 'addForeignPtrFinalizer'.
179 newForeignPtr_ (Ptr obj) = do
182 case mkForeignObj# obj s# of
183 (# s1#, fo# #) -> (# s1#, ForeignPtr fo# r #)
185 touchPinnedByteArray# :: MutableByteArray# RealWorld -> IO ()
186 touchPinnedByteArray# ba# = IO $ \s -> case touch# ba# s of s -> (# s, () #)
188 touchForeignPtr :: ForeignPtr a -> IO ()
189 -- ^This function ensures that the foreign object in
190 -- question is alive at the given place in the sequence of IO
191 -- actions. In particular 'Foreign.ForeignPtr.withForeignPtr'
192 -- does a 'touchForeignPtr' after it
193 -- executes the user action.
195 -- This function can be used to express liveness
196 -- dependencies between 'ForeignPtr's: for
197 -- example, if the finalizer for one
198 -- 'ForeignPtr' touches a second
199 -- 'ForeignPtr', then it is ensured that the
200 -- second 'ForeignPtr' will stay alive at
201 -- least as long as the first. This can be useful when you
202 -- want to manipulate /interior pointers/ to
203 -- a foreign structure: you can use
204 -- 'touchForeignObj' to express the
205 -- requirement that the exterior pointer must not be finalized
206 -- until the interior pointer is no longer referenced.
207 touchForeignPtr (ForeignPtr fo r)
208 = IO $ \s -> case touch# fo s of s -> (# s, () #)
209 touchForeignPtr (MallocPtr fo r)
210 = touchPinnedByteArray# fo
212 unsafeForeignPtrToPtr :: ForeignPtr a -> Ptr a
213 -- ^This function extracts the pointer component of a foreign
214 -- pointer. This is a potentially dangerous operations, as if the
215 -- argument to 'unsafeForeignPtrToPtr' is the last usage
216 -- occurence of the given foreign pointer, then its finaliser(s) will
217 -- be run, which potentially invalidates the plain pointer just
218 -- obtained. Hence, 'touchForeignPtr' must be used
219 -- wherever it has to be guaranteed that the pointer lives on - i.e.,
220 -- has another usage occurrence.
222 -- To avoid subtle coding errors, hand written marshalling code
223 -- should preferably use 'Foreign.ForeignPtr.withForeignPtr' rather
224 -- than combinations of 'unsafeForeignPtrToPtr' and
225 -- 'touchForeignPtr'. However, the later routines
226 -- are occasionally preferred in tool generated marshalling code.
227 unsafeForeignPtrToPtr (ForeignPtr fo r) = Ptr (foreignObjToAddr# fo)
228 unsafeForeignPtrToPtr (MallocPtr fo r) = Ptr (byteArrayContents# (unsafeCoerce# fo))
230 castForeignPtr :: ForeignPtr a -> ForeignPtr b
231 -- ^This function casts a 'ForeignPtr'
232 -- parameterised by one type into another type.
233 castForeignPtr f = unsafeCoerce# f
235 -- | Causes a the finalizers associated with a foreign pointer to be run
237 finalizeForeignPtr :: ForeignPtr a -> IO ()
238 finalizeForeignPtr foreignPtr = do
239 finalizers <- readIORef refFinalizers
241 writeIORef refFinalizers []
243 refFinalizers = case foreignPtr of
244 (ForeignPtr _ ref) -> ref
245 (MallocPtr _ ref) -> ref