Optimised foreign pointer representation, for heap-allocated objects
[ghc-base.git] / 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         mallocPlainForeignPtr,
24         mallocForeignPtrBytes,
25         mallocPlainForeignPtrBytes,
26         addForeignPtrFinalizer, 
27         touchForeignPtr,
28         unsafeForeignPtrToPtr,
29         castForeignPtr,
30         newConcForeignPtr,
31         addForeignPtrConcFinalizer,
32         finalizeForeignPtr
33   ) where
34
35 import Control.Monad    ( sequence_ )
36 import Foreign.Storable
37 import Numeric          ( showHex )
38
39 import GHC.Show
40 import GHC.Num
41 import GHC.List         ( null, replicate, length )
42 import GHC.Base
43 import GHC.IOBase
44 import GHC.STRef        ( STRef(..) )
45 import GHC.Ptr          ( Ptr(..), FunPtr, castFunPtrToPtr )
46 import GHC.Err
47
48 -- |The type 'ForeignPtr' represents references to objects that are
49 -- maintained in a foreign language, i.e., that are not part of the
50 -- data structures usually managed by the Haskell storage manager.
51 -- The essential difference between 'ForeignPtr's and vanilla memory
52 -- references of type @Ptr a@ is that the former may be associated
53 -- with /finalizers/. A finalizer is a routine that is invoked when
54 -- the Haskell storage manager detects that - within the Haskell heap
55 -- and stack - there are no more references left that are pointing to
56 -- the 'ForeignPtr'.  Typically, the finalizer will, then, invoke
57 -- routines in the foreign language that free the resources bound by
58 -- the foreign object.
59 --
60 -- The 'ForeignPtr' is parameterised in the same way as 'Ptr'.  The
61 -- type argument of 'ForeignPtr' should normally be an instance of
62 -- class 'Storable'.
63 --
64 data ForeignPtr a = ForeignPtr Addr# ForeignPtrContents
65         -- we cache the Addr# in the ForeignPtr object, but attach
66         -- the finalizer to the IORef (or the MutableByteArray# in
67         -- the case of a MallocPtr).  The aim of the representation
68         -- is to make withForeignPtr efficient; in fact, withForeignPtr
69         -- should be just as efficient as unpacking a Ptr, and multiple
70         -- withForeignPtrs can share an unpacked ForeignPtr.  Note
71         -- that touchForeignPtr only has to touch the ForeignPtrContents
72         -- object, because that ensures that whatever the finalizer is
73         -- attached to is kept alive.
74
75 data ForeignPtrContents
76   = PlainForeignPtr !(IORef [IO ()])
77   | MallocPtr      (MutableByteArray# RealWorld) !(IORef [IO ()])
78   | PlainPtr       (MutableByteArray# RealWorld)
79
80 instance Eq (ForeignPtr a) where
81     p == q  =  unsafeForeignPtrToPtr p == unsafeForeignPtrToPtr q
82
83 instance Ord (ForeignPtr a) where
84     compare p q  =  compare (unsafeForeignPtrToPtr p) (unsafeForeignPtrToPtr q)
85
86 instance Show (ForeignPtr a) where
87     showsPrec p f = showsPrec p (unsafeForeignPtrToPtr f)
88
89 #include "MachDeps.h"
90
91 #if (WORD_SIZE_IN_BITS == 32 || WORD_SIZE_IN_BITS == 64)
92 instance Show (Ptr a) where
93    showsPrec p (Ptr a) rs = pad_out (showHex (word2Integer(int2Word#(addr2Int# a))) "") rs
94      where
95         -- want 0s prefixed to pad it out to a fixed length.
96        pad_out ls rs = 
97           '0':'x':(replicate (2*SIZEOF_HSPTR - length ls) '0') ++ ls ++ rs
98        -- word2Integer :: Word# -> Integer (stolen from Word.lhs)
99        word2Integer w = case word2Integer# w of
100                         (# s, d #) -> J# s d
101
102 instance Show (FunPtr a) where
103    showsPrec p = showsPrec p . castFunPtrToPtr
104 #endif
105
106 -- |A Finalizer is represented as a pointer to a foreign function that, at
107 -- finalisation time, gets as an argument a plain pointer variant of the
108 -- foreign pointer that the finalizer is associated with.
109 -- 
110 type FinalizerPtr a = FunPtr (Ptr a -> IO ())
111
112 newConcForeignPtr :: Ptr a -> IO () -> IO (ForeignPtr a)
113 --
114 -- ^Turns a plain memory reference into a foreign object by
115 -- associating a finalizer - given by the monadic operation - with the
116 -- reference.  The storage manager will start the finalizer, in a
117 -- separate thread, some time after the last reference to the
118 -- @ForeignPtr@ is dropped.  There is no guarantee of promptness, and
119 -- in fact there is no guarantee that the finalizer will eventually
120 -- run at all.
121 --
122 -- Note that references from a finalizer do not necessarily prevent
123 -- another object from being finalized.  If A's finalizer refers to B
124 -- (perhaps using 'touchForeignPtr', then the only guarantee is that
125 -- B's finalizer will never be started before A's.  If both A and B
126 -- are unreachable, then both finalizers will start together.  See
127 -- 'touchForeignPtr' for more on finalizer ordering.
128 --
129 newConcForeignPtr p finalizer
130   = do fObj <- newForeignPtr_ p
131        addForeignPtrConcFinalizer fObj finalizer
132        return fObj
133
134 mallocForeignPtr :: Storable a => IO (ForeignPtr a)
135 -- ^ Allocate some memory and return a 'ForeignPtr' to it.  The memory
136 -- will be released automatically when the 'ForeignPtr' is discarded.
137 --
138 -- 'mallocForeignPtr' is equivalent to
139 --
140 -- >    do { p <- malloc; newForeignPtr finalizerFree p }
141 -- 
142 -- although it may be implemented differently internally: you may not
143 -- assume that the memory returned by 'mallocForeignPtr' has been
144 -- allocated with 'Foreign.Marshal.Alloc.malloc'.
145 --
146 -- GHC notes: 'mallocForeignPtr' has a heavily optimised
147 -- implementation in GHC.  It uses pinned memory in the garbage
148 -- collected heap, so the 'ForeignPtr' does not require a finalizer to
149 -- free the memory.  Use of 'mallocForeignPtr' and associated
150 -- functions is strongly recommended in preference to 'newForeignPtr'
151 -- with a finalizer.
152 -- 
153 mallocForeignPtr = doMalloc undefined
154   where doMalloc :: Storable b => b -> IO (ForeignPtr b)
155         doMalloc a = do
156           r <- newIORef []
157           IO $ \s ->
158             case newPinnedByteArray# size s of { (# s, mbarr# #) ->
159              (# s, ForeignPtr (byteArrayContents# (unsafeCoerce# mbarr#))
160                               (MallocPtr mbarr# r) #)
161             }
162             where (I# size) = sizeOf a
163
164 -- | This function is similar to 'mallocForeignPtr', except that the
165 -- size of the memory required is given explicitly as a number of bytes.
166 mallocForeignPtrBytes :: Int -> IO (ForeignPtr a)
167 mallocForeignPtrBytes (I# size) = do 
168   r <- newIORef []
169   IO $ \s ->
170      case newPinnedByteArray# size s      of { (# s, mbarr# #) ->
171        (# s, ForeignPtr (byteArrayContents# (unsafeCoerce# mbarr#))
172                         (MallocPtr mbarr# r) #)
173      }
174
175 -- | Allocate some memory and return a 'ForeignPtr' to it.  The memory
176 -- will be released automatically when the 'ForeignPtr' is discarded.
177 --
178 -- GHC notes: 'mallocPlainForeignPtr' has a heavily optimised
179 -- implementation in GHC.  It uses pinned memory in the garbage
180 -- collected heap, as for mallocForeignPtr. Unlike mallocForeignPtr, a
181 -- ForeignPtr created with mallocPlainForeignPtr carries no finalizers.
182 -- It is not possible to add a finalizer to a ForeignPtr created with
183 -- mallocPlainForeignPtr. This is useful for ForeignPtrs that will live
184 -- only inside Haskell (such as those created for packed strings).
185 -- Attempts to add a finalizer to a ForeignPtr created this way, or to
186 -- finalize such a pointer, will have no effect.
187 -- 
188 mallocPlainForeignPtr :: Storable a => IO (ForeignPtr a)
189 mallocPlainForeignPtr = doMalloc undefined
190   where doMalloc :: Storable b => b -> IO (ForeignPtr b)
191         doMalloc a = IO $ \s ->
192             case newPinnedByteArray# size s of { (# s, mbarr# #) ->
193              (# s, ForeignPtr (byteArrayContents# (unsafeCoerce# mbarr#))
194                               (PlainPtr mbarr#) #)
195             }
196             where (I# size) = sizeOf a
197
198 -- | This function is similar to 'mallocForeignPtrBytes', except that
199 -- the internally an optimised ForeignPtr representation with no
200 -- finalizer is used.
201 mallocPlainForeignPtrBytes :: Int -> IO (ForeignPtr a)
202 mallocPlainForeignPtrBytes (I# size) = IO $ \s ->
203     case newPinnedByteArray# size s      of { (# s, mbarr# #) ->
204        (# s, ForeignPtr (byteArrayContents# (unsafeCoerce# mbarr#))
205                         (PlainPtr mbarr#) #)
206      }
207
208 addForeignPtrFinalizer :: FinalizerPtr a -> ForeignPtr a -> IO ()
209 -- ^This function adds a finalizer to the given foreign object.  The
210 -- finalizer will run /before/ all other finalizers for the same
211 -- object which have already been registered.
212 addForeignPtrFinalizer finalizer fptr = 
213   addForeignPtrConcFinalizer fptr 
214         (mkFinalizer finalizer (unsafeForeignPtrToPtr fptr))
215
216 addForeignPtrConcFinalizer :: ForeignPtr a -> IO () -> IO ()
217 -- ^This function adds a finalizer to the given @ForeignPtr@.  The
218 -- finalizer will run /before/ all other finalizers for the same
219 -- object which have already been registered.
220 --
221 -- This is a variant of @addForeignPtrFinalizer@, where the finalizer
222 -- is an arbitrary @IO@ action.  When it is invoked, the finalizer
223 -- will run in a new thread.
224 --
225 -- NB. Be very careful with these finalizers.  One common trap is that
226 -- if a finalizer references another finalized value, it does not
227 -- prevent that value from being finalized.  In particular, 'Handle's
228 -- are finalized objects, so a finalizer should not refer to a 'Handle'
229 -- (including @stdout@, @stdin@ or @stderr@).
230 --
231 addForeignPtrConcFinalizer (ForeignPtr a c) finalizer = 
232   addForeignPtrConcFinalizer_ c finalizer
233
234 addForeignPtrConcFinalizer_ f@(PlainForeignPtr r) finalizer = do
235   fs <- readIORef r
236   writeIORef r (finalizer : fs)
237   if (null fs)
238      then IO $ \s ->
239               case r of { IORef (STRef r#) ->
240               case mkWeak# r# () (foreignPtrFinalizer r) s of {  (# s1, w #) ->
241               (# s1, () #) }}
242      else return ()
243 addForeignPtrConcFinalizer_ f@(MallocPtr fo r) finalizer = do 
244   fs <- readIORef r
245   writeIORef r (finalizer : fs)
246   if (null fs)
247      then  IO $ \s -> 
248                case mkWeak# fo () (do foreignPtrFinalizer r; touch f) s of
249                   (# s1, w #) -> (# s1, () #)
250      else return ()
251
252 addForeignPtrConcFinalizer_ _ _ =
253   error "GHC.ForeignPtr: attempt to add a finalizer to plain pointer"
254
255 foreign import ccall "dynamic" 
256   mkFinalizer :: FinalizerPtr a -> Ptr a -> IO ()
257
258 foreignPtrFinalizer :: IORef [IO ()] -> IO ()
259 foreignPtrFinalizer r = do fs <- readIORef r; sequence_ fs
260
261 newForeignPtr_ :: Ptr a -> IO (ForeignPtr a)
262 -- ^Turns a plain memory reference into a foreign pointer that may be
263 -- associated with finalizers by using 'addForeignPtrFinalizer'.
264 newForeignPtr_ (Ptr obj) =  do
265   r <- newIORef []
266   return (ForeignPtr obj (PlainForeignPtr r))
267
268 touchForeignPtr :: ForeignPtr a -> IO ()
269 -- ^This function ensures that the foreign object in
270 -- question is alive at the given place in the sequence of IO
271 -- actions. In particular 'Foreign.ForeignPtr.withForeignPtr'
272 -- does a 'touchForeignPtr' after it
273 -- executes the user action.
274 -- 
275 -- Note that this function should not be used to express dependencies
276 -- between finalizers on 'ForeignPtr's.  For example, if the finalizer
277 -- for a 'ForeignPtr' @F1@ calls 'touchForeignPtr' on a second
278 -- 'ForeignPtr' @F2@, then the only guarantee is that the finalizer
279 -- for @F2@ is never started before the finalizer for @F1@.  They
280 -- might be started together if for example both @F1@ and @F2@ are
281 -- otherwise unreachable, and in that case the scheduler might end up
282 -- running the finalizer for @F2@ first.
283 --
284 -- In general, it is not recommended to use finalizers on separate
285 -- objects with ordering constraints between them.  To express the
286 -- ordering robustly requires explicit synchronisation using @MVar@s
287 -- between the finalizers, but even then the runtime sometimes runs
288 -- multiple finalizers sequentially in a single thread (for
289 -- performance reasons), so synchronisation between finalizers could
290 -- result in artificial deadlock.  Another alternative is to use
291 -- explicit reference counting.
292 --
293 touchForeignPtr (ForeignPtr fo r) = touch r
294
295 touch r = IO $ \s -> case touch# r s of s -> (# s, () #)
296
297 unsafeForeignPtrToPtr :: ForeignPtr a -> Ptr a
298 -- ^This function extracts the pointer component of a foreign
299 -- pointer.  This is a potentially dangerous operations, as if the
300 -- argument to 'unsafeForeignPtrToPtr' is the last usage
301 -- occurrence of the given foreign pointer, then its finalizer(s) will
302 -- be run, which potentially invalidates the plain pointer just
303 -- obtained.  Hence, 'touchForeignPtr' must be used
304 -- wherever it has to be guaranteed that the pointer lives on - i.e.,
305 -- has another usage occurrence.
306 --
307 -- To avoid subtle coding errors, hand written marshalling code
308 -- should preferably use 'Foreign.ForeignPtr.withForeignPtr' rather
309 -- than combinations of 'unsafeForeignPtrToPtr' and
310 -- 'touchForeignPtr'.  However, the later routines
311 -- are occasionally preferred in tool generated marshalling code.
312 unsafeForeignPtrToPtr (ForeignPtr fo r) = Ptr fo
313
314 castForeignPtr :: ForeignPtr a -> ForeignPtr b
315 -- ^This function casts a 'ForeignPtr'
316 -- parameterised by one type into another type.
317 castForeignPtr f = unsafeCoerce# f
318
319 -- | Causes the finalizers associated with a foreign pointer to be run
320 -- immediately.
321 finalizeForeignPtr :: ForeignPtr a -> IO ()
322 finalizeForeignPtr (ForeignPtr _ (PlainPtr _)) = return () -- no effect
323 finalizeForeignPtr (ForeignPtr _ foreignPtr) = do
324         finalizers <- readIORef refFinalizers
325         sequence_ finalizers
326         writeIORef refFinalizers []
327         where
328                 refFinalizers = case foreignPtr of
329                         (PlainForeignPtr ref) -> ref
330                         (MallocPtr     _ ref) -> ref
331