[project @ 2003-05-27 16:57:09 by malcolm]
[ghc-base.git] / Foreign / Marshal / Alloc.hs
1 {-# OPTIONS -fno-implicit-prelude #-}
2 -----------------------------------------------------------------------------
3 -- |
4 -- Module      :  Foreign.Marshal.Alloc
5 -- Copyright   :  (c) The FFI task force 2001
6 -- License     :  BSD-style (see the file libraries/base/LICENSE)
7 -- 
8 -- Maintainer  :  ffi@haskell.org
9 -- Stability   :  provisional
10 -- Portability :  portable
11 --
12 -- Marshalling support: basic routines for memory allocation
13 --
14 -----------------------------------------------------------------------------
15
16 module Foreign.Marshal.Alloc (
17   -- * Allocation
18   malloc,       -- :: Storable a =>        IO (Ptr a)
19   mallocBytes,  -- ::               Int -> IO (Ptr a)
20
21   alloca,       -- :: Storable a =>        (Ptr a -> IO b) -> IO b
22   allocaBytes,  -- ::               Int -> (Ptr a -> IO b) -> IO b
23
24   realloc,      -- :: Storable b => Ptr a        -> IO (Ptr b)
25   reallocBytes, -- ::               Ptr a -> Int -> IO (Ptr a)
26
27   free,         -- :: Ptr a -> IO ()
28   finalizerFree -- :: FinalizerPtr a
29 ) where
30
31 import Data.Maybe
32 import Foreign.Ptr              ( Ptr, nullPtr, FunPtr )
33 import Foreign.C.Types          ( CSize )
34 import Foreign.Storable         ( Storable(sizeOf) )
35
36 #ifdef __GLASGOW_HASKELL__
37 import Foreign.ForeignPtr       ( FinalizerPtr )
38 import GHC.IOBase
39 import GHC.Real
40 import GHC.Ptr
41 import GHC.Err
42 import GHC.Base
43 #elif defined(__NHC__)
44 import NHC.FFI                  ( FinalizerPtr, CInt(..) )
45 import IO                       ( bracket )
46 #else
47 import Control.Exception        ( bracket )
48 #endif
49
50 #ifdef __HUGS__
51 import Hugs.ForeignPtr          ( FinalizerPtr )
52 #endif
53
54
55 -- exported functions
56 -- ------------------
57
58 -- |Allocate space for storable type.  The size of the area allocated
59 -- is determined by the 'sizeOf' method from the instance of
60 -- 'Storable' for the appropriate type.
61 --
62 malloc :: Storable a => IO (Ptr a)
63 malloc  = doMalloc undefined
64   where
65     doMalloc       :: Storable a => a -> IO (Ptr a)
66     doMalloc dummy  = mallocBytes (sizeOf dummy)
67
68 -- |Allocate given number of bytes of storage, equivalent to C\'s @malloc()@.
69 --
70 mallocBytes      :: Int -> IO (Ptr a)
71 mallocBytes size  = failWhenNULL "malloc" (_malloc (fromIntegral size))
72
73 -- |Temporarily allocate space for a storable type.
74 --
75 -- * the pointer passed as an argument to the function must /not/ escape from
76 --   this function; in other words, in @alloca f@ the allocated storage must
77 --   not be used after @f@ returns
78 --
79 alloca :: Storable a => (Ptr a -> IO b) -> IO b
80 alloca  = doAlloca undefined
81   where
82     doAlloca       :: Storable a => a -> (Ptr a -> IO b) -> IO b
83     doAlloca dummy  = allocaBytes (sizeOf dummy)
84
85 -- |Temporarily allocate the given number of bytes of storage.
86 --
87 -- * the pointer passed as an argument to the function must /not/ escape from
88 --   this function; in other words, in @allocaBytes n f@ the allocated storage
89 --   must not be used after @f@ returns
90 --
91 #ifdef __GLASGOW_HASKELL__
92 allocaBytes :: Int -> (Ptr a -> IO b) -> IO b
93 allocaBytes (I# size) action = IO $ \ s ->
94      case newPinnedByteArray# size s      of { (# s, mbarr# #) ->
95      case unsafeFreezeByteArray# mbarr# s of { (# s, barr#  #) ->
96      let addr = Ptr (byteArrayContents# barr#) in
97      case action addr    of { IO action ->
98      case action s       of { (# s, r #) ->
99      case touch# barr# s of { s ->
100      (# s, r #)
101   }}}}}
102 #else
103 allocaBytes      :: Int -> (Ptr a -> IO b) -> IO b
104 allocaBytes size  = bracket (mallocBytes size) free
105 #endif
106
107 -- |Adjust a malloc\'ed storage area to the given size of the required type
108 -- (corresponds to C\'s @realloc()@).
109 --
110 realloc :: Storable b => Ptr a -> IO (Ptr b)
111 realloc  = doRealloc undefined
112   where
113     doRealloc           :: Storable b => b -> Ptr a -> IO (Ptr b)
114     doRealloc dummy ptr  = let
115                              size = fromIntegral (sizeOf dummy)
116                            in
117                            failWhenNULL "realloc" (_realloc ptr size)
118
119 -- |Adjust a malloc\'ed storage area to the given size (equivalent to
120 -- C\'s @realloc()@).
121 --
122 reallocBytes          :: Ptr a -> Int -> IO (Ptr a)
123 reallocBytes ptr size  = 
124   failWhenNULL "realloc" (_realloc ptr (fromIntegral size))
125
126 -- |Free malloc\'ed storage (equivalent to
127 -- C\'s @free()@)
128 --
129 free :: Ptr a -> IO ()
130 free  = _free
131
132
133 -- auxilliary routines
134 -- -------------------
135
136 -- asserts that the pointer returned from the action in the second argument is
137 -- non-null
138 --
139 failWhenNULL :: String -> IO (Ptr a) -> IO (Ptr a)
140 failWhenNULL name f = do
141    addr <- f
142    if addr == nullPtr
143 #ifdef __GLASGOW_HASKELL__
144       then ioException (IOError Nothing ResourceExhausted name 
145                                         "out of memory" Nothing)
146 #else
147       then ioError (userError (name++": out of memory"))
148 #endif
149       else return addr
150
151 -- basic C routines needed for memory allocation
152 --
153 foreign import ccall unsafe "stdlib.h malloc"  _malloc  ::          CSize -> IO (Ptr a)
154 foreign import ccall unsafe "stdlib.h realloc" _realloc :: Ptr a -> CSize -> IO (Ptr b)
155 foreign import ccall unsafe "stdlib.h free"    _free    :: Ptr a -> IO ()
156
157 -- | A pointer to a foreign function equivalent to 'free', which may be used
158 -- as a finalizer for storage allocated with 'malloc' or 'mallocBytes'.
159 foreign import ccall unsafe "stdlib.h &free" finalizerFree :: FinalizerPtr a