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