[project @ 2003-06-19 13:20:37 by simonmar]
[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 import GHC.Num
44 #elif defined(__NHC__)
45 import NHC.FFI                  ( FinalizerPtr, CInt(..) )
46 import IO                       ( bracket )
47 #else
48 import Control.Exception        ( bracket )
49 #endif
50
51 #ifdef __HUGS__
52 import Hugs.ForeignPtr          ( FinalizerPtr )
53 #endif
54
55
56 -- exported functions
57 -- ------------------
58
59 -- |Allocate space for storable type.  The size of the area allocated
60 -- is determined by the 'sizeOf' method from the instance of
61 -- 'Storable' for the appropriate type.
62 --
63 malloc :: Storable a => IO (Ptr a)
64 malloc  = doMalloc undefined
65   where
66     doMalloc       :: Storable a => a -> IO (Ptr a)
67     doMalloc dummy  = mallocBytes (sizeOf dummy)
68
69 -- |Allocate given number of bytes of storage, equivalent to C\'s @malloc()@.
70 --
71 mallocBytes      :: Int -> IO (Ptr a)
72 mallocBytes size  = failWhenNULL "malloc" (_malloc (fromIntegral size))
73
74 -- |Temporarily allocate space for a storable type.
75 --
76 -- * the pointer passed as an argument to the function must /not/ escape from
77 --   this function; in other words, in @alloca f@ the allocated storage must
78 --   not be used after @f@ returns
79 --
80 alloca :: Storable a => (Ptr a -> IO b) -> IO b
81 alloca  = doAlloca undefined
82   where
83     doAlloca       :: Storable a => a -> (Ptr a -> IO b) -> IO b
84     doAlloca dummy  = allocaBytes (sizeOf dummy)
85
86 -- |Temporarily allocate the given number of bytes of storage.
87 --
88 -- * the pointer passed as an argument to the function must /not/ escape from
89 --   this function; in other words, in @allocaBytes n f@ the allocated storage
90 --   must not be used after @f@ returns
91 --
92 #ifdef __GLASGOW_HASKELL__
93 allocaBytes :: Int -> (Ptr a -> IO b) -> IO b
94 allocaBytes (I# size) action = IO $ \ s ->
95      case newPinnedByteArray# size s      of { (# s, mbarr# #) ->
96      case unsafeFreezeByteArray# mbarr# s of { (# s, barr#  #) ->
97      let addr = Ptr (byteArrayContents# barr#) in
98      case action addr    of { IO action ->
99      case action s       of { (# s, r #) ->
100      case touch# barr# s of { s ->
101      (# s, r #)
102   }}}}}
103 #else
104 allocaBytes      :: Int -> (Ptr a -> IO b) -> IO b
105 allocaBytes size  = bracket (mallocBytes size) free
106 #endif
107
108 -- |Adjust a malloc\'ed storage area to the given size of the required type
109 -- (corresponds to C\'s @realloc()@).
110 --
111 realloc :: Storable b => Ptr a -> IO (Ptr b)
112 realloc  = doRealloc undefined
113   where
114     doRealloc           :: Storable b => b -> Ptr a -> IO (Ptr b)
115     doRealloc dummy ptr  = let
116                              size = fromIntegral (sizeOf dummy)
117                            in
118                            failWhenNULL "realloc" (_realloc ptr size)
119
120 -- |Adjust a malloc\'ed storage area to the given size (equivalent to
121 -- C\'s @realloc()@).
122 --
123 reallocBytes          :: Ptr a -> Int -> IO (Ptr a)
124 reallocBytes ptr 0     = do free ptr; return nullPtr
125 reallocBytes ptr size  = 
126   failWhenNULL "realloc" (_realloc ptr (fromIntegral size))
127
128 -- |Free malloc\'ed storage (equivalent to
129 -- C\'s @free()@)
130 --
131 free :: Ptr a -> IO ()
132 free  = _free
133
134
135 -- auxilliary routines
136 -- -------------------
137
138 -- asserts that the pointer returned from the action in the second argument is
139 -- non-null
140 --
141 failWhenNULL :: String -> IO (Ptr a) -> IO (Ptr a)
142 failWhenNULL name f = do
143    addr <- f
144    if addr == nullPtr
145 #ifdef __GLASGOW_HASKELL__
146       then ioException (IOError Nothing ResourceExhausted name 
147                                         "out of memory" Nothing)
148 #else
149       then ioError (userError (name++": out of memory"))
150 #endif
151       else return addr
152
153 -- basic C routines needed for memory allocation
154 --
155 foreign import ccall unsafe "stdlib.h malloc"  _malloc  ::          CSize -> IO (Ptr a)
156 foreign import ccall unsafe "stdlib.h realloc" _realloc :: Ptr a -> CSize -> IO (Ptr b)
157 foreign import ccall unsafe "stdlib.h free"    _free    :: Ptr a -> IO ()
158
159 -- | A pointer to a foreign function equivalent to 'free', which may be used
160 -- as a finalizer for storage allocated with 'malloc' or 'mallocBytes'.
161 foreign import ccall unsafe "stdlib.h &free" finalizerFree :: FinalizerPtr a