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,
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 = unsafeForeignPtrToPtr p == unsafeForeignPtrToPtr q
66 instance Ord (ForeignPtr a) where
67 compare p q = compare (unsafeForeignPtrToPtr p) (unsafeForeignPtrToPtr q)
69 instance Show (ForeignPtr a) where
70 showsPrec p f = showsPrec p (unsafeForeignPtrToPtr 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 newConcForeignPtr :: Ptr a -> IO () -> IO (ForeignPtr a)
82 -- ^Turns a plain memory reference into a foreign object
83 -- by associating a finaliser - given by the monadic operation
84 -- - with the reference. The finaliser will be executed after
85 -- the last reference to the foreign object is dropped. Note
86 -- that there is no guarantee on how soon the finaliser is
87 -- executed after the last reference was dropped; this depends
88 -- on the details of the Haskell storage manager. The only
89 -- guarantee is that the finaliser runs before the program
92 -- The finalizer, when invoked, will run in a separate thread.
94 newConcForeignPtr p finalizer
95 = do fObj <- newForeignPtr_ p
96 addForeignPtrConcFinalizer fObj finalizer
99 mallocForeignPtr :: Storable a => IO (ForeignPtr a)
100 -- ^ Allocate some memory and return a 'ForeignPtr' to it. The memory
101 -- will be released automatically when the 'ForeignPtr' is discarded.
103 -- 'mallocForeignPtr' is equivalent to
105 -- > do { p <- malloc; newForeignPtr finalizerFree p }
107 -- although it may be implemented differently internally: you may not
108 -- assume that the memory returned by 'mallocForeignPtr' has been
109 -- allocated with 'Foreign.Marshal.Alloc.malloc'.
110 mallocForeignPtr = doMalloc undefined
111 where doMalloc :: Storable a => a -> IO (ForeignPtr a)
115 case newPinnedByteArray# size s of { (# s, mbarr# #) ->
116 (# s, MallocPtr mbarr# r #)
118 where (I# size) = sizeOf a
120 -- | This function is similar to 'mallocForeignPtr', except that the
121 -- size of the memory required is given explicitly as a number of bytes.
122 mallocForeignPtrBytes :: Int -> IO (ForeignPtr a)
123 mallocForeignPtrBytes (I# size) = do
126 case newPinnedByteArray# size s of { (# s, mbarr# #) ->
127 (# s, MallocPtr mbarr# r #)
130 addForeignPtrFinalizer :: FinalizerPtr a -> ForeignPtr a -> IO ()
131 -- ^This function adds a finaliser to the given foreign object. The
132 -- finalizer will run /before/ all other finalizers for the same
133 -- object which have already been registered.
134 addForeignPtrFinalizer finalizer fptr =
135 addForeignPtrConcFinalizer fptr
136 (mkFinalizer finalizer (unsafeForeignPtrToPtr fptr))
138 addForeignPtrConcFinalizer :: ForeignPtr a -> IO () -> IO ()
139 -- ^This function adds a finaliser to the given @ForeignPtr@. The
140 -- finalizer will run /before/ all other finalizers for the same
141 -- object which have already been registered.
143 -- This is a variant of @addForeignPtrFinalizer@, where the finalizer
144 -- is an arbitrary @IO@ action. When it is invoked, the finalizer
145 -- will run in a new thread.
147 addForeignPtrConcFinalizer f@(ForeignPtr fo r) finalizer = do
149 writeIORef r (finalizer : fs)
152 let p = unsafeForeignPtrToPtr f in
153 case mkWeak# fo () (foreignPtrFinalizer r p) s of
154 (# s1, w #) -> (# s1, () #)
156 addForeignPtrConcFinalizer f@(MallocPtr fo r) finalizer = do
158 writeIORef r (finalizer : fs)
161 let p = unsafeForeignPtrToPtr f in
162 case mkWeak# fo () (do foreignPtrFinalizer r p
163 touchPinnedByteArray# fo) s of
164 (# s1, w #) -> (# s1, () #)
167 foreign import ccall "dynamic"
168 mkFinalizer :: FinalizerPtr a -> Ptr a -> IO ()
170 foreignPtrFinalizer :: IORef [IO ()] -> Ptr a -> IO ()
171 foreignPtrFinalizer r p = do
175 newForeignPtr_ :: Ptr a -> IO (ForeignPtr a)
176 -- ^Turns a plain memory reference into a foreign pointer that may be
177 -- associated with finalizers by using 'addForeignPtrFinalizer'.
178 newForeignPtr_ (Ptr obj) = do
181 case mkForeignObj# obj s# of
182 (# s1#, fo# #) -> (# s1#, ForeignPtr fo# r #)
184 touchPinnedByteArray# :: MutableByteArray# RealWorld -> IO ()
185 touchPinnedByteArray# ba# = IO $ \s -> case touch# ba# s of s -> (# s, () #)
187 touchForeignPtr :: ForeignPtr a -> IO ()
188 -- ^This function ensures that the foreign object in
189 -- question is alive at the given place in the sequence of IO
190 -- actions. In particular 'Foreign.ForeignPtr.withForeignPtr'
191 -- does a 'touchForeignPtr' after it
192 -- executes the user action.
194 -- This function can be used to express liveness
195 -- dependencies between 'ForeignPtr's: for
196 -- example, if the finalizer for one
197 -- 'ForeignPtr' touches a second
198 -- 'ForeignPtr', then it is ensured that the
199 -- second 'ForeignPtr' will stay alive at
200 -- least as long as the first. This can be useful when you
201 -- want to manipulate /interior pointers/ to
202 -- a foreign structure: you can use
203 -- 'touchForeignObj' to express the
204 -- requirement that the exterior pointer must not be finalized
205 -- until the interior pointer is no longer referenced.
206 touchForeignPtr (ForeignPtr fo r)
207 = IO $ \s -> case touch# fo s of s -> (# s, () #)
208 touchForeignPtr (MallocPtr fo r)
209 = touchPinnedByteArray# fo
211 unsafeForeignPtrToPtr :: ForeignPtr a -> Ptr a
212 -- ^This function extracts the pointer component of a foreign
213 -- pointer. This is a potentially dangerous operations, as if the
214 -- argument to 'unsafeForeignPtrToPtr' is the last usage
215 -- occurence of the given foreign pointer, then its finaliser(s) will
216 -- be run, which potentially invalidates the plain pointer just
217 -- obtained. Hence, 'touchForeignPtr' must be used
218 -- wherever it has to be guaranteed that the pointer lives on - i.e.,
219 -- has another usage occurrence.
221 -- To avoid subtle coding errors, hand written marshalling code
222 -- should preferably use 'Foreign.ForeignPtr.withForeignPtr' rather
223 -- than combinations of 'unsafeForeignPtrToPtr' and
224 -- 'touchForeignPtr'. However, the later routines
225 -- are occasionally preferred in tool generated marshalling code.
226 unsafeForeignPtrToPtr (ForeignPtr fo r) = Ptr (foreignObjToAddr# fo)
227 unsafeForeignPtrToPtr (MallocPtr fo r) = Ptr (byteArrayContents# (unsafeCoerce# fo))
229 castForeignPtr :: ForeignPtr a -> ForeignPtr b
230 -- ^This function casts a 'ForeignPtr'
231 -- parameterised by one type into another type.
232 castForeignPtr f = unsafeCoerce# f