1 -----------------------------------------------------------------------------
3 -- (c) The University of Glasgow 2001-2003
5 -- Access to system tools: gcc, cp, rm etc
7 -----------------------------------------------------------------------------
14 setPgmL, -- String -> IO ()
26 -- Command-line override
29 getTopDir, -- IO String -- The value of $libdir
30 getPackageConfigPath, -- IO String -- Where package.conf is
31 getUsageMsgPaths, -- IO (String,String)
33 -- Interface to system tools
34 runUnlit, runCpp, runCc, -- [Option] -> IO ()
35 runPp, -- [Option] -> IO ()
36 runMangle, runSplit, -- [Option] -> IO ()
37 runAs, runLink, -- [Option] -> IO ()
40 runIlx2il, runIlasm, -- [String] -> IO ()
44 touch, -- String -> String -> IO ()
45 copy, -- String -> String -> String -> IO ()
46 normalisePath, -- FilePath -> FilePath
48 -- Temporary-file management
51 cleanTempFiles, cleanTempFilesExcept,
55 system, -- String -> IO ExitCode
58 getSysMan, -- IO String Parallel system only
64 #include "HsVersions.h"
67 import DriverPhases ( isHaskellUserSrcFilename )
70 import Panic ( GhcException(..) )
71 import Util ( global, notNull )
72 import CmdLineOpts ( dynFlag, verbosity )
74 import EXCEPTION ( throwDyn )
75 import DATA_IOREF ( IORef, readIORef, writeIORef )
78 import Monad ( when, unless )
79 import System ( ExitCode(..), getEnv, system )
80 import IO ( try, catch,
81 openFile, hPutStrLn, hPutStr, hClose, hFlush, IOMode(..),
83 import Directory ( doesFileExist, removeFile )
84 import List ( intersperse, partition )
86 #include "../includes/config.h"
88 -- GHC <= 4.08 didn't have rawSystem, and runs into problems with long command
89 -- lines on mingw32, so we disallow it now.
90 #if __GLASGOW_HASKELL__ < 500
91 #error GHC >= 5.00 is required for bootstrapping GHC
94 #ifndef mingw32_HOST_OS
95 #if __GLASGOW_HASKELL__ > 504
96 import qualified System.Posix.Internals
98 import qualified Posix
100 #else /* Must be Win32 */
101 import List ( isPrefixOf )
102 import Util ( dropList )
104 import CString ( CString, peekCString )
107 #if __GLASGOW_HASKELL__ < 601
108 import Foreign ( withMany, withArray0, nullPtr, Ptr )
109 import CForeign ( CString, withCString, throwErrnoIfMinus1 )
111 import System.Cmd ( rawSystem )
116 The configuration story
117 ~~~~~~~~~~~~~~~~~~~~~~~
119 GHC needs various support files (library packages, RTS etc), plus
120 various auxiliary programs (cp, gcc, etc). It finds these in one
123 * When running as an *installed program*, GHC finds most of this support
124 stuff in the installed library tree. The path to this tree is passed
125 to GHC via the -B flag, and given to initSysTools .
127 * When running *in-place* in a build tree, GHC finds most of this support
128 stuff in the build tree. The path to the build tree is, again passed
131 GHC tells which of the two is the case by seeing whether package.conf
132 is in TopDir [installed] or in TopDir/ghc/driver [inplace] (what a hack).
135 SysTools.initSysProgs figures out exactly where all the auxiliary programs
136 are, and initialises mutable variables to make it easy to call them.
137 To to this, it makes use of definitions in Config.hs, which is a Haskell
138 file containing variables whose value is figured out by the build system.
140 Config.hs contains two sorts of things
142 cGCC, The *names* of the programs
145 etc They do *not* include paths
148 cUNLIT_DIR_REL The *path* to the directory containing unlit, split etc
149 cSPLIT_DIR_REL *relative* to the root of the build tree,
150 for use when running *in-place* in a build tree (only)
154 ---------------------------------------------
155 NOTES for an ALTERNATIVE scheme (i.e *not* what is currently implemented):
157 Another hair-brained scheme for simplifying the current tool location
158 nightmare in GHC: Simon originally suggested using another
159 configuration file along the lines of GCC's specs file - which is fine
160 except that it means adding code to read yet another configuration
161 file. What I didn't notice is that the current package.conf is
162 general enough to do this:
165 {name = "tools", import_dirs = [], source_dirs = [],
166 library_dirs = [], hs_libraries = [], extra_libraries = [],
167 include_dirs = [], c_includes = [], package_deps = [],
168 extra_ghc_opts = ["-pgmc/usr/bin/gcc","-pgml${libdir}/bin/unlit", ... etc.],
169 extra_cc_opts = [], extra_ld_opts = []}
171 Which would have the advantage that we get to collect together in one
172 place the path-specific package stuff with the path-specific tool
175 ---------------------------------------------
178 %************************************************************************
180 \subsection{Global variables to contain system programs}
182 %************************************************************************
184 All these pathnames are maintained IN THE NATIVE FORMAT OF THE HOST MACHINE.
185 (See remarks under pathnames below)
188 GLOBAL_VAR(v_Pgm_L, error "pgm_L", String) -- unlit
189 GLOBAL_VAR(v_Pgm_P, error "pgm_P", (String,[Option])) -- cpp
190 GLOBAL_VAR(v_Pgm_F, error "pgm_F", String) -- pp
191 GLOBAL_VAR(v_Pgm_c, error "pgm_c", String) -- gcc
192 GLOBAL_VAR(v_Pgm_m, error "pgm_m", String) -- asm code mangler
193 GLOBAL_VAR(v_Pgm_s, error "pgm_s", String) -- asm code splitter
194 GLOBAL_VAR(v_Pgm_a, error "pgm_a", String) -- as
196 GLOBAL_VAR(v_Pgm_I, error "pgm_I", String) -- ilx2il
197 GLOBAL_VAR(v_Pgm_i, error "pgm_i", String) -- ilasm
199 GLOBAL_VAR(v_Pgm_l, error "pgm_l", String) -- ld
200 GLOBAL_VAR(v_Pgm_MkDLL, error "pgm_dll", String) -- mkdll
202 GLOBAL_VAR(v_Pgm_T, error "pgm_T", String) -- touch
203 GLOBAL_VAR(v_Pgm_CP, error "pgm_CP", String) -- cp
205 GLOBAL_VAR(v_Path_package_config, error "path_package_config", String)
206 GLOBAL_VAR(v_Path_usages, error "ghc_usage.txt", (String,String))
208 GLOBAL_VAR(v_TopDir, error "TopDir", String) -- -B<dir>
210 -- Parallel system only
211 GLOBAL_VAR(v_Pgm_sysman, error "pgm_sysman", String) -- system manager
213 -- ways to get at some of these variables from outside this module
214 getPackageConfigPath = readIORef v_Path_package_config
215 getTopDir = readIORef v_TopDir
219 %************************************************************************
221 \subsection{Initialisation}
223 %************************************************************************
226 initSysTools :: [String] -- Command-line arguments starting "-B"
228 -> IO () -- Set all the mutable variables above, holding
229 -- (a) the system programs
230 -- (b) the package-config file
231 -- (c) the GHC usage message
234 initSysTools minusB_args
235 = do { (am_installed, top_dir) <- findTopDir minusB_args
236 ; writeIORef v_TopDir top_dir
238 -- for "installed" this is the root of GHC's support files
239 -- for "in-place" it is the root of the build tree
240 -- NB: top_dir is assumed to be in standard Unix format '/' separated
242 ; let installed, installed_bin :: FilePath -> FilePath
243 installed_bin pgm = pgmPath top_dir pgm
244 installed file = pgmPath top_dir file
245 inplace dir pgm = pgmPath (top_dir `slash`
246 cPROJECT_DIR `slash` dir) pgm
249 | am_installed = installed "package.conf"
250 | otherwise = inplace cGHC_DRIVER_DIR_REL "package.conf.inplace"
253 | am_installed = installed "ghc-usage.txt"
254 | otherwise = inplace cGHC_DRIVER_DIR_REL "ghc-usage.txt"
257 | am_installed = installed "ghci-usage.txt"
258 | otherwise = inplace cGHC_DRIVER_DIR_REL "ghci-usage.txt"
260 -- For all systems, unlit, split, mangle are GHC utilities
261 -- architecture-specific stuff is done when building Config.hs
263 | am_installed = installed_bin cGHC_UNLIT_PGM
264 | otherwise = inplace cGHC_UNLIT_DIR_REL cGHC_UNLIT_PGM
266 -- split and mangle are Perl scripts
268 | am_installed = installed_bin cGHC_SPLIT_PGM
269 | otherwise = inplace cGHC_SPLIT_DIR_REL cGHC_SPLIT_PGM
272 | am_installed = installed_bin cGHC_MANGLER_PGM
273 | otherwise = inplace cGHC_MANGLER_DIR_REL cGHC_MANGLER_PGM
275 #ifndef mingw32_HOST_OS
276 -- check whether TMPDIR is set in the environment
277 ; IO.try (do dir <- getEnv "TMPDIR" -- fails if not set
282 -- On Win32, consult GetTempPath() for a temp dir.
283 -- => it first tries TMP, TEMP, then finally the
284 -- Windows directory(!). The directory is in short-path
287 let len = (2048::Int)
288 buf <- mallocArray len
289 ret <- getTempPath len buf
292 -- failed, consult TMPDIR.
302 -- Check that the package config exists
303 ; config_exists <- doesFileExist pkgconfig_path
304 ; when (not config_exists) $
305 throwDyn (InstallationError
306 ("Can't find package.conf as " ++ pkgconfig_path))
308 #if defined(mingw32_HOST_OS)
309 -- WINDOWS-SPECIFIC STUFF
310 -- On Windows, gcc and friends are distributed with GHC,
311 -- so when "installed" we look in TopDir/bin
312 -- When "in-place" we look wherever the build-time configure
314 -- When "install" we tell gcc where its specs file + exes are (-B)
315 -- and also some places to pick up include files. We need
316 -- to be careful to put all necessary exes in the -B place
317 -- (as, ld, cc1, etc) since if they don't get found there, gcc
318 -- then tries to run unadorned "as", "ld", etc, and will
319 -- pick up whatever happens to be lying around in the path,
320 -- possibly including those from a cygwin install on the target,
321 -- which is exactly what we're trying to avoid.
322 ; let gcc_path | am_installed = installed_bin ("gcc -B\"" ++ installed "gcc-lib/\"")
324 -- The trailing "/" is absolutely essential; gcc seems
325 -- to construct file names simply by concatenating to this
326 -- -B path with no extra slash
327 -- We use "/" rather than "\\" because otherwise "\\\" is mangled
328 -- later on; although gcc_path is in NATIVE format, gcc can cope
329 -- (see comments with declarations of global variables)
331 -- The quotes round the -B argument are in case TopDir has spaces in it
333 perl_path | am_installed = installed_bin cGHC_PERL
334 | otherwise = cGHC_PERL
336 -- 'touch' is a GHC util for Windows, and similarly unlit, mangle
337 ; let touch_path | am_installed = installed_bin cGHC_TOUCHY_PGM
338 | otherwise = inplace cGHC_TOUCHY_DIR_REL cGHC_TOUCHY_PGM
340 -- On Win32 we don't want to rely on #!/bin/perl, so we prepend
341 -- a call to Perl to get the invocation of split and mangle
342 ; let split_path = perl_path ++ " \"" ++ split_script ++ "\""
343 mangle_path = perl_path ++ " \"" ++ mangle_script ++ "\""
346 | am_installed = pgmPath (installed "gcc-lib/") cMKDLL ++
347 " --dlltool-name " ++ pgmPath (installed "gcc-lib/") "dlltool" ++
348 " --driver-name " ++ gcc_path
351 -- UNIX-SPECIFIC STUFF
352 -- On Unix, the "standard" tools are assumed to be
353 -- in the same place whether we are running "in-place" or "installed"
354 -- That place is wherever the build-time configure script found them.
355 ; let gcc_path = cGCC
357 mkdll_path = panic "Can't build DLLs on a non-Win32 system"
359 -- On Unix, scripts are invoked using the '#!' method. Binary
360 -- installations of GHC on Unix place the correct line on the front
361 -- of the script at installation time, so we don't want to wire-in
362 -- our knowledge of $(PERL) on the host system here.
363 ; let split_path = split_script
364 mangle_path = mangle_script
367 -- cpp is derived from gcc on all platforms
368 -- HACK, see setPgmP below. We keep 'words' here to remember to fix
369 -- Config.hs one day.
370 ; let cpp_path = (gcc_path, (Option "-E"):(map Option (words cRAWCPP_FLAGS)))
372 -- For all systems, copy and remove are provided by the host
373 -- system; architecture-specific stuff is done when building Config.hs
374 ; let cp_path = cGHC_CP
376 -- Other things being equal, as and ld are simply gcc
377 ; let as_path = gcc_path
381 -- ilx2il and ilasm are specified in Config.hs
382 ; let ilx2il_path = cILX2IL
386 -- Initialise the global vars
387 ; writeIORef v_Path_package_config pkgconfig_path
388 ; writeIORef v_Path_usages (ghc_usage_msg_path,
391 ; writeIORef v_Pgm_sysman (top_dir ++ "/ghc/rts/parallel/SysMan")
392 -- Hans: this isn't right in general, but you can
393 -- elaborate it in the same way as the others
395 ; writeIORef v_Pgm_L unlit_path
396 ; writeIORef v_Pgm_P cpp_path
397 ; writeIORef v_Pgm_F ""
398 ; writeIORef v_Pgm_c gcc_path
399 ; writeIORef v_Pgm_m mangle_path
400 ; writeIORef v_Pgm_s split_path
401 ; writeIORef v_Pgm_a as_path
403 ; writeIORef v_Pgm_I ilx2il_path
404 ; writeIORef v_Pgm_i ilasm_path
406 ; writeIORef v_Pgm_l ld_path
407 ; writeIORef v_Pgm_MkDLL mkdll_path
408 ; writeIORef v_Pgm_T touch_path
409 ; writeIORef v_Pgm_CP cp_path
414 #if defined(mingw32_HOST_OS)
415 foreign import stdcall "GetTempPathA" unsafe getTempPath :: Int -> CString -> IO Int32
419 The various setPgm functions are called when a command-line option
424 is used to override a particular program with a new one
427 setPgmL = writeIORef v_Pgm_L
428 -- XXX HACK: Prelude> words "'does not' work" ===> ["'does","not'","work"]
429 -- Config.hs should really use Option.
430 setPgmP arg = let (pgm:args) = words arg in writeIORef v_Pgm_P (pgm,map Option args)
431 setPgmF = writeIORef v_Pgm_F
432 setPgmc = writeIORef v_Pgm_c
433 setPgmm = writeIORef v_Pgm_m
434 setPgms = writeIORef v_Pgm_s
435 setPgma = writeIORef v_Pgm_a
436 setPgml = writeIORef v_Pgm_l
438 setPgmI = writeIORef v_Pgm_I
439 setPgmi = writeIORef v_Pgm_i
446 -- for "installed" this is the root of GHC's support files
447 -- for "in-place" it is the root of the build tree
450 -- 1. Set proto_top_dir
451 -- a) look for (the last) -B flag, and use it
452 -- b) if there are no -B flags, get the directory
453 -- where GHC is running (only on Windows)
455 -- 2. If package.conf exists in proto_top_dir, we are running
456 -- installed; and TopDir = proto_top_dir
458 -- 3. Otherwise we are running in-place, so
459 -- proto_top_dir will be /...stuff.../ghc/compiler
460 -- Set TopDir to /...stuff..., which is the root of the build tree
462 -- This is very gruesome indeed
464 findTopDir :: [String]
465 -> IO (Bool, -- True <=> am installed, False <=> in-place
466 String) -- TopDir (in Unix format '/' separated)
469 = do { top_dir <- get_proto
470 -- Discover whether we're running in a build tree or in an installation,
471 -- by looking for the package configuration file.
472 ; am_installed <- doesFileExist (top_dir `slash` "package.conf")
474 ; return (am_installed, top_dir)
477 -- get_proto returns a Unix-format path (relying on getBaseDir to do so too)
478 get_proto | notNull minusbs
479 = return (normalisePath (drop 2 (last minusbs))) -- 2 for "-B"
481 = do { maybe_exec_dir <- getBaseDir -- Get directory of executable
482 ; case maybe_exec_dir of -- (only works on Windows;
483 -- returns Nothing on Unix)
484 Nothing -> throwDyn (InstallationError "missing -B<dir> option")
485 Just dir -> return dir
490 %************************************************************************
492 \subsection{Command-line options}
494 %************************************************************************
496 When invoking external tools as part of the compilation pipeline, we
497 pass these a sequence of options on the command-line. Rather than
498 just using a list of Strings, we use a type that allows us to distinguish
499 between filepaths and 'other stuff'. [The reason being, of course, that
500 this type gives us a handle on transforming filenames, and filenames only,
501 to whatever format they're expected to be on a particular platform.]
505 = FileOption -- an entry that _contains_ filename(s) / filepaths.
506 String -- a non-filepath prefix that shouldn't be transformed (e.g., "/out="
507 String -- the filepath/filename portion
510 showOpt (FileOption pre f) = pre ++ platformPath f
511 showOpt (Option "") = ""
512 showOpt (Option s) = s
517 %************************************************************************
519 \subsection{Running an external program}
521 %************************************************************************
525 runUnlit :: [Option] -> IO ()
526 runUnlit args = do p <- readIORef v_Pgm_L
527 runSomething "Literate pre-processor" p args
529 runCpp :: [Option] -> IO ()
530 runCpp args = do (p,baseArgs) <- readIORef v_Pgm_P
531 runSomething "C pre-processor" p (baseArgs ++ args)
533 runPp :: [Option] -> IO ()
534 runPp args = do p <- readIORef v_Pgm_F
535 runSomething "Haskell pre-processor" p args
537 runCc :: [Option] -> IO ()
538 runCc args = do p <- readIORef v_Pgm_c
539 runSomething "C Compiler" p args
541 runMangle :: [Option] -> IO ()
542 runMangle args = do p <- readIORef v_Pgm_m
543 runSomething "Mangler" p args
545 runSplit :: [Option] -> IO ()
546 runSplit args = do p <- readIORef v_Pgm_s
547 runSomething "Splitter" p args
549 runAs :: [Option] -> IO ()
550 runAs args = do p <- readIORef v_Pgm_a
551 runSomething "Assembler" p args
553 runLink :: [Option] -> IO ()
554 runLink args = do p <- readIORef v_Pgm_l
555 runSomething "Linker" p args
558 runIlx2il :: [Option] -> IO ()
559 runIlx2il args = do p <- readIORef v_Pgm_I
560 runSomething "Ilx2Il" p args
562 runIlasm :: [Option] -> IO ()
563 runIlasm args = do p <- readIORef v_Pgm_i
564 runSomething "Ilasm" p args
567 runMkDLL :: [Option] -> IO ()
568 runMkDLL args = do p <- readIORef v_Pgm_MkDLL
569 runSomething "Make DLL" p args
571 touch :: String -> String -> IO ()
572 touch purpose arg = do p <- readIORef v_Pgm_T
573 runSomething purpose p [FileOption "" arg]
575 copy :: String -> String -> String -> IO ()
576 copy purpose from to = do
577 verb <- dynFlag verbosity
578 when (verb >= 2) $ hPutStrLn stderr ("*** " ++ purpose)
580 h <- openFile to WriteMode
581 ls <- readFile from -- inefficient, but it'll do for now.
582 -- ToDo: speed up via slurping.
588 getSysMan :: IO String -- How to invoke the system manager
589 -- (parallel system only)
590 getSysMan = readIORef v_Pgm_sysman
594 getUsageMsgPaths :: IO (FilePath,FilePath)
595 -- the filenames of the usage messages (ghc, ghci)
596 getUsageMsgPaths = readIORef v_Path_usages
600 %************************************************************************
602 \subsection{Managing temporary files
604 %************************************************************************
607 GLOBAL_VAR(v_FilesToClean, [], [String] )
608 GLOBAL_VAR(v_TmpDir, cDEFAULT_TMPDIR, String )
609 -- v_TmpDir has no closing '/'
613 setTmpDir dir = writeIORef v_TmpDir (canonicalise dir)
615 #if !defined(mingw32_HOST_OS)
616 canonicalise p = normalisePath p
618 -- Canonicalisation of temp path under win32 is a bit more
619 -- involved: (a) strip trailing slash,
620 -- (b) normalise slashes
621 -- (c) just in case, if there is a prefix /cygdrive/x/, change to x:
623 canonicalise path = normalisePath (xltCygdrive (removeTrailingSlash path))
625 -- if we're operating under cygwin, and TMP/TEMP is of
626 -- the form "/cygdrive/drive/path", translate this to
627 -- "drive:/path" (as GHC isn't a cygwin app and doesn't
628 -- understand /cygdrive paths.)
630 | "/cygdrive/" `isPrefixOf` path =
631 case drop (length "/cygdrive/") path of
632 drive:xs@('/':_) -> drive:':':xs
636 -- strip the trailing backslash (awful, but we only do this once).
637 removeTrailingSlash path =
644 cleanTempFiles :: Int -> IO ()
646 = do fs <- readIORef v_FilesToClean
647 removeTmpFiles verb fs
648 writeIORef v_FilesToClean []
650 cleanTempFilesExcept :: Int -> [FilePath] -> IO ()
651 cleanTempFilesExcept verb dont_delete
652 = do files <- readIORef v_FilesToClean
653 let (to_keep, to_delete) = partition (`elem` dont_delete) files
654 removeTmpFiles verb to_delete
655 writeIORef v_FilesToClean to_keep
658 -- find a temporary name that doesn't already exist.
659 newTempName :: Suffix -> IO FilePath
661 = do x <- getProcessID
662 tmp_dir <- readIORef v_TmpDir
663 findTempName tmp_dir x
665 findTempName tmp_dir x
666 = do let filename = tmp_dir ++ "/ghc" ++ show x ++ '.':extn
667 b <- doesFileExist filename
668 if b then findTempName tmp_dir (x+1)
669 else do add v_FilesToClean filename -- clean it up later
672 addFilesToClean :: [FilePath] -> IO ()
673 -- May include wildcards [used by DriverPipeline.run_phase SplitMangle]
674 addFilesToClean files = mapM_ (add v_FilesToClean) files
676 removeTmpFiles :: Int -> [FilePath] -> IO ()
677 removeTmpFiles verb fs
679 traceCmd "Deleting temp files"
680 ("Deleting: " ++ unwords deletees)
683 -- Flat out refuse to delete files that are likely to be source input
684 -- files (is there a worse bug than having a compiler delete your source
687 -- Deleting source files is a sign of a bug elsewhere, so prominently flag
690 | null non_deletees = act
692 hPutStrLn stderr ("WARNING - NOT deleting source files: " ++ unwords non_deletees)
695 (non_deletees, deletees) = partition isHaskellUserSrcFilename fs
697 rm f = removeFile f `IO.catch`
700 hPutStrLn stderr ("Warning: deleting non-existent " ++ f)
706 %************************************************************************
708 \subsection{Running a program}
710 %************************************************************************
713 GLOBAL_VAR(v_Dry_run, False, Bool)
716 setDryRun = writeIORef v_Dry_run True
718 -----------------------------------------------------------------------------
719 -- Running an external program
721 runSomething :: String -- For -v message
722 -> String -- Command name (possibly a full path)
723 -- assumed already dos-ified
724 -> [Option] -- Arguments
725 -- runSomething will dos-ify them
728 runSomething phase_name pgm args = do
729 let real_args = filter notNull (map showOpt args)
730 traceCmd phase_name (concat (intersperse " " (pgm:real_args))) $ do
731 exit_code <- rawSystem pgm real_args
732 if (exit_code /= ExitSuccess)
733 then throwDyn (PhaseFailed phase_name exit_code)
736 traceCmd :: String -> String -> IO () -> IO ()
737 -- a) trace the command (at two levels of verbosity)
738 -- b) don't do it at all if dry-run is set
739 traceCmd phase_name cmd_line action
740 = do { verb <- dynFlag verbosity
741 ; when (verb >= 2) $ hPutStrLn stderr ("*** " ++ phase_name)
742 ; when (verb >= 3) $ hPutStrLn stderr cmd_line
746 ; n <- readIORef v_Dry_run
750 ; action `IO.catch` handle_exn verb
753 handle_exn verb exn = do { when (verb >= 2) (hPutStr stderr "\n")
754 ; when (verb >= 3) (hPutStrLn stderr ("Failed: " ++ cmd_line ++ (show exn)))
755 ; throwDyn (PhaseFailed phase_name (ExitFailure 1)) }
757 -- -----------------------------------------------------------------------------
758 -- rawSystem: run an external command
760 #if __GLASGOW_HASKELL__ < 601
762 -- This code is copied from System.Cmd on GHC 6.1.
764 rawSystem :: FilePath -> [String] -> IO ExitCode
766 #ifndef mingw32_TARGET_OS
769 withCString cmd $ \pcmd ->
770 withMany withCString (cmd:args) $ \cstrs ->
771 withArray0 nullPtr cstrs $ \arr -> do
772 status <- throwErrnoIfMinus1 "rawSystem" (c_rawSystem pcmd arr)
774 0 -> return ExitSuccess
775 n -> return (ExitFailure n)
777 foreign import ccall "rawSystem" unsafe
778 c_rawSystem :: CString -> Ptr CString -> IO Int
782 -- On Windows, the command line is passed to the operating system as
783 -- a single string. Command-line parsing is done by the executable
785 rawSystem cmd args = do
786 let cmdline = {-translate-} cmd ++ concat (map ((' ':) . translate) args)
787 -- Urk, don't quote/escape the command name on Windows, because the
788 -- compiler is exceedingly naughty and sometimes uses 'perl "..."'
789 -- as the command name.
790 withCString cmdline $ \pcmdline -> do
791 status <- throwErrnoIfMinus1 "rawSystem" (c_rawSystem pcmdline)
793 0 -> return ExitSuccess
794 n -> return (ExitFailure n)
796 translate :: String -> String
797 translate str = '"' : foldr escape "\"" str
798 where escape '"' str = '\\' : '"' : str
799 escape '\\' str = '\\' : '\\' : str
800 escape c str = c : str
802 foreign import ccall "rawSystem" unsafe
803 c_rawSystem :: CString -> IO Int
810 %************************************************************************
812 \subsection{Path names}
814 %************************************************************************
816 We maintain path names in Unix form ('/'-separated) right until
817 the last moment. On Windows we dos-ify them just before passing them
818 to the Windows command.
820 The alternative, of using '/' consistently on Unix and '\' on Windows,
821 proved quite awkward. There were a lot more calls to platformPath,
822 and even on Windows we might invoke a unix-like utility (eg 'sh'), which
823 interpreted a command line 'foo\baz' as 'foobaz'.
826 -----------------------------------------------------------------------------
827 -- Convert filepath into platform / MSDOS form.
829 normalisePath :: String -> String
830 -- Just changes '\' to '/'
832 pgmPath :: String -- Directory string in Unix format
833 -> String -- Program name with no directory separators
835 -> String -- Program invocation string in native format
839 #if defined(mingw32_HOST_OS)
840 --------------------- Windows version ------------------
841 normalisePath xs = subst '\\' '/' xs
842 platformPath p = subst '/' '\\' p
843 pgmPath dir pgm = platformPath dir ++ '\\' : pgm
845 subst a b ls = map (\ x -> if x == a then b else x) ls
847 --------------------- Non-Windows version --------------
848 normalisePath xs = xs
849 pgmPath dir pgm = dir ++ '/' : pgm
850 platformPath stuff = stuff
851 --------------------------------------------------------
857 -----------------------------------------------------------------------------
858 Path name construction
861 slash :: String -> String -> String
862 slash s1 s2 = s1 ++ ('/' : s2)
866 %************************************************************************
868 \subsection{Support code}
870 %************************************************************************
873 -----------------------------------------------------------------------------
874 -- Define getBaseDir :: IO (Maybe String)
876 #if defined(mingw32_HOST_OS)
877 getBaseDir :: IO (Maybe String)
878 -- Assuming we are running ghc, accessed by path $()/bin/ghc.exe,
879 -- return the path $(stuff). Note that we drop the "bin/" directory too.
880 getBaseDir = do let len = (2048::Int) -- plenty, PATH_MAX is 512 under Win32.
881 buf <- mallocArray len
882 ret <- getModuleFileName nullPtr buf len
883 if ret == 0 then free buf >> return Nothing
884 else do s <- peekCString buf
886 return (Just (rootDir s))
888 rootDir s = reverse (dropList "/bin/ghc.exe" (reverse (normalisePath s)))
890 foreign import stdcall "GetModuleFileNameA" unsafe
891 getModuleFileName :: Ptr () -> CString -> Int -> IO Int32
893 getBaseDir :: IO (Maybe String) = do return Nothing
896 #ifdef mingw32_HOST_OS
897 foreign import ccall "_getpid" unsafe getProcessID :: IO Int -- relies on Int == Int32 on Windows
898 #elif __GLASGOW_HASKELL__ > 504
899 getProcessID :: IO Int
900 getProcessID = System.Posix.Internals.c_getpid >>= return . fromIntegral
902 getProcessID :: IO Int
903 getProcessID = Posix.getProcessID