[project @ 2005-02-03 10:32:11 by ross]
[ghc.git] / libraries / base / GHC / ForeignPtr.hs
1 {-# OPTIONS_GHC -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 -- #hide
17 module GHC.ForeignPtr
18 (
19 ForeignPtr(..),
20 FinalizerPtr,
21 newForeignPtr_,
22 mallocForeignPtr,
23 mallocForeignPtrBytes,
24 addForeignPtrFinalizer,
25 touchForeignPtr,
26 unsafeForeignPtrToPtr,
27 castForeignPtr,
28 newConcForeignPtr,
29 addForeignPtrConcFinalizer,
30 finalizeForeignPtr
31 ) where
32
33 import Control.Monad ( sequence_ )
34 import Foreign.Ptr
35 import Foreign.Storable
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 /finalizers/. A finalizer 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 finalizer 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 -- |A Finalizer is represented as a pointer to a foreign function that, at
74 -- finalisation time, gets as an argument a plain pointer variant of the
75 -- foreign pointer that the finalizer is associated with.
76 --
77 type FinalizerPtr a = FunPtr (Ptr a -> IO ())
78
79 newConcForeignPtr :: Ptr a -> IO () -> IO (ForeignPtr a)
80 --
81 -- ^Turns a plain memory reference into a foreign object by
82 -- associating a finalizer - given by the monadic operation - with the
83 -- reference. The storage manager will start the finalizer, in a
84 -- separate thread, some time after the last reference to the
85 -- @ForeignPtr@ is dropped. There is no guarantee of promptness, and
86 -- in fact there is no guarantee that the finalizer will eventually
87 -- run at all.
88 --
89 newConcForeignPtr p finalizer
90 = do fObj <- newForeignPtr_ p
91 addForeignPtrConcFinalizer fObj finalizer
92 return fObj
93
94 mallocForeignPtr :: Storable a => IO (ForeignPtr a)
95 -- ^ Allocate some memory and return a 'ForeignPtr' to it. The memory
96 -- will be released automatically when the 'ForeignPtr' is discarded.
97 --
98 -- 'mallocForeignPtr' is equivalent to
99 --
100 -- > do { p <- malloc; newForeignPtr finalizerFree p }
101 --
102 -- although it may be implemented differently internally: you may not
103 -- assume that the memory returned by 'mallocForeignPtr' has been
104 -- allocated with 'Foreign.Marshal.Alloc.malloc'.
105 mallocForeignPtr = doMalloc undefined
106 where doMalloc :: Storable b => b -> IO (ForeignPtr b)
107 doMalloc a = do
108 r <- newIORef []
109 IO $ \s ->
110 case newPinnedByteArray# size s of { (# s, mbarr# #) ->
111 (# s, MallocPtr mbarr# r #)
112 }
113 where (I# size) = sizeOf a
114
115 -- | This function is similar to 'mallocForeignPtr', except that the
116 -- size of the memory required is given explicitly as a number of bytes.
117 mallocForeignPtrBytes :: Int -> IO (ForeignPtr a)
118 mallocForeignPtrBytes (I# size) = do
119 r <- newIORef []
120 IO $ \s ->
121 case newPinnedByteArray# size s of { (# s, mbarr# #) ->
122 (# s, MallocPtr mbarr# r #)
123 }
124
125 addForeignPtrFinalizer :: FinalizerPtr a -> ForeignPtr a -> IO ()
126 -- ^This function adds a finalizer to the given foreign object. The
127 -- finalizer will run /before/ all other finalizers for the same
128 -- object which have already been registered.
129 addForeignPtrFinalizer finalizer fptr =
130 addForeignPtrConcFinalizer fptr
131 (mkFinalizer finalizer (unsafeForeignPtrToPtr fptr))
132
133 addForeignPtrConcFinalizer :: ForeignPtr a -> IO () -> IO ()
134 -- ^This function adds a finalizer to the given @ForeignPtr@. The
135 -- finalizer will run /before/ all other finalizers for the same
136 -- object which have already been registered.
137 --
138 -- This is a variant of @addForeignPtrFinalizer@, where the finalizer
139 -- is an arbitrary @IO@ action. When it is invoked, the finalizer
140 -- will run in a new thread.
141 --
142 -- NB. Be very careful with these finalizers. One common trap is that
143 -- if a finalizer references another finalized value, it does not
144 -- prevent that value from being finalized. In particular, 'Handle's
145 -- are finalized objects, so a finalizer should not refer to a 'Handle'
146 -- (including @stdout@, @stdin@ or @stderr@).
147 --
148 addForeignPtrConcFinalizer f@(ForeignPtr fo r) finalizer = do
149 fs <- readIORef r
150 writeIORef r (finalizer : fs)
151 if (null fs)
152 then IO $ \s ->
153 let p = unsafeForeignPtrToPtr f in
154 case mkWeak# fo () (foreignPtrFinalizer r p) s of
155 (# s1, w #) -> (# s1, () #)
156 else return ()
157 addForeignPtrConcFinalizer f@(MallocPtr fo r) finalizer = do
158 fs <- readIORef r
159 writeIORef r (finalizer : fs)
160 if (null fs)
161 then IO $ \s ->
162 let p = unsafeForeignPtrToPtr f in
163 case mkWeak# fo () (do foreignPtrFinalizer r p
164 touchPinnedByteArray# fo) s of
165 (# s1, w #) -> (# s1, () #)
166 else return ()
167
168 foreign import ccall "dynamic"
169 mkFinalizer :: FinalizerPtr a -> Ptr a -> IO ()
170
171 foreignPtrFinalizer :: IORef [IO ()] -> Ptr a -> IO ()
172 foreignPtrFinalizer r p = do
173 fs <- readIORef r
174 sequence_ fs
175
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
180 r <- newIORef []
181 IO $ \ s# ->
182 case mkForeignObj# obj s# of
183 (# s1#, fo# #) -> (# s1#, ForeignPtr fo# r #)
184
185 touchPinnedByteArray# :: MutableByteArray# RealWorld -> IO ()
186 touchPinnedByteArray# ba# = IO $ \s -> case touch# ba# s of s -> (# s, () #)
187
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.
194 --
195 -- Note that this function should not be used to express liveness
196 -- dependencies between 'ForeignPtr's. For example, if the finalizer
197 -- for a 'ForeignPtr' @F1@ calls 'touchForeignPtr' on a second
198 -- 'ForeignPtr' @F2@, then the only guarantee is that the finalizer
199 -- for @F2@ is never started before the finalizer for @F1@. They
200 -- might be started together if for example both @F1@ and @F2@ are
201 -- otherwise unreachable, and in that case the scheduler might end up
202 -- running the finalizer for @F2@ first.
203 --
204 -- In general, it is not recommended to use finalizers on separate
205 -- objects with ordering constraints between them. To express the
206 -- ordering robustly requires explicit synchronisation using @MVar@s
207 -- between the finalizers, but even then the runtime sometimes runs
208 -- multiple finalizers sequentially in a single thread (for
209 -- performance reasons), so synchronisation between finalizers could
210 -- result in artificial deadlock.
211 --
212 touchForeignPtr (ForeignPtr fo r)
213 = IO $ \s -> case touch# fo s of s -> (# s, () #)
214 touchForeignPtr (MallocPtr fo r)
215 = touchPinnedByteArray# fo
216
217 unsafeForeignPtrToPtr :: ForeignPtr a -> Ptr a
218 -- ^This function extracts the pointer component of a foreign
219 -- pointer. This is a potentially dangerous operations, as if the
220 -- argument to 'unsafeForeignPtrToPtr' is the last usage
221 -- occurrence of the given foreign pointer, then its finalizer(s) will
222 -- be run, which potentially invalidates the plain pointer just
223 -- obtained. Hence, 'touchForeignPtr' must be used
224 -- wherever it has to be guaranteed that the pointer lives on - i.e.,
225 -- has another usage occurrence.
226 --
227 -- To avoid subtle coding errors, hand written marshalling code
228 -- should preferably use 'Foreign.ForeignPtr.withForeignPtr' rather
229 -- than combinations of 'unsafeForeignPtrToPtr' and
230 -- 'touchForeignPtr'. However, the later routines
231 -- are occasionally preferred in tool generated marshalling code.
232 unsafeForeignPtrToPtr (ForeignPtr fo r) = Ptr (foreignObjToAddr# fo)
233 unsafeForeignPtrToPtr (MallocPtr fo r) = Ptr (byteArrayContents# (unsafeCoerce# fo))
234
235 castForeignPtr :: ForeignPtr a -> ForeignPtr b
236 -- ^This function casts a 'ForeignPtr'
237 -- parameterised by one type into another type.
238 castForeignPtr f = unsafeCoerce# f
239
240 -- | Causes a the finalizers associated with a foreign pointer to be run
241 -- immediately.
242 finalizeForeignPtr :: ForeignPtr a -> IO ()
243 finalizeForeignPtr foreignPtr = do
244 finalizers <- readIORef refFinalizers
245 sequence_ finalizers
246 writeIORef refFinalizers []
247 where
248 refFinalizers = case foreignPtr of
249 (ForeignPtr _ ref) -> ref
250 (MallocPtr _ ref) -> ref