1 {-# OPTIONS_GHC -cpp -fffi #-}
2 -----------------------------------------------------------------------------
4 -- Module : System.Process.Internals
5 -- Copyright : (c) The University of Glasgow 2004
6 -- License : BSD-style (see the file libraries/base/LICENSE)
8 -- Maintainer : libraries@haskell.org
9 -- Stability : experimental
10 -- Portability : portable
12 -- Operations for creating and interacting with sub-processes.
14 -----------------------------------------------------------------------------
17 module System.Process.Internals (
18 ProcessHandle(..), PHANDLE,
19 #if !defined(mingw32_HOST_OS) && !defined(__MINGW32__)
20 pPrPr_disableITimers, c_execvpe,
21 # ifdef __GLASGOW_HASKELL__
24 ignoreSignal, defaultSignal,
26 # ifdef __GLASGOW_HASKELL__
27 runProcessWin32, translate,
33 withFilePathException, withCEnvironment
36 import Prelude -- necessary to get dependencies right
38 #if !defined(mingw32_HOST_OS) && !defined(__MINGW32__)
39 import System.Posix.Types ( CPid )
40 import System.IO ( Handle )
42 import Data.Word ( Word32 )
45 import Data.Maybe ( fromMaybe )
46 # ifdef __GLASGOW_HASKELL__
47 import GHC.IOBase ( haFD, FD, Exception(..), IOException(..) )
48 import GHC.Handle ( stdin, stdout, stderr, withHandle_ )
50 import Hugs.Exception ( Exception(..), IOException(..) )
53 import Control.Exception ( handle, throwIO )
57 #if defined(mingw32_HOST_OS)
58 import Control.Monad ( when )
59 import System.Directory ( doesFileExist )
60 import Control.Exception ( catchJust, ioErrors )
61 import System.IO.Error ( isDoesNotExistError, doesNotExistErrorType,
63 import System.Environment ( getEnv )
64 import System.Directory.Internals ( parseSearchPath, joinFileName )
68 {-# CFILES cbits/execvpe.c #-}
71 #include "HsBaseConfig.h"
73 -- ----------------------------------------------------------------------------
76 {- | A handle to a process, which can be used to wait for termination
77 of the process using 'waitForProcess'.
79 None of the process-creation functions in this library wait for
80 termination: they all return a 'ProcessHandle' which may be used
81 to wait for the process later.
83 #if !defined(mingw32_HOST_OS) && !defined(__MINGW32__)
89 newtype ProcessHandle = ProcessHandle PHANDLE
91 -- ----------------------------------------------------------------------------
93 #if !defined(mingw32_HOST_OS) && !defined(__MINGW32__)
95 -- this function disables the itimer, which would otherwise cause confusing
96 -- signals to be sent to the new process.
97 foreign import ccall unsafe "pPrPr_disableITimers"
98 pPrPr_disableITimers :: IO ()
100 foreign import ccall unsafe "execvpe"
101 c_execvpe :: CString -> Ptr CString -> Ptr CString -> IO CInt
105 #if !defined(mingw32_HOST_OS) && !defined(__MINGW32__)
107 #ifdef __GLASGOW_HASKELL__
108 -- -----------------------------------------------------------------------------
109 -- POSIX runProcess with signal handling in the child
113 -> FilePath -- ^ Filename of the executable
114 -> [String] -- ^ Arguments to pass to the executable
115 -> Maybe FilePath -- ^ Optional path to the working directory
116 -> Maybe [(String,String)] -- ^ Optional environment (otherwise inherit)
117 -> Maybe Handle -- ^ Handle to use for @stdin@
118 -> Maybe Handle -- ^ Handle to use for @stdout@
119 -> Maybe Handle -- ^ Handle to use for @stderr@
120 -> Maybe CLong -- handler for SIGINT
121 -> Maybe CLong -- handler for SIGQUIT
124 runProcessPosix fun cmd args mb_cwd mb_env mb_stdin mb_stdout mb_stderr
126 = withFilePathException cmd $ do
127 fd_stdin <- withHandle_ fun (fromMaybe stdin mb_stdin) $ return . haFD
128 fd_stdout <- withHandle_ fun (fromMaybe stdout mb_stdout) $ return . haFD
129 fd_stderr <- withHandle_ fun (fromMaybe stderr mb_stderr) $ return . haFD
130 -- some of these might refer to the same Handle, so don't do
131 -- nested withHandle_'s (that will deadlock).
132 maybeWith withCEnvironment mb_env $ \pEnv -> do
133 maybeWith withCString mb_cwd $ \pWorkDir -> do
134 withMany withCString (cmd:args) $ \cstrs -> do
135 let (set_int, inthand)
138 Just hand -> (1, hand)
142 Just hand -> (1, hand)
143 withArray0 nullPtr cstrs $ \pargs -> do
144 ph <- throwErrnoIfMinus1 fun $
145 c_runProcess pargs pWorkDir pEnv
146 fd_stdin fd_stdout fd_stderr
147 set_int inthand set_quit quithand
148 return (ProcessHandle ph)
150 foreign import ccall unsafe "runProcess"
152 :: Ptr CString -- args
153 -> CString -- working directory (or NULL)
154 -> Ptr CString -- env (or NULL)
158 -> CInt -- non-zero: set child's SIGINT handler
159 -> CLong -- SIGINT handler
160 -> CInt -- non-zero: set child's SIGQUIT handler
161 -> CLong -- SIGQUIT handler
164 #endif /* __GLASGOW_HASKELL__ */
166 ignoreSignal = CONST_SIG_IGN :: CLong
167 defaultSignal = CONST_SIG_DFL :: CLong
171 #ifdef __GLASGOW_HASKELL__
173 runProcessWin32 fun cmd args mb_cwd mb_env
174 mb_stdin mb_stdout mb_stderr extra_cmdline
175 = withFilePathException cmd $ do
176 fd_stdin <- withHandle_ fun (fromMaybe stdin mb_stdin) $ return . haFD
177 fd_stdout <- withHandle_ fun (fromMaybe stdout mb_stdout) $ return . haFD
178 fd_stderr <- withHandle_ fun (fromMaybe stderr mb_stderr) $ return . haFD
179 -- some of these might refer to the same Handle, so don't do
180 -- nested withHandle_'s (that will deadlock).
181 maybeWith withCEnvironment mb_env $ \pEnv -> do
182 maybeWith withCString mb_cwd $ \pWorkDir -> do
183 let cmdline = translate cmd ++
184 concat (map ((' ':) . translate) args) ++
185 (if null extra_cmdline then "" else ' ':extra_cmdline)
186 withCString cmdline $ \pcmdline -> do
187 proc_handle <- throwErrnoIfMinus1 fun
188 (c_runProcess pcmdline pWorkDir pEnv
189 fd_stdin fd_stdout fd_stderr)
190 return (ProcessHandle proc_handle)
192 foreign import ccall unsafe "runProcess"
202 -- ------------------------------------------------------------------------
203 -- Passing commands to the OS on Windows
206 On Windows this is tricky. We use CreateProcess, passing a single
207 command-line string (lpCommandLine) as its argument. (CreateProcess
208 is well documented on http://msdn.microsoft/com.)
210 - It parses the beginning of the string to find the command. If the
211 file name has embedded spaces, it must be quoted, using double
213 "foo\this that\cmd" arg1 arg2
215 - The invoked command can in turn access the entire lpCommandLine string,
216 and the C runtime does indeed do so, parsing it to generate the
217 traditional argument vector argv[0], argv[1], etc. It does this
218 using a complex and arcane set of rules which are described here:
220 http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vccelng/htm/progs_12.asp
222 (if this URL stops working, you might be able to find it by
223 searching for "Parsing C Command-Line Arguments" on MSDN. Also,
224 the code in the Microsoft C runtime that does this translation
225 is shipped with VC++).
227 Our goal in runProcess is to take a command filename and list of
228 arguments, and construct a string which inverts the translatsions
229 described above, such that the program at the other end sees exactly
230 the same arguments in its argv[] that we passed to rawSystem.
232 This inverse translation is implemented by 'translate' below.
234 Here are some pages that give informations on Windows-related
235 limitations and deviations from Unix conventions:
237 http://support.microsoft.com/default.aspx?scid=kb;en-us;830473
238 Command lines and environment variables effectively limited to 8191
239 characters on Win XP, 2047 on NT/2000 (probably even less on Win 9x):
241 http://www.microsoft.com/windowsxp/home/using/productdoc/en/default.asp?url=/WINDOWSXP/home/using/productdoc/en/percent.asp
242 Command-line substitution under Windows XP. IIRC these facilities (or at
243 least a large subset of them) are available on Win NT and 2000. Some
244 might be available on Win 9x.
246 http://www.microsoft.com/windowsxp/home/using/productdoc/en/default.asp?url=/WINDOWSXP/home/using/productdoc/en/Cmd.asp
247 How CMD.EXE processes command lines.
250 Note: CreateProcess does have a separate argument (lpApplicationName)
251 with which you can specify the command, but we have to slap the
252 command into lpCommandLine anyway, so that argv[0] is what a C program
253 expects (namely the application name). So it seems simpler to just
254 use lpCommandLine alone, which CreateProcess supports.
257 -- Translate command-line arguments for passing to CreateProcess().
258 translate :: String -> String
259 translate str = '"' : snd (foldr escape (True,"\"") str)
260 where escape '"' (b, str) = (True, '\\' : '"' : str)
261 escape '\\' (True, str) = (True, '\\' : '\\' : str)
262 escape '\\' (False, str) = (False, '\\' : str)
263 escape c (b, str) = (False, c : str)
264 -- See long comment above for what this function is trying to do.
266 -- The Bool passed back along the string is True iff the
267 -- rest of the string is a sequence of backslashes followed by
270 #endif /* __GLASGOW_HASKELL__ */
275 -- ----------------------------------------------------------------------------
278 {- | Turns a shell command into a raw command. Usually this involves
279 wrapping it in an invocation of the shell.
281 There's a difference in the signature of commandToProcess between
282 the Windows and Unix versions. On Unix, exec takes a list of strings,
283 and we want to pass our command to /bin/sh as a single argument.
285 On Windows, CreateProcess takes a single string for the command,
286 which is later decomposed by cmd.exe. In this case, we just want
287 to prepend @\"c:\WINDOWS\CMD.EXE \/c\"@ to our command line. The
288 command-line translation that we normally do for arguments on
289 Windows isn't required (or desirable) here.
292 #if !defined(mingw32_HOST_OS) && !defined(__MINGW32__)
296 -> IO (FilePath,[String])
297 commandToProcess string = return ("/bin/sh", ["-c", string])
303 -> IO (FilePath,String)
304 commandToProcess string = do
305 cmd <- findCommandInterpreter
306 return (cmd, "/c "++string)
307 -- We don't want to put the cmd into a single
308 -- argument, because cmd.exe will not try to split it up. Instead,
309 -- we just tack the command on the end of the cmd.exe command line,
310 -- which partly works. There seem to be some quoting issues, but
311 -- I don't have the energy to find+fix them right now (ToDo). --SDM
312 -- (later) Now I don't know what the above comment means. sigh.
314 -- Find CMD.EXE (or COMMAND.COM on Win98). We use the same algorithm as
315 -- system() in the VC++ CRT (Vc7/crt/src/system.c in a VC++ installation).
316 findCommandInterpreter :: IO FilePath
317 findCommandInterpreter = do
319 catchJust ioErrors (getEnv "COMSPEC") $ \e -> do
320 when (not (isDoesNotExistError e)) $ ioError e
322 -- try to find CMD.EXE or COMMAND.COM
324 let filename | osver .&. 0x8000 /= 0 = "command.com"
325 | otherwise = "cmd.exe"
326 path <- getEnv "PATH"
328 -- use our own version of System.Directory.findExecutable, because
329 -- that assumes the .exe suffix.
330 search :: [FilePath] -> IO (Maybe FilePath)
331 search [] = return Nothing
333 let path = d `joinFileName` filename
334 b <- doesFileExist path
335 if b then return (Just path)
338 mb_path <- search (parseSearchPath path)
341 Nothing -> ioError (mkIOError doesNotExistErrorType
342 "findCommandInterpreter" Nothing Nothing)
343 Just cmd -> return cmd
346 foreign import stdcall unsafe "__hscore_get_osver"
347 c_get_osver :: IO CUInt
350 #endif /* __HUGS__ */
352 -- ----------------------------------------------------------------------------
355 withFilePathException :: FilePath -> IO a -> IO a
356 withFilePathException fpath act = handle mapEx act
358 mapEx (IOException (IOError h iot fun str _)) = ioError (IOError h iot fun str (Just fpath))
361 #if !defined(mingw32_HOST_OS) && !defined(__MINGW32__)
362 withCEnvironment :: [(String,String)] -> (Ptr CString -> IO a) -> IO a
363 withCEnvironment env act =
364 let env' = map (\(name, val) -> name ++ ('=':val)) env
365 in withMany withCString env' (\pEnv -> withArray0 nullPtr pEnv act)
367 withCEnvironment :: [(String,String)] -> (Ptr () -> IO a) -> IO a
368 withCEnvironment env act =
369 let env' = foldr (\(name, val) env -> name ++ ('=':val)++'\0':env) "\0" env
370 in withCString env' (act . castPtr)