ForeignCall.lhs 6.93 KB
Newer Older
1 2 3 4 5 6
%
% (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
%
\section[Foreign]{Foreign calls}

\begin{code}
7
{-# OPTIONS -w #-}
8 9 10
-- The above warning supression flag is a temporary kludge.
-- While working on this module you are encouraged to remove it and fix
-- any warnings in the module. See
Ian Lynagh's avatar
Ian Lynagh committed
11
--     http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
12 13
-- for details

14 15
module ForeignCall (
	ForeignCall(..),
16
	Safety(..), playSafe,
17

18
	CExportSpec(..), CLabelString, isCLabelString, pprCLabelString,
19
	CCallSpec(..), 
20
	CCallTarget(..), isDynamicTarget,
21 22 23
	CCallConv(..), defaultCCallConv, ccallConvToInt, ccallConvAttribute,
    ) where

24
import FastString
25
import Binary
26
import Outputable
Ian Lynagh's avatar
Ian Lynagh committed
27 28

import Data.Char
29 30 31 32 33 34 35 36 37 38
\end{code}


%************************************************************************
%*									*
\subsubsection{Data types}
%*									*
%************************************************************************

\begin{code}
39 40
newtype ForeignCall = CCall CCallSpec
  deriving Eq
41
  {-! derive: Binary !-}
42 43 44 45

-- We may need more clues to distinguish foreign calls
-- but this simple printer will do for now
instance Outputable ForeignCall where
chak's avatar
chak committed
46
  ppr (CCall cc)  = ppr cc		
47 48 49 50 51 52 53
\end{code}

  
\begin{code}
data Safety
  = PlaySafe		-- Might invoke Haskell GC, or do a call back, or
			-- switch threads, etc.  So make sure things are
54 55 56 57 58 59 60 61
			-- tidy before the call. Additionally, in the threaded
			-- RTS we arrange for the external call to be executed
			-- by a separate OS thread, i.e., _concurrently_ to the
			-- execution of other Haskell threads.

      Bool              -- Indicates the deprecated "threadsafe" annotation
                        -- which is now an alias for "safe". This information
                        -- is never used except to emit a deprecation warning.
62 63 64

  | PlayRisky		-- None of the above can happen; the call will return
			-- without interacting with the runtime system at all
65
  deriving ( Eq, Show )
66
	-- Show used just for Show Lex.Token, I think
67
  {-! derive: Binary !-}
68 69

instance Outputable Safety where
Ian Lynagh's avatar
Ian Lynagh committed
70 71 72
  ppr (PlaySafe False) = ptext (sLit "safe")
  ppr (PlaySafe True)  = ptext (sLit "threadsafe")
  ppr PlayRisky = ptext (sLit "unsafe")
73

sof's avatar
sof committed
74 75 76
playSafe :: Safety -> Bool
playSafe PlaySafe{} = True
playSafe PlayRisky  = False
77 78 79 80 81 82 83 84 85 86
\end{code}


%************************************************************************
%*									*
\subsubsection{Calling C}
%*									*
%************************************************************************

\begin{code}
87 88 89 90
data CExportSpec
  = CExportStatic		-- foreign export ccall foo :: ty
	CLabelString		-- C Name of exported function
	CCallConv
91
  {-! derive: Binary !-}
92

93 94 95 96 97
data CCallSpec
  =  CCallSpec	CCallTarget	-- What to call
		CCallConv	-- Calling convention to use.
		Safety
  deriving( Eq )
98
  {-! derive: Binary !-}
99 100 101 102 103 104 105 106 107
\end{code}

The call target:

\begin{code}
data CCallTarget
  = StaticTarget  CLabelString  -- An "unboxed" ccall# to `fn'.
  | DynamicTarget 		-- First argument (an Addr#) is the function pointer
  deriving( Eq )
108
  {-! derive: Binary !-}
109

110
isDynamicTarget :: CCallTarget -> Bool
111
isDynamicTarget DynamicTarget = True
Ian Lynagh's avatar
Ian Lynagh committed
112
isDynamicTarget _             = False
113 114 115
\end{code}


116 117 118 119 120 121 122 123 124 125 126
Stuff to do with calling convention:

ccall:		Caller allocates parameters, *and* deallocates them.

stdcall: 	Caller allocates parameters, callee deallocates.
		Function name has @N after it, where N is number of arg bytes
		e.g.  _Foo@8

ToDo: The stdcall calling convention is x86 (win32) specific,
so perhaps we should emit a warning if it's being used on other
platforms.
127 128
 
See: http://www.programmersheaven.com/2/Calling-conventions
129 130

\begin{code}
131
data CCallConv = CCallConv | StdCallConv | CmmCallConv | PrimCallConv
132 133
  deriving (Eq)
  {-! derive: Binary !-}
134 135

instance Outputable CCallConv where
Ian Lynagh's avatar
Ian Lynagh committed
136 137 138
  ppr StdCallConv = ptext (sLit "stdcall")
  ppr CCallConv   = ptext (sLit "ccall")
  ppr CmmCallConv = ptext (sLit "C--")
139
  ppr PrimCallConv = ptext (sLit "prim")
140 141 142 143 144 145 146 147 148 149 150 151 152 153

defaultCCallConv :: CCallConv
defaultCCallConv = CCallConv

ccallConvToInt :: CCallConv -> Int
ccallConvToInt StdCallConv = 0
ccallConvToInt CCallConv   = 1
\end{code}

Generate the gcc attribute corresponding to the given
calling convention (used by PprAbsC):

\begin{code}
ccallConvAttribute :: CCallConv -> String
154
ccallConvAttribute StdCallConv = "__attribute__((__stdcall__))"
155 156 157
ccallConvAttribute CCallConv   = ""
\end{code}

158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
\begin{code}
type CLabelString = FastString		-- A C label, completely unencoded

pprCLabelString :: CLabelString -> SDoc
pprCLabelString lbl = ftext lbl

isCLabelString :: CLabelString -> Bool	-- Checks to see if this is a valid C label
isCLabelString lbl 
  = all ok (unpackFS lbl)
  where
    ok c = isAlphaNum c || c == '_' || c == '.'
	-- The '.' appears in e.g. "foo.so" in the 
	-- module part of a ExtName.  Maybe it should be separate
\end{code}


174 175 176
Printing into C files:

\begin{code}
177 178 179
instance Outputable CExportSpec where
  ppr (CExportStatic str _) = pprCLabelString str

180
instance Outputable CCallSpec where
181 182
  ppr (CCallSpec fun cconv safety)
    = hcat [ ifPprDebug callconv, ppr_fun fun ]
183
    where
184 185 186 187 188 189 190
      callconv = text "{-" <> ppr cconv <> text "-}"

      gc_suf | playSafe safety = text "_GC"
	     | otherwise       = empty

      ppr_fun DynamicTarget     = text "__dyn_ccall" <> gc_suf <+> text "\"\""
      ppr_fun (StaticTarget fn) = text "__ccall"     <> gc_suf <+> pprCLabelString fn
191 192 193
\end{code}


194 195 196 197 198 199
%************************************************************************
%*									*
\subsubsection{Misc}
%*									*
%************************************************************************

200 201 202
\begin{code}
{-* Generated by DrIFT-v1.0 : Look, but Don't Touch. *-}
instance Binary ForeignCall where
203 204
    put_ bh (CCall aa) = put_ bh aa
    get bh = do aa <- get bh; return (CCall aa)
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249

instance Binary Safety where
    put_ bh (PlaySafe aa) = do
	    putByte bh 0
	    put_ bh aa
    put_ bh PlayRisky = do
	    putByte bh 1
    get bh = do
	    h <- getByte bh
	    case h of
	      0 -> do aa <- get bh
		      return (PlaySafe aa)
	      _ -> do return PlayRisky

instance Binary CExportSpec where
    put_ bh (CExportStatic aa ab) = do
	    put_ bh aa
	    put_ bh ab
    get bh = do
	  aa <- get bh
	  ab <- get bh
	  return (CExportStatic aa ab)

instance Binary CCallSpec where
    put_ bh (CCallSpec aa ab ac) = do
	    put_ bh aa
	    put_ bh ab
	    put_ bh ac
    get bh = do
	  aa <- get bh
	  ab <- get bh
	  ac <- get bh
	  return (CCallSpec aa ab ac)

instance Binary CCallTarget where
    put_ bh (StaticTarget aa) = do
	    putByte bh 0
	    put_ bh aa
    put_ bh DynamicTarget = do
	    putByte bh 1
    get bh = do
	    h <- getByte bh
	    case h of
	      0 -> do aa <- get bh
		      return (StaticTarget aa)
250
	      _ -> do return DynamicTarget
251 252 253 254 255 256

instance Binary CCallConv where
    put_ bh CCallConv = do
	    putByte bh 0
    put_ bh StdCallConv = do
	    putByte bh 1
257 258
    put_ bh PrimCallConv = do
	    putByte bh 2
259 260 261 262
    get bh = do
	    h <- getByte bh
	    case h of
	      0 -> do return CCallConv
263 264
	      1 -> do return StdCallConv
	      _ -> do return PrimCallConv
265
\end{code}