65588ff76b338937eae81df755a3ffb587167e5e
[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   -- * Memory allocation
18   -- ** Local allocation
19   alloca,       -- :: Storable a =>        (Ptr a -> IO b) -> IO b
20   allocaBytes,  -- ::               Int -> (Ptr a -> IO b) -> IO b
21
22   -- ** Dynamic allocation
23   malloc,       -- :: Storable a =>        IO (Ptr a)
24   mallocBytes,  -- ::               Int -> IO (Ptr a)
25
26   realloc,      -- :: Storable b => Ptr a        -> IO (Ptr b)
27   reallocBytes, -- ::               Ptr a -> Int -> IO (Ptr a)
28
29   free,         -- :: Ptr a -> IO ()
30   finalizerFree -- :: FinalizerPtr a
31 ) where
32
33 import Data.Maybe
34 import Foreign.Ptr              ( Ptr, nullPtr, FunPtr )
35 import Foreign.C.Types          ( CSize )
36 import Foreign.Storable         ( Storable(sizeOf) )
37
38 #ifdef __GLASGOW_HASKELL__
39 import Foreign.ForeignPtr       ( FinalizerPtr )
40 import GHC.IOBase
41 import GHC.Real
42 import GHC.Ptr
43 import GHC.Err
44 import GHC.Base
45 import GHC.Num
46 #elif defined(__NHC__)
47 import NHC.FFI                  ( FinalizerPtr, CInt(..) )
48 import IO                       ( bracket )
49 #else
50 import Control.Exception        ( bracket )
51 #endif
52
53 #ifdef __HUGS__
54 import Hugs.ForeignPtr          ( FinalizerPtr )
55 #endif
56
57
58 -- exported functions
59 -- ------------------
60
61 -- |Allocate a block of memory that is sufficient to hold values of type
62 -- @a@.  The size of the area allocated is determined by the 'sizeOf'
63 -- method from the instance of 'Storable' for the appropriate type.
64 --
65 -- The memory may be deallocated using 'free' or 'finalizerFree' when
66 -- no longer required.
67 --
68 malloc :: Storable a => IO (Ptr a)
69 malloc  = doMalloc undefined
70   where
71     doMalloc       :: Storable b => b -> IO (Ptr b)
72     doMalloc dummy  = mallocBytes (sizeOf dummy)
73
74 -- |Allocate a block of memory of the given number of bytes.
75 -- The block of memory is sufficiently aligned for any of the basic
76 -- foreign types that fits into a memory block of the allocated size.
77 --
78 -- The memory may be deallocated using 'free' or 'finalizerFree' when
79 -- no longer required.
80 --
81 mallocBytes      :: Int -> IO (Ptr a)
82 mallocBytes size  = failWhenNULL "malloc" (_malloc (fromIntegral size))
83
84 -- |@'alloca' f@ executes the computation @f@, passing as argument
85 -- a pointer to a temporarily allocated block of memory sufficient to
86 -- hold values of type @a@.
87 --
88 -- The memory is freed when @f@ terminates (either normally or via an
89 -- exception), so the pointer passed to @f@ must /not/ be used after this.
90 --
91 alloca :: Storable a => (Ptr a -> IO b) -> IO b
92 alloca  = doAlloca undefined
93   where
94     doAlloca       :: Storable a' => a' -> (Ptr a' -> IO b') -> IO b'
95     doAlloca dummy  = allocaBytes (sizeOf dummy)
96
97 -- |@'allocaBytes' n f@ executes the computation @f@, passing as argument
98 -- a pointer to a temporarily allocated block of memory of @n@ bytes.
99 -- The block of memory is sufficiently aligned for any of the basic
100 -- foreign types that fits into a memory block of the allocated size.
101 --
102 -- The memory is freed when @f@ terminates (either normally or via an
103 -- exception), so the pointer passed to @f@ must /not/ be used after this.
104 --
105 #ifdef __GLASGOW_HASKELL__
106 allocaBytes :: Int -> (Ptr a -> IO b) -> IO b
107 allocaBytes (I# size) action = IO $ \ s ->
108      case newPinnedByteArray# size s      of { (# s, mbarr# #) ->
109      case unsafeFreezeByteArray# mbarr# s of { (# s, barr#  #) ->
110      let addr = Ptr (byteArrayContents# barr#) in
111      case action addr    of { IO action ->
112      case action s       of { (# s, r #) ->
113      case touch# barr# s of { s ->
114      (# s, r #)
115   }}}}}
116 #else
117 allocaBytes      :: Int -> (Ptr a -> IO b) -> IO b
118 allocaBytes size  = bracket (mallocBytes size) free
119 #endif
120
121 -- |Resize a memory area that was allocated with 'malloc' or 'mallocBytes'
122 -- to the size needed to store values of type @b@.  The returned pointer
123 -- may refer to an entirely different memory area, but will be suitably
124 -- aligned to hold values of type @b@.  The contents of the referenced
125 -- memory area will be the same as of the original pointer up to the
126 -- minimum of the original size and the size of values of type @b@.
127 --
128 -- If the argument to 'realloc' is 'nullPtr', 'realloc' behaves like
129 -- 'malloc'.
130 --
131 realloc :: Storable b => Ptr a -> IO (Ptr b)
132 realloc  = doRealloc undefined
133   where
134     doRealloc           :: Storable b' => b' -> Ptr a' -> IO (Ptr b')
135     doRealloc dummy ptr  = let
136                              size = fromIntegral (sizeOf dummy)
137                            in
138                            failWhenNULL "realloc" (_realloc ptr size)
139
140 -- |Resize a memory area that was allocated with 'malloc' or 'mallocBytes'
141 -- to the given size.  The returned pointer may refer to an entirely
142 -- different memory area, but will be sufficiently aligned for any of the
143 -- basic foreign types that fits into a memory block of the given size.
144 -- The contents of the referenced memory area will be the same as of
145 -- the original pointer up to the minimum of the original size and the
146 -- given size.
147 --
148 -- If the pointer argument to 'reallocBytes' is 'nullPtr', 'reallocBytes'
149 -- behaves like 'malloc'.  If the requested size is 0, 'reallocBytes'
150 -- behaves like 'free'.
151 --
152 reallocBytes          :: Ptr a -> Int -> IO (Ptr a)
153 reallocBytes ptr 0     = do free ptr; return nullPtr
154 reallocBytes ptr size  = 
155   failWhenNULL "realloc" (_realloc ptr (fromIntegral size))
156
157 -- |Free a block of memory that was allocated with 'malloc',
158 -- 'mallocBytes', 'realloc', 'reallocBytes', 'Foreign.Marshal.Utils.new'
159 -- or any of the @new@/X/ functions in "Foreign.Marshal.Array" or
160 -- "Foreign.C.String".
161 --
162 free :: Ptr a -> IO ()
163 free  = _free
164
165
166 -- auxilliary routines
167 -- -------------------
168
169 -- asserts that the pointer returned from the action in the second argument is
170 -- non-null
171 --
172 failWhenNULL :: String -> IO (Ptr a) -> IO (Ptr a)
173 failWhenNULL name f = do
174    addr <- f
175    if addr == nullPtr
176 #ifdef __GLASGOW_HASKELL__
177       then ioException (IOError Nothing ResourceExhausted name 
178                                         "out of memory" Nothing)
179 #else
180       then ioError (userError (name++": out of memory"))
181 #endif
182       else return addr
183
184 -- basic C routines needed for memory allocation
185 --
186 foreign import ccall unsafe "stdlib.h malloc"  _malloc  ::          CSize -> IO (Ptr a)
187 foreign import ccall unsafe "stdlib.h realloc" _realloc :: Ptr a -> CSize -> IO (Ptr b)
188 foreign import ccall unsafe "stdlib.h free"    _free    :: Ptr a -> IO ()
189
190 -- | A pointer to a foreign function equivalent to 'free', which may be
191 -- used as a finalizer (cf 'Foreign.ForeignPtr.ForeignPtr') for storage
192 -- allocated with 'malloc', 'mallocBytes', 'realloc' or 'reallocBytes'.
193 foreign import ccall unsafe "stdlib.h &free" finalizerFree :: FinalizerPtr a