1 -----------------------------------------------------------------------------
2 -- Access to system tools: gcc, cp, rm etc
4 -- (c) The University of Glasgow 2000
6 -----------------------------------------------------------------------------
12 setPgm, -- String -> IO ()
13 -- Command-line override
16 packageConfigPath, -- IO String
17 -- Where package.conf is
19 -- Interface to system tools
20 runUnlit, runCpp, runCc, -- [String] -> IO ()
21 runMangle, runSplit, -- [String] -> IO ()
22 runAs, runLink, -- [String] -> IO ()
25 touch, -- String -> String -> IO ()
26 copy, -- String -> String -> String -> IO ()
28 -- Temporary-file management
31 cleanTempFiles, cleanTempFilesExcept, removeTmpFiles,
35 getProcessID, -- IO Int
36 system, -- String -> IO Int
39 showGhcUsage, -- IO () Shows usage message and exits
40 getSysMan -- IO String Parallel system only
47 import Panic ( progName, GhcException(..) )
48 import Util ( global )
49 import CmdLineOpts ( dynFlag, verbosity )
51 import Exception ( throwDyn, catchAllIO )
53 import Directory ( doesFileExist, removeFile )
54 import IOExts ( IORef, readIORef, writeIORef )
55 import Monad ( when, unless )
56 import System ( system, ExitCode(..), exitWith, getEnv )
58 #include "../includes/config.h"
60 #if !defined(mingw32_TARGET_OS)
61 import qualified Posix
64 import List ( isPrefixOf )
67 import List ( isSuffixOf )
69 #include "HsVersions.h"
74 The configuration story
75 ~~~~~~~~~~~~~~~~~~~~~~~
77 GHC needs various support files (library packages, RTS etc), plus
78 various auxiliary programs (cp, gcc, etc). It finds these in one
81 * When running as an *installed program*, GHC finds most of this support
82 stuff in the installed library tree. The path to this tree is passed
83 to GHC via the -B flag, and given to initSysTools .
85 * When running *in-place* in a build tree, GHC finds most of this support
86 stuff in the build tree. The path to the build tree is, again passed
89 GHC tells which of the two is the case by seeing whether package.conf
90 is in TopDir [installed] or in TopDir/ghc/driver [inplace] (what a hack).
93 SysTools.initSysProgs figures out exactly where all the auxiliary programs
94 are, and initialises mutable variables to make it easy to call them.
95 To to this, it makes use of definitions in Config.hs, which is a Haskell
96 file containing variables whose value is figured out by the build system.
98 Config.hs contains two sorts of things
100 cGCC, The *names* of the programs
103 etc They do *not* include paths
106 cUNLIT_DIR The *path* to the directory containing unlit, split etc
107 cSPLIT_DIR *relative* to the root of the build tree,
108 for use when running *in-place* in a build tree (only)
112 ---------------------------------------------
113 NOTES for an ALTERNATIVE scheme (i.e *not* what is currently implemented):
115 Another hair-brained scheme for simplifying the current tool location
116 nightmare in GHC: Simon originally suggested using another
117 configuration file along the lines of GCC's specs file - which is fine
118 except that it means adding code to read yet another configuration
119 file. What I didn't notice is that the current package.conf is
120 general enough to do this:
123 {name = "tools", import_dirs = [], source_dirs = [],
124 library_dirs = [], hs_libraries = [], extra_libraries = [],
125 include_dirs = [], c_includes = [], package_deps = [],
126 extra_ghc_opts = ["-pgmc/usr/bin/gcc","-pgml${libdir}/bin/unlit", ... etc.],
127 extra_cc_opts = [], extra_ld_opts = []}
129 Which would have the advantage that we get to collect together in one
130 place the path-specific package stuff with the path-specific tool
133 ---------------------------------------------
136 %************************************************************************
138 \subsection{Global variables to contain system programs}
140 %************************************************************************
142 All these pathnames are maintained IN THE NATIVE FORMAT OF THE HOST MACHINE.
143 (See remarks under pathnames below)
146 GLOBAL_VAR(v_Pgm_L, error "pgm_L", String) -- unlit
147 GLOBAL_VAR(v_Pgm_P, error "pgm_P", String) -- cpp
148 GLOBAL_VAR(v_Pgm_c, error "pgm_c", String) -- gcc
149 GLOBAL_VAR(v_Pgm_m, error "pgm_m", String) -- asm code mangler
150 GLOBAL_VAR(v_Pgm_s, error "pgm_s", String) -- asm code splitter
151 GLOBAL_VAR(v_Pgm_a, error "pgm_a", String) -- as
152 GLOBAL_VAR(v_Pgm_l, error "pgm_l", String) -- ld
153 GLOBAL_VAR(v_Pgm_MkDLL, error "pgm_dll", String) -- mkdll
155 GLOBAL_VAR(v_Pgm_T, error "pgm_T", String) -- touch
156 GLOBAL_VAR(v_Pgm_CP, error "pgm_CP", String) -- cp
158 GLOBAL_VAR(v_Path_package_config, error "path_package_config", String)
159 GLOBAL_VAR(v_Path_usage, error "ghc_usage.txt", String)
161 -- Parallel system only
162 GLOBAL_VAR(v_Pgm_sysman, error "pgm_sysman", String) -- system manager
166 %************************************************************************
168 \subsection{Initialisation}
170 %************************************************************************
173 initSysTools :: [String] -- Command-line arguments starting "-B"
175 -> IO String -- Set all the mutable variables above, holding
176 -- (a) the system programs
177 -- (b) the package-config file
178 -- (c) the GHC usage message
182 initSysTools minusB_args
183 = do { (am_installed, top_dir) <- getTopDir minusB_args
185 -- for "installed" this is the root of GHC's support files
186 -- for "in-place" it is the root of the build tree
187 -- NB: top_dir is assumed to be in standard Unix format '/' separated
189 ; let installed, installed_bin :: FilePath -> FilePath
190 installed_bin pgm = pgmPath (top_dir `slash` "extra-bin") pgm
191 installed file = pgmPath top_dir file
192 inplace dir pgm = pgmPath (top_dir `slash` dir) pgm
195 | am_installed = installed "package.conf"
196 | otherwise = inplace cGHC_DRIVER_DIR "package.conf.inplace"
199 | am_installed = installed "ghc-usage.txt"
200 | otherwise = inplace cGHC_DRIVER_DIR "ghc-usage.txt"
202 -- For all systems, unlit, split, mangle are GHC utilities
203 -- architecture-specific stuff is done when building Config.hs
205 | am_installed = installed_bin cGHC_UNLIT
206 | otherwise = inplace cGHC_UNLIT_DIR cGHC_UNLIT
208 -- split and mangle are Perl scripts
210 | am_installed = installed_bin cGHC_SPLIT
211 | otherwise = inplace cGHC_SPLIT_DIR cGHC_SPLIT
214 | am_installed = installed_bin cGHC_MANGLER
215 | otherwise = inplace cGHC_MANGLER_DIR cGHC_MANGLER
217 #ifndef mingw32_TARGET_OS
218 -- check whether TMPDIR is set in the environment
219 ; IO.try (do dir <- getEnv "TMPDIR" -- fails if not set
225 -- Check that the package config exists
226 ; config_exists <- doesFileExist pkgconfig_path
227 ; when (not config_exists) $
228 throwDyn (InstallationError
229 ("Can't find package.conf as " ++ pkgconfig_path))
231 #if defined(mingw32_TARGET_OS)
232 -- WINDOWS-SPECIFIC STUFF
233 -- On Windows, gcc and friends are distributed with GHC,
234 -- so when "installed" we look in TopDir/bin
235 -- When "in-place" we look wherever the build-time configure
237 -- When "install" we tell gcc where its specs file + exes are (-B)
238 -- and also some places to pick up include files. We need
239 -- to be careful to put all necessary exes in the -B place
240 -- (as, ld, cc1, etc) since if they don't get found there, gcc
241 -- then tries to run unadorned "as", "ld", etc, and will
242 -- pick up whatever happens to be lying around in the path,
243 -- possibly including those from a cygwin install on the target,
244 -- which is exactly what we're trying to avoid.
245 ; let gcc_path | am_installed = installed_bin ("gcc -B" ++ installed "gcc-lib/"
246 ++ " -I" ++ installed "include/mingw")
248 perl_path | am_installed = installed_bin cGHC_PERL
249 | otherwise = cGHC_PERL
251 -- 'touch' is a GHC util for Windows, and similarly unlit, mangle
252 ; let touch_path | am_installed = installed_bin cGHC_TOUCHY
253 | otherwise = inplace cGHC_TOUCHY_DIR cGHC_TOUCHY
255 -- On Win32 we don't want to rely on #!/bin/perl, so we prepend
256 -- a call to Perl to get the invocation of split and mangle
257 ; let split_path = perl_path ++ " " ++ split_script
258 mangle_path = perl_path ++ " " ++ mangle_script
260 ; let mkdll_path = cMKDLL
262 -- UNIX-SPECIFIC STUFF
263 -- On Unix, the "standard" tools are assumed to be
264 -- in the same place whether we are running "in-place" or "installed"
265 -- That place is wherever the build-time configure script found them.
266 ; let gcc_path = cGCC
267 touch_path = cGHC_TOUCHY
268 mkdll_path = panic "Can't build DLLs on a non-Win32 system"
270 -- On Unix, scripts are invoked using the '#!' method. Binary
271 -- installations of GHC on Unix place the correct line on the front
272 -- of the script at installation time, so we don't want to wire-in
273 -- our knowledge of $(PERL) on the host system here.
274 ; let split_path = split_script
275 mangle_path = mangle_script
278 -- cpp is derived from gcc on all platforms
279 ; let cpp_path = gcc_path ++ " -E " ++ cRAWCPP_FLAGS
281 -- For all systems, copy and remove are provided by the host
282 -- system; architecture-specific stuff is done when building Config.hs
283 ; let cp_path = cGHC_CP
285 -- Other things being equal, as and ld are simply gcc
286 ; let as_path = gcc_path
290 -- Initialise the global vars
291 ; writeIORef v_Path_package_config pkgconfig_path
292 ; writeIORef v_Path_usage ghc_usage_msg_path
294 ; writeIORef v_Pgm_sysman (top_dir ++ "/ghc/rts/parallel/SysMan")
295 -- Hans: this isn't right in general, but you can
296 -- elaborate it in the same way as the others
298 ; writeIORef v_Pgm_L unlit_path
299 ; writeIORef v_Pgm_P cpp_path
300 ; writeIORef v_Pgm_c gcc_path
301 ; writeIORef v_Pgm_m mangle_path
302 ; writeIORef v_Pgm_s split_path
303 ; writeIORef v_Pgm_a as_path
304 ; writeIORef v_Pgm_l ld_path
305 ; writeIORef v_Pgm_MkDLL mkdll_path
306 ; writeIORef v_Pgm_T touch_path
307 ; writeIORef v_Pgm_CP cp_path
313 setPgm is called when a command-line option like
315 is used to override a particular program with a new onw
318 setPgm :: String -> IO ()
319 -- The string is the flag, minus the '-pgm' prefix
320 -- So the first character says which program to override
322 setPgm ('P' : pgm) = writeIORef v_Pgm_P pgm
323 setPgm ('c' : pgm) = writeIORef v_Pgm_c pgm
324 setPgm ('m' : pgm) = writeIORef v_Pgm_m pgm
325 setPgm ('s' : pgm) = writeIORef v_Pgm_s pgm
326 setPgm ('a' : pgm) = writeIORef v_Pgm_a pgm
327 setPgm ('l' : pgm) = writeIORef v_Pgm_l pgm
328 setPgm pgm = unknownFlagErr ("-pgm" ++ pgm)
334 -- for "installed" this is the root of GHC's support files
335 -- for "in-place" it is the root of the build tree
338 -- 1. Set proto_top_dir
339 -- a) look for (the last) -B flag, and use it
340 -- b) if there are no -B flags, get the directory
341 -- where GHC is running (only on Windows)
343 -- 2. If package.conf exists in proto_top_dir, we are running
344 -- installed; and TopDir = proto_top_dir
346 -- 3. Otherwise we are running in-place, so
347 -- proto_top_dir will be /...stuff.../ghc/compiler
348 -- Set TopDir to /...stuff..., which is the root of the build tree
350 -- This is very gruesome indeed
352 getTopDir :: [String]
353 -> IO (Bool, -- True <=> am installed, False <=> in-place
354 String) -- TopDir (in Unix format '/' separated)
357 = do { top_dir <- get_proto
358 -- Discover whether we're running in a build tree or in an installation,
359 -- by looking for the package configuration file.
360 ; am_installed <- doesFileExist (top_dir `slash` "package.conf")
362 ; return (am_installed, top_dir)
365 -- get_proto returns a Unix-format path
366 get_proto | not (null minusbs)
367 = return (unDosifyPath (drop 2 (last minusbs))) -- 2 for "-B"
369 = do { maybe_exec_dir <- getExecDir -- Get directory of executable
370 ; case maybe_exec_dir of -- (only works on Windows;
371 -- returns Nothing on Unix)
372 Nothing -> throwDyn (InstallationError "missing -B<dir> option")
373 Just dir -> return (unDosifyPath dir)
378 %************************************************************************
380 \subsection{Running an external program}
382 %************************************************************************
386 runUnlit :: [String] -> IO ()
387 runUnlit args = do p <- readIORef v_Pgm_L
388 runSomething "Literate pre-processor" p args
390 runCpp :: [String] -> IO ()
391 runCpp args = do p <- readIORef v_Pgm_P
392 runSomething "C pre-processor" p args
394 runCc :: [String] -> IO ()
395 runCc args = do p <- readIORef v_Pgm_c
396 runSomething "C Compiler" p args
398 runMangle :: [String] -> IO ()
399 runMangle args = do p <- readIORef v_Pgm_m
400 runSomething "Mangler" p args
402 runSplit :: [String] -> IO ()
403 runSplit args = do p <- readIORef v_Pgm_s
404 runSomething "Splitter" p args
406 runAs :: [String] -> IO ()
407 runAs args = do p <- readIORef v_Pgm_a
408 runSomething "Assembler" p args
410 runLink :: [String] -> IO ()
411 runLink args = do p <- readIORef v_Pgm_l
412 runSomething "Linker" p args
414 runMkDLL :: [String] -> IO ()
415 runMkDLL args = do p <- readIORef v_Pgm_MkDLL
416 runSomething "Make DLL" p args
418 touch :: String -> String -> IO ()
419 touch purpose arg = do p <- readIORef v_Pgm_T
420 runSomething purpose p [arg]
422 copy :: String -> String -> String -> IO ()
423 copy purpose from to = do
424 verb <- dynFlag verbosity
425 when (verb >= 2) $ hPutStrLn stderr ("*** " ++ purpose)
427 h <- openFile to WriteMode
428 ls <- readFile from -- inefficient, but it'll do for now.
429 -- ToDo: speed up via slurping.
435 getSysMan :: IO String -- How to invoke the system manager
436 -- (parallel system only)
437 getSysMan = readIORef v_Pgm_sysman
440 %************************************************************************
442 \subsection{GHC Usage message}
444 %************************************************************************
446 Show the usage message and exit
449 showGhcUsage = do { usage_path <- readIORef v_Path_usage
450 ; usage <- readFile usage_path
452 ; exitWith ExitSuccess }
455 dump ('$':'$':s) = hPutStr stderr progName >> dump s
456 dump (c:s) = hPutChar stderr c >> dump s
458 packageConfigPath = readIORef v_Path_package_config
462 %************************************************************************
464 \subsection{Managing temporary files
466 %************************************************************************
469 GLOBAL_VAR(v_FilesToClean, [], [String] )
470 GLOBAL_VAR(v_TmpDir, cDEFAULT_TMPDIR, String )
471 -- v_TmpDir has no closing '/'
475 setTmpDir dir = writeIORef v_TmpDir dir
477 cleanTempFiles :: Int -> IO ()
478 cleanTempFiles verb = do fs <- readIORef v_FilesToClean
479 removeTmpFiles verb fs
481 cleanTempFilesExcept :: Int -> [FilePath] -> IO ()
482 cleanTempFilesExcept verb dont_delete
483 = do fs <- readIORef v_FilesToClean
484 let leftovers = filter (`notElem` dont_delete) fs
485 removeTmpFiles verb leftovers
486 writeIORef v_FilesToClean dont_delete
489 -- find a temporary name that doesn't already exist.
490 newTempName :: Suffix -> IO FilePath
492 = do x <- getProcessID
493 tmp_dir <- readIORef v_TmpDir
494 findTempName tmp_dir x
496 findTempName tmp_dir x
497 = do let filename = tmp_dir ++ "/ghc" ++ show x ++ '.':extn
498 b <- doesFileExist filename
499 if b then findTempName tmp_dir (x+1)
500 else do add v_FilesToClean filename -- clean it up later
503 addFilesToClean :: [FilePath] -> IO ()
504 -- May include wildcards [used by DriverPipeline.run_phase SplitMangle]
505 addFilesToClean files = mapM_ (add v_FilesToClean) files
507 removeTmpFiles :: Int -> [FilePath] -> IO ()
508 removeTmpFiles verb fs
509 = traceCmd "Deleting temp files"
510 ("Deleting: " ++ unwords fs)
513 rm f = removeFile f `catchAllIO`
516 hPutStrLn stderr ("Warning: deleting non-existent " ++ f)
522 %************************************************************************
524 \subsection{Running a program}
526 %************************************************************************
529 GLOBAL_VAR(v_Dry_run, False, Bool)
532 setDryRun = writeIORef v_Dry_run True
534 -----------------------------------------------------------------------------
535 -- Running an external program
537 runSomething :: String -- For -v message
538 -> String -- Command name (possibly a full path)
539 -- assumed already dos-ified
540 -> [String] -- Arguments
541 -- runSomething will dos-ify them
544 runSomething phase_name pgm args
545 = traceCmd phase_name cmd_line $
546 do { exit_code <- system cmd_line
547 ; if exit_code /= ExitSuccess
548 then throwDyn (PhaseFailed phase_name exit_code)
552 cmd_line = unwords (pgm : dosifyPaths args)
553 -- The pgm is already in native format (appropriate dir separators)
555 traceCmd :: String -> String -> IO () -> IO ()
556 -- a) trace the command (at two levels of verbosity)
557 -- b) don't do it at all if dry-run is set
558 traceCmd phase_name cmd_line action
559 = do { verb <- dynFlag verbosity
560 ; when (verb >= 2) $ hPutStrLn stderr ("*** " ++ phase_name)
561 ; when (verb >= 3) $ hPutStrLn stderr cmd_line
565 ; n <- readIORef v_Dry_run
569 ; action `catchAllIO` handle_exn verb
572 handle_exn verb exn = do { when (verb >= 2) (hPutStr stderr "\n")
573 ; when (verb >= 3) (hPutStrLn stderr ("Failed: " ++ cmd_line))
574 ; throwDyn (PhaseFailed phase_name (ExitFailure 1)) }
578 %************************************************************************
580 \subsection{Path names}
582 %************************************************************************
584 We maintain path names in Unix form ('/'-separated) right until
585 the last moment. On Windows we dos-ify them just before passing them
586 to the Windows command.
588 The alternative, of using '/' consistently on Unix and '\' on Windows,
589 proved quite awkward. There were a lot more calls to dosifyPath,
590 and even on Windows we might invoke a unix-like utility (eg 'sh'), which
591 interpreted a command line 'foo\baz' as 'foobaz'.
594 -----------------------------------------------------------------------------
595 -- Convert filepath into MSDOS form.
597 dosifyPaths :: [String] -> [String]
598 -- dosifyPaths does two things
599 -- a) change '/' to '\'
600 -- b) remove initial '/cygdrive/'
602 unDosifyPath :: String -> String
603 -- Just change '\' to '/'
605 pgmPath :: String -- Directory string in Unix format
606 -> String -- Program name with no directory separators
608 -> String -- Program invocation string in native format
612 #if defined(mingw32_TARGET_OS)
614 --------------------- Windows version ------------------
615 dosifyPaths xs = map dosifyPath xs
617 unDosifyPath xs = subst '\\' '/' xs
619 pgmPath dir pgm = dosifyPath dir ++ '\\' : pgm
622 = subst '/' '\\' real_stuff
624 -- fully convince myself that /cygdrive/ prefixes cannot
625 -- really appear here.
626 cygdrive_prefix = "/cygdrive/"
629 | cygdrive_prefix `isPrefixOf` stuff = drop (length cygdrive_prefix) stuff
634 --------------------- Unix version ---------------------
637 pgmPath dir pgm = dir ++ '/' : pgm
638 --------------------------------------------------------
641 subst a b ls = map (\ x -> if x == a then b else x) ls
645 -----------------------------------------------------------------------------
646 Path name construction
649 slash :: String -> String -> String
650 absPath, relPath :: [String] -> String
653 isSlash other = False
656 relPath xs = foldr1 slash xs
658 absPath xs = "" `slash` relPath xs
660 slash s1 s2 = s1 ++ ('/' : s2)
664 %************************************************************************
666 \subsection{Support code}
668 %************************************************************************
671 -----------------------------------------------------------------------------
672 -- Define getExecDir :: IO (Maybe String)
674 #if defined(mingw32_TARGET_OS)
675 getExecDir :: IO (Maybe String)
676 getExecDir = do h <- getModuleHandle Nothing
677 n <- getModuleFileName h
678 return (Just (reverse (tail (dropWhile (not . isSlash) (reverse (unDosifyPath n))))))
680 getExecDir :: IO (Maybe String) = do return Nothing
683 #ifdef mingw32_TARGET_OS
684 foreign import "_getpid" getProcessID :: IO Int -- relies on Int == Int32 on Windows
686 getProcessID :: IO Int
687 getProcessID = Posix.getProcessID