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.system, -- String -> IO Int -- System.system
39 showGhcUsage, -- IO () Shows usage message and exits
40 getSysMan, -- IO String Parallel system only
41 dosifyPath, -- String -> String
43 runSomething -- ToDo: make private
49 import Panic ( progName, GhcException(..) )
50 import Util ( global )
51 import CmdLineOpts ( dynFlag, verbosity )
53 import List ( intersperse )
54 import Exception ( throwDyn, catchAllIO )
55 import IO ( hPutStr, hPutChar, hPutStrLn, hFlush, stderr )
56 import Directory ( doesFileExist, removeFile )
57 import IOExts ( IORef, readIORef, writeIORef )
58 import Monad ( when, unless )
59 import qualified System
60 import System ( ExitCode(..) )
62 #include "../includes/config.h"
64 #if !defined(mingw32_TARGET_OS)
65 import qualified Posix
67 import Addr ( nullAddr )
70 #include "HsVersions.h"
72 {-# DEPRECATED runSomething "runSomething should be private to SysTools" #-}
77 The configuration story
78 ~~~~~~~~~~~~~~~~~~~~~~~
80 GHC needs various support files (library packages, RTS etc), plus
81 various auxiliary programs (cp, gcc, etc). It finds these in one
84 * When running as an *installed program*, GHC finds most of this support
85 stuff in the installed library tree. The path to this tree is passed
86 to GHC via the -B flag, and given to initSysTools .
88 * When running *in-place* in a build tree, GHC finds most of this support
89 stuff in the build tree. The path to the build tree is, again passed
92 GHC tells which of the two is the case by seeing whether package.conf
93 is in TopDir [installed] or in TopDir/ghc/driver [inplace] (what a hack).
96 SysTools.initSysProgs figures out exactly where all the auxiliary programs
97 are, and initialises mutable variables to make it easy to call them.
98 To to this, it makes use of definitions in Config.hs, which is a Haskell
99 file containing variables whose value is figured out by the build system.
101 Config.hs contains two sorts of things
103 cGCC, The *names* of the programs
106 etc They do *not* include paths
109 cUNLIT_DIR The *path* to the directory containing unlit, split etc
110 cSPLIT_DIR *relative* to the root of the build tree,
111 for use when running *in-place* in a build tree (only)
115 %************************************************************************
117 \subsection{Global variables to contain system programs}
119 %************************************************************************
122 GLOBAL_VAR(v_Pgm_L, error "pgm_L", String) -- unlit
123 GLOBAL_VAR(v_Pgm_P, error "pgm_P", String) -- cpp
124 GLOBAL_VAR(v_Pgm_c, error "pgm_c", String) -- gcc
125 GLOBAL_VAR(v_Pgm_m, error "pgm_m", String) -- asm code mangler
126 GLOBAL_VAR(v_Pgm_s, error "pgm_s", String) -- asm code splitter
127 GLOBAL_VAR(v_Pgm_a, error "pgm_a", String) -- as
128 GLOBAL_VAR(v_Pgm_l, error "pgm_l", String) -- ld
129 GLOBAL_VAR(v_Pgm_MkDLL, error "pgm_dll", String) -- mkdll
131 GLOBAL_VAR(v_Pgm_T, error "pgm_T", String) -- touch
132 GLOBAL_VAR(v_Pgm_CP, error "pgm_CP", String) -- cp
134 GLOBAL_VAR(v_Path_package_config, error "path_package_config", String)
135 GLOBAL_VAR(v_Path_usage, error "ghc_usage.txt", String)
137 -- Parallel system only
138 GLOBAL_VAR(v_Pgm_sysman, error "pgm_sysman", String) -- system manager
142 %************************************************************************
144 \subsection{Initialisation}
146 %************************************************************************
149 initSysTools :: [String] -- Command-line arguments starting "-B"
151 -> IO String -- Set all the mutable variables above, holding
152 -- (a) the system programs
153 -- (b) the package-config file
154 -- (c) the GHC usage message
158 initSysTools minusB_args
159 = do { (am_installed, top_dir) <- getTopDir minusB_args
161 -- for "installed" this is the root of GHC's support files
162 -- for "in-place" it is the root of the build tree
164 ; let installed_bin pgm = top_dir `slash` "bin" `slash` pgm
165 installed file = top_dir `slash` file
166 inplace dir pgm = top_dir `slash` dir `slash` pgm
169 | am_installed = installed "package.conf"
170 | otherwise = inplace cGHC_DRIVER_DIR "package.conf.inplace"
173 | am_installed = installed "ghc-usage.txt"
174 | otherwise = inplace cGHC_DRIVER_DIR "ghc-usage.txt"
176 -- For all systems, unlit, split, mangle are GHC utilities
177 -- architecture-specific stuff is done when building Config.hs
179 | am_installed = installed_bin cGHC_UNLIT
180 | otherwise = inplace cGHC_UNLIT_DIR cGHC_UNLIT
182 -- split and mangle are Perl scripts
184 | am_installed = installed_bin cGHC_SPLIT
185 | otherwise = inplace cGHC_SPLIT_DIR cGHC_SPLIT
188 | am_installed = installed_bin cGHC_MANGLER
189 | otherwise = inplace cGHC_MANGLER_DIR cGHC_MANGLER
191 -- Check that the package config exists
192 ; config_exists <- doesFileExist pkgconfig_path
193 ; when (not config_exists) $
194 throwDyn (InstallationError
195 ("Can't find package.conf in " ++ pkgconfig_path))
197 #if defined(mingw32_TARGET_OS)
198 -- WINDOWS-SPECIFIC STUFF
199 -- On Windows, gcc and friends are distributed with GHC,
200 -- so when "installed" we look in TopDir/bin
201 -- When "in-place" we look wherever the build-time configure
203 ; let cpp_path | am_installed = installed cRAWCPP
204 | otherwise = cRAWCPP
205 gcc_path | am_installed = installed cGCC
207 perl_path | am_installed = installed cGHC_PERL
208 | otherwise = cGHC_PERL
210 -- 'touch' is a GHC util for Windows, and similarly unlit, mangle
211 ; let touch_path | am_installed = installed cGHC_TOUCHY
212 | otherwise = inplace cGHC_TOUCHY_DIR cGHC_TOUCHY
214 -- On Win32 we don't want to rely on #!/bin/perl, so we prepend
215 -- a call to Perl to get the invocation of split and mangle
216 ; let split_path = perl_path ++ " " ++ split_script
217 mangle_path = perl_path ++ " " ++ mangle_script
219 ; let mkdll_path = cMKDLL
221 -- UNIX-SPECIFIC STUFF
222 -- On Unix, the "standard" tools are assumed to be
223 -- in the same place whether we are running "in-place" or "installed"
224 -- That place is wherever the build-time configure script found them.
225 ; let cpp_path = cRAWCPP
227 touch_path = cGHC_TOUCHY
228 mkdll_path = panic "Cant build DLLs on a non-Win32 system"
230 -- On Unix, scripts are invoked using the '#!' method. Binary
231 -- installations of GHC on Unix place the correct line on the front
232 -- of the script at installation time, so we don't want to wire-in
233 -- our knowledge of $(PERL) on the host system here.
234 ; let split_path = split_script
235 mangle_path = mangle_script
239 -- For all systems, copy and remove are provided by the host
240 -- system; architecture-specific stuff is done when building Config.hs
241 ; let cp_path = cGHC_CP
243 -- Other things being equal, as and ld are simply gcc
244 ; let as_path = gcc_path
248 -- Initialise the global vars
249 ; writeIORef v_Path_package_config pkgconfig_path
250 ; writeIORef v_Path_usage ghc_usage_msg_path
252 ; writeIORef v_Pgm_sysman (top_dir ++ "/ghc/rts/parallel/SysMan")
253 -- Hans: this isn't right in general, but you can
254 -- elaborate it in the same way as the others
256 ; writeIORef v_Pgm_L unlit_path
257 ; writeIORef v_Pgm_P cpp_path
258 ; writeIORef v_Pgm_c gcc_path
259 ; writeIORef v_Pgm_m mangle_path
260 ; writeIORef v_Pgm_s split_path
261 ; writeIORef v_Pgm_a as_path
262 ; writeIORef v_Pgm_l ld_path
263 ; writeIORef v_Pgm_MkDLL mkdll_path
264 ; writeIORef v_Pgm_T touch_path
265 ; writeIORef v_Pgm_CP cp_path
271 setPgm is called when a command-line option like
273 is used to override a particular program with a new onw
276 setPgm :: String -> IO ()
277 -- The string is the flag, minus the '-pgm' prefix
278 -- So the first character says which program to override
280 setPgm ('P' : pgm) = writeIORef v_Pgm_P pgm
281 setPgm ('c' : pgm) = writeIORef v_Pgm_c pgm
282 setPgm ('m' : pgm) = writeIORef v_Pgm_m pgm
283 setPgm ('s' : pgm) = writeIORef v_Pgm_s pgm
284 setPgm ('a' : pgm) = writeIORef v_Pgm_a pgm
285 setPgm ('l' : pgm) = writeIORef v_Pgm_l pgm
286 setPgm pgm = unknownFlagErr ("-pgm" ++ pgm)
292 -- for "installed" this is the root of GHC's support files
293 -- for "in-place" it is the root of the build tree
296 -- 1. Set proto_top_dir
297 -- a) look for (the last) -B flag, and use it
298 -- b) if there are no -B flags, get the directory
299 -- where GHC is running
301 -- 2. If package.conf exists in proto_top_dir, we are running
302 -- installed; and TopDir = proto_top_dir
304 -- 3. Otherwise we are running in-place, so
305 -- proto_top_dir will be /...stuff.../ghc/compiler
306 -- Set TopDir to /...stuff..., which is the root of the build tree
308 -- This is very gruesome indeed
310 getTopDir :: [String]
311 -> IO (Bool, -- True <=> am installed, False <=> in-place
315 = do { proto_top_dir <- get_proto
317 -- Discover whether we're running in a build tree or in an installation,
318 -- by looking for the package configuration file.
319 ; am_installed <- doesFileExist (proto_top_dir `slash` "package.conf")
321 ; if am_installed then
322 return (True, proto_top_dir)
324 return (False, remove_suffix proto_top_dir)
327 get_proto | not (null minusbs)
328 = return (dosifyPath (drop 2 (last minusbs)))
330 = do { maybe_exec_dir <- getExecDir -- Get directory of executable
331 ; case maybe_exec_dir of -- (only works on Windows)
332 Nothing -> throwDyn (InstallationError
333 "missing -B<dir> option")
334 Just dir -> return dir
337 remove_suffix dir -- "/...stuff.../ghc/compiler" --> "/...stuff..."
338 = ASSERT2( not (null p1) &&
340 dosifyPath dir == dosifyPath (top_dir ++ "/ghc/compiler"),
344 p1 = dropWhile (not . isSlash) (reverse dir)
345 p2 = dropWhile (not . isSlash) (tail p1) -- head is '/'
346 top_dir = reverse (tail p2) -- head is '/'
350 %************************************************************************
352 \subsection{Running an external program}
354 %************************************************************************
358 runUnlit :: [String] -> IO ()
359 runUnlit args = do p <- readIORef v_Pgm_L
360 runSomething "Literate pre-processor" p args
362 runCpp :: [String] -> IO ()
363 runCpp args = do p <- readIORef v_Pgm_P
364 runSomething "C pre-processor" p args
366 runCc :: [String] -> IO ()
367 runCc args = do p <- readIORef v_Pgm_c
368 runSomething "C Compiler" p args
370 runMangle :: [String] -> IO ()
371 runMangle args = do p <- readIORef v_Pgm_m
372 runSomething "Mangler" p args
374 runSplit :: [String] -> IO ()
375 runSplit args = do p <- readIORef v_Pgm_s
376 runSomething "Splitter" p args
378 runAs :: [String] -> IO ()
379 runAs args = do p <- readIORef v_Pgm_a
380 runSomething "Assembler" p args
382 runLink :: [String] -> IO ()
383 runLink args = do p <- readIORef v_Pgm_l
384 runSomething "Linker" p args
386 runMkDLL :: [String] -> IO ()
387 runMkDLL args = do p <- readIORef v_Pgm_MkDLL
388 runSomething "Make DLL" p args
390 touch :: String -> String -> IO ()
391 touch purpose arg = do p <- readIORef v_Pgm_T
392 runSomething purpose p [arg]
394 copy :: String -> String -> String -> IO ()
395 copy purpose from to = do p <- readIORef v_Pgm_CP
396 runSomething purpose p [from,to]
400 getSysMan :: IO String -- How to invoke the system manager
401 -- (parallel system only)
402 getSysMan = readIORef v_Pgm_sysman
405 %************************************************************************
407 \subsection{GHC Usage message}
409 %************************************************************************
411 Show the usage message and exit
414 showGhcUsage = do { usage_path <- readIORef v_Path_usage
415 ; usage <- readFile usage_path
417 ; System.exitWith System.ExitSuccess }
420 dump ('$':'$':s) = hPutStr stderr progName >> dump s
421 dump (c:s) = hPutChar stderr c >> dump s
423 packageConfigPath = readIORef v_Path_package_config
427 %************************************************************************
429 \subsection{Managing temporary files
431 %************************************************************************
433 One reason this code is here is because SysTools.system needs to make
437 GLOBAL_VAR(v_FilesToClean, [], [String] )
438 GLOBAL_VAR(v_TmpDir, cDEFAULT_TMPDIR, String )
439 -- v_TmpDir has no closing '/'
443 setTmpDir dir = writeIORef v_TmpDir dir
445 cleanTempFiles :: Int -> IO ()
446 cleanTempFiles verb = do fs <- readIORef v_FilesToClean
447 removeTmpFiles verb fs
449 cleanTempFilesExcept :: Int -> [FilePath] -> IO ()
450 cleanTempFilesExcept verb dont_delete
451 = do fs <- readIORef v_FilesToClean
452 let leftovers = filter (`notElem` dont_delete) fs
453 removeTmpFiles verb leftovers
454 writeIORef v_FilesToClean dont_delete
457 -- find a temporary name that doesn't already exist.
458 newTempName :: Suffix -> IO FilePath
460 = do x <- getProcessID
461 tmp_dir <- readIORef v_TmpDir
462 findTempName tmp_dir x
464 findTempName tmp_dir x
465 = do let filename = tmp_dir ++ "/ghc" ++ show x ++ '.':extn
466 b <- doesFileExist filename
467 if b then findTempName tmp_dir (x+1)
468 else do add v_FilesToClean filename -- clean it up later
471 addFilesToClean :: [FilePath] -> IO ()
472 -- May include wildcards [used by DriverPipeline.run_phase SplitMangle]
473 addFilesToClean files = mapM_ (add v_FilesToClean) files
475 removeTmpFiles :: Int -> [FilePath] -> IO ()
476 removeTmpFiles verb fs
477 = traceCmd "Deleting temp files"
478 ("Deleting: " ++ concat (intersperse " " fs))
481 rm f = removeFile f `catchAllIO`
482 (\exn -> hPutStrLn stderr ("Warning: deleting non-existent " ++ f) >>
488 %************************************************************************
490 \subsection{Running a program}
492 %************************************************************************
495 GLOBAL_VAR(v_Dry_run, False, Bool)
498 setDryRun = writeIORef v_Dry_run True
500 -----------------------------------------------------------------------------
501 -- Running an external program
503 runSomething :: String -- For -v message
504 -> String -- Command name (possibly a full path)
505 -- assumed already dos-ified
506 -> [String] -- Arguments
507 -- runSomthing will dos-ify them
510 runSomething phase_name pgm args
511 = traceCmd phase_name cmd_line $
512 do { exit_code <- System.system cmd_line
513 ; if exit_code /= ExitSuccess
514 then throwDyn (PhaseFailed phase_name exit_code)
518 cmd_line = unwords (pgm : dosifyPaths args)
520 traceCmd :: String -> String -> IO () -> IO ()
521 -- a) trace the command (at two levels of verbosity)
522 -- b) don't do it at all if dry-run is set
523 traceCmd phase_name cmd_line action
524 = do { verb <- dynFlag verbosity
525 ; when (verb >= 2) $ hPutStrLn stderr ("*** " ++ phase_name)
526 ; when (verb >= 3) $ hPutStrLn stderr cmd_line
530 ; n <- readIORef v_Dry_run
534 ; action `catchAllIO` handle_exn verb
537 handle_exn verb exn = do { when (verb >= 2) (hPutStr stderr "\n")
538 ; when (verb >= 3) (hPutStrLn stderr ("Failed: " ++ cmd_line))
539 ; throwDyn (PhaseFailed phase_name (ExitFailure 1)) }
543 %************************************************************************
545 \subsection{Support code}
547 %************************************************************************
551 -----------------------------------------------------------------------------
552 -- Convert filepath into MSDOS form.
554 dosifyPaths :: [String] -> [String]
555 dosifyPath :: String -> String
556 -- dosifyPath does two things
557 -- a) change '/' to '\'
558 -- b) remove initial '/cygdrive/'
560 #if defined(mingw32_TARGET_OS)
561 dosifyPaths xs = map dosifyPath xs
564 = subst '/' '\\' real_stuff
566 -- fully convince myself that /cygdrive/ prefixes cannot
567 -- really appear here.
568 cygdrive_prefix = "/cygdrive/"
571 | cygdrive_prefix `isPrefixOf` stuff = drop (length cygdrive_prefix) stuff
574 subst a b ls = map (\ x -> if x == a then b else x) ls
580 -----------------------------------------------------------------------------
581 -- Path name construction
582 -- At the moment, we always use '/' and rely on dosifyPath
583 -- to switch to DOS pathnames when necessary
585 slash :: String -> String -> String
586 absPath, relPath :: [String] -> String
590 isSlash other = False
593 relPath xs = foldr1 slash xs
595 absPath xs = "" `slash` relPath xs
597 #if defined(mingw32_TARGET_OS)
598 slash s1 s2 = s1 ++ ('\\' : s2)
600 slash s1 s2 = s1 ++ ('/' : s2)
603 -----------------------------------------------------------------------------
604 -- Define myGetProcessId :: IO Int
605 -- getExecDir :: IO (Maybe String)
607 #ifdef mingw32_TARGET_OS
608 foreign import "_getpid" getProcessID :: IO Int -- relies on Int == Int32 on Windows
610 getExecDir :: IO (Maybe String)
611 getExecDir = return Nothing
613 foreign import stdcall "GetCurrentDirectoryA" getCurrentDirectory :: Int32 -> CString -> IO Int32
614 getExecDir = do len <- getCurrentDirectory 0 nullAddr
615 buf <- mallocArray (fromIntegral len)
616 ret <- getCurrentDirectory len buf
617 if ret == 0 then return Nothing
618 else do s <- peekCString buf
619 destructArray (fromIntegral len) buf
623 getProcessID :: IO Int
624 getProcessID = Posix.getProcessID
625 getExecDir :: IO (Maybe String) = do return Nothing