Move instance of Show Ptr to Ptr.hs (fewer orphans)
[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
90 -- |A Finalizer is represented as a pointer to a foreign function that, at
91 -- finalisation time, gets as an argument a plain pointer variant of the
92 -- foreign pointer that the finalizer is associated with.
93 -- 
94 type FinalizerPtr a = FunPtr (Ptr a -> IO ())
95
96 newConcForeignPtr :: Ptr a -> IO () -> IO (ForeignPtr a)
97 --
98 -- ^Turns a plain memory reference into a foreign object by
99 -- associating a finalizer - given by the monadic operation - with the
100 -- reference.  The storage manager will start the finalizer, in a
101 -- separate thread, some time after the last reference to the
102 -- @ForeignPtr@ is dropped.  There is no guarantee of promptness, and
103 -- in fact there is no guarantee that the finalizer will eventually
104 -- run at all.
105 --
106 -- Note that references from a finalizer do not necessarily prevent
107 -- another object from being finalized.  If A's finalizer refers to B
108 -- (perhaps using 'touchForeignPtr', then the only guarantee is that
109 -- B's finalizer will never be started before A's.  If both A and B
110 -- are unreachable, then both finalizers will start together.  See
111 -- 'touchForeignPtr' for more on finalizer ordering.
112 --
113 newConcForeignPtr p finalizer
114   = do fObj <- newForeignPtr_ p
115        addForeignPtrConcFinalizer fObj finalizer
116        return fObj
117
118 mallocForeignPtr :: Storable a => IO (ForeignPtr a)
119 -- ^ Allocate some memory and return a 'ForeignPtr' to it.  The memory
120 -- will be released automatically when the 'ForeignPtr' is discarded.
121 --
122 -- 'mallocForeignPtr' is equivalent to
123 --
124 -- >    do { p <- malloc; newForeignPtr finalizerFree p }
125 -- 
126 -- although it may be implemented differently internally: you may not
127 -- assume that the memory returned by 'mallocForeignPtr' has been
128 -- allocated with 'Foreign.Marshal.Alloc.malloc'.
129 --
130 -- GHC notes: 'mallocForeignPtr' has a heavily optimised
131 -- implementation in GHC.  It uses pinned memory in the garbage
132 -- collected heap, so the 'ForeignPtr' does not require a finalizer to
133 -- free the memory.  Use of 'mallocForeignPtr' and associated
134 -- functions is strongly recommended in preference to 'newForeignPtr'
135 -- with a finalizer.
136 -- 
137 mallocForeignPtr = doMalloc undefined
138   where doMalloc :: Storable b => b -> IO (ForeignPtr b)
139         doMalloc a = do
140           r <- newIORef []
141           IO $ \s ->
142             case newPinnedByteArray# size s of { (# s, mbarr# #) ->
143              (# s, ForeignPtr (byteArrayContents# (unsafeCoerce# mbarr#))
144                               (MallocPtr mbarr# r) #)
145             }
146             where (I# size) = sizeOf a
147
148 -- | This function is similar to 'mallocForeignPtr', except that the
149 -- size of the memory required is given explicitly as a number of bytes.
150 mallocForeignPtrBytes :: Int -> IO (ForeignPtr a)
151 mallocForeignPtrBytes (I# size) = do 
152   r <- newIORef []
153   IO $ \s ->
154      case newPinnedByteArray# size s      of { (# s, mbarr# #) ->
155        (# s, ForeignPtr (byteArrayContents# (unsafeCoerce# mbarr#))
156                         (MallocPtr mbarr# r) #)
157      }
158
159 -- | Allocate some memory and return a 'ForeignPtr' to it.  The memory
160 -- will be released automatically when the 'ForeignPtr' is discarded.
161 --
162 -- GHC notes: 'mallocPlainForeignPtr' has a heavily optimised
163 -- implementation in GHC.  It uses pinned memory in the garbage
164 -- collected heap, as for mallocForeignPtr. Unlike mallocForeignPtr, a
165 -- ForeignPtr created with mallocPlainForeignPtr carries no finalizers.
166 -- It is not possible to add a finalizer to a ForeignPtr created with
167 -- mallocPlainForeignPtr. This is useful for ForeignPtrs that will live
168 -- only inside Haskell (such as those created for packed strings).
169 -- Attempts to add a finalizer to a ForeignPtr created this way, or to
170 -- finalize such a pointer, will throw an exception.
171 -- 
172 mallocPlainForeignPtr :: Storable a => IO (ForeignPtr a)
173 mallocPlainForeignPtr = doMalloc undefined
174   where doMalloc :: Storable b => b -> IO (ForeignPtr b)
175         doMalloc a = IO $ \s ->
176             case newPinnedByteArray# size s of { (# s, mbarr# #) ->
177              (# s, ForeignPtr (byteArrayContents# (unsafeCoerce# mbarr#))
178                               (PlainPtr mbarr#) #)
179             }
180             where (I# size) = sizeOf a
181
182 -- | This function is similar to 'mallocForeignPtrBytes', except that
183 -- the internally an optimised ForeignPtr representation with no
184 -- finalizer is used. Attempts to add a finalizer will cause an
185 -- exception to be thrown.
186 mallocPlainForeignPtrBytes :: Int -> IO (ForeignPtr a)
187 mallocPlainForeignPtrBytes (I# size) = IO $ \s ->
188     case newPinnedByteArray# size s      of { (# s, mbarr# #) ->
189        (# s, ForeignPtr (byteArrayContents# (unsafeCoerce# mbarr#))
190                         (PlainPtr mbarr#) #)
191      }
192
193 addForeignPtrFinalizer :: FinalizerPtr a -> ForeignPtr a -> IO ()
194 -- ^This function adds a finalizer to the given foreign object.  The
195 -- finalizer will run /before/ all other finalizers for the same
196 -- object which have already been registered.
197 addForeignPtrFinalizer finalizer fptr = 
198   addForeignPtrConcFinalizer fptr 
199         (mkFinalizer finalizer (unsafeForeignPtrToPtr fptr))
200
201 addForeignPtrConcFinalizer :: ForeignPtr a -> IO () -> IO ()
202 -- ^This function adds a finalizer to the given @ForeignPtr@.  The
203 -- finalizer will run /before/ all other finalizers for the same
204 -- object which have already been registered.
205 --
206 -- This is a variant of @addForeignPtrFinalizer@, where the finalizer
207 -- is an arbitrary @IO@ action.  When it is invoked, the finalizer
208 -- will run in a new thread.
209 --
210 -- NB. Be very careful with these finalizers.  One common trap is that
211 -- if a finalizer references another finalized value, it does not
212 -- prevent that value from being finalized.  In particular, 'Handle's
213 -- are finalized objects, so a finalizer should not refer to a 'Handle'
214 -- (including @stdout@, @stdin@ or @stderr@).
215 --
216 addForeignPtrConcFinalizer (ForeignPtr a c) finalizer = 
217   addForeignPtrConcFinalizer_ c finalizer
218
219 addForeignPtrConcFinalizer_ f@(PlainForeignPtr r) finalizer = do
220   fs <- readIORef r
221   writeIORef r (finalizer : fs)
222   if (null fs)
223      then IO $ \s ->
224               case r of { IORef (STRef r#) ->
225               case mkWeak# r# () (foreignPtrFinalizer r) s of {  (# s1, w #) ->
226               (# s1, () #) }}
227      else return ()
228 addForeignPtrConcFinalizer_ f@(MallocPtr fo r) finalizer = do 
229   fs <- readIORef r
230   writeIORef r (finalizer : fs)
231   if (null fs)
232      then  IO $ \s -> 
233                case mkWeak# fo () (do foreignPtrFinalizer r; touch f) s of
234                   (# s1, w #) -> (# s1, () #)
235      else return ()
236
237 addForeignPtrConcFinalizer_ _ _ =
238   error "GHC.ForeignPtr: attempt to add a finalizer to plain pointer"
239
240 foreign import ccall "dynamic" 
241   mkFinalizer :: FinalizerPtr a -> Ptr a -> IO ()
242
243 foreignPtrFinalizer :: IORef [IO ()] -> IO ()
244 foreignPtrFinalizer r = do fs <- readIORef r; sequence_ fs
245
246 newForeignPtr_ :: Ptr a -> IO (ForeignPtr a)
247 -- ^Turns a plain memory reference into a foreign pointer that may be
248 -- associated with finalizers by using 'addForeignPtrFinalizer'.
249 newForeignPtr_ (Ptr obj) =  do
250   r <- newIORef []
251   return (ForeignPtr obj (PlainForeignPtr r))
252
253 touchForeignPtr :: ForeignPtr a -> IO ()
254 -- ^This function ensures that the foreign object in
255 -- question is alive at the given place in the sequence of IO
256 -- actions. In particular 'Foreign.ForeignPtr.withForeignPtr'
257 -- does a 'touchForeignPtr' after it
258 -- executes the user action.
259 -- 
260 -- Note that this function should not be used to express dependencies
261 -- between finalizers on 'ForeignPtr's.  For example, if the finalizer
262 -- for a 'ForeignPtr' @F1@ calls 'touchForeignPtr' on a second
263 -- 'ForeignPtr' @F2@, then the only guarantee is that the finalizer
264 -- for @F2@ is never started before the finalizer for @F1@.  They
265 -- might be started together if for example both @F1@ and @F2@ are
266 -- otherwise unreachable, and in that case the scheduler might end up
267 -- running the finalizer for @F2@ first.
268 --
269 -- In general, it is not recommended to use finalizers on separate
270 -- objects with ordering constraints between them.  To express the
271 -- ordering robustly requires explicit synchronisation using @MVar@s
272 -- between the finalizers, but even then the runtime sometimes runs
273 -- multiple finalizers sequentially in a single thread (for
274 -- performance reasons), so synchronisation between finalizers could
275 -- result in artificial deadlock.  Another alternative is to use
276 -- explicit reference counting.
277 --
278 touchForeignPtr (ForeignPtr fo r) = touch r
279
280 touch r = IO $ \s -> case touch# r s of s -> (# s, () #)
281
282 unsafeForeignPtrToPtr :: ForeignPtr a -> Ptr a
283 -- ^This function extracts the pointer component of a foreign
284 -- pointer.  This is a potentially dangerous operations, as if the
285 -- argument to 'unsafeForeignPtrToPtr' is the last usage
286 -- occurrence of the given foreign pointer, then its finalizer(s) will
287 -- be run, which potentially invalidates the plain pointer just
288 -- obtained.  Hence, 'touchForeignPtr' must be used
289 -- wherever it has to be guaranteed that the pointer lives on - i.e.,
290 -- has another usage occurrence.
291 --
292 -- To avoid subtle coding errors, hand written marshalling code
293 -- should preferably use 'Foreign.ForeignPtr.withForeignPtr' rather
294 -- than combinations of 'unsafeForeignPtrToPtr' and
295 -- 'touchForeignPtr'.  However, the later routines
296 -- are occasionally preferred in tool generated marshalling code.
297 unsafeForeignPtrToPtr (ForeignPtr fo r) = Ptr fo
298
299 castForeignPtr :: ForeignPtr a -> ForeignPtr b
300 -- ^This function casts a 'ForeignPtr'
301 -- parameterised by one type into another type.
302 castForeignPtr f = unsafeCoerce# f
303
304 -- | Causes the finalizers associated with a foreign pointer to be run
305 -- immediately.
306 finalizeForeignPtr :: ForeignPtr a -> IO ()
307 finalizeForeignPtr (ForeignPtr _ (PlainPtr _)) = return () -- no effect
308 finalizeForeignPtr (ForeignPtr _ foreignPtr) = do
309         finalizers <- readIORef refFinalizers
310         sequence_ finalizers
311         writeIORef refFinalizers []
312         where
313                 refFinalizers = case foreignPtr of
314                         (PlainForeignPtr ref) -> ref
315                         (MallocPtr     _ ref) -> ref
316