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