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
42 runSomething -- ToDo: make private
48 import Panic ( progName, GhcException(..) )
49 import Util ( global )
50 import CmdLineOpts ( dynFlag, verbosity )
52 import List ( intersperse, isPrefixOf )
53 import Exception ( throwDyn, catchAllIO )
54 import IO ( openFile, hClose, IOMode(..),
55 hPutStr, hPutChar, hPutStrLn, hFlush, stderr
57 import Directory ( doesFileExist, removeFile )
58 import IOExts ( IORef, readIORef, writeIORef )
59 import Monad ( when, unless )
60 import qualified System
61 import System ( ExitCode(..) )
63 #include "../includes/config.h"
65 #if !defined(mingw32_TARGET_OS)
66 import qualified Posix
68 import Ptr ( nullPtr )
71 #include "HsVersions.h"
73 {-# DEPRECATED runSomething "runSomething should be private to SysTools" #-}
78 The configuration story
79 ~~~~~~~~~~~~~~~~~~~~~~~
81 GHC needs various support files (library packages, RTS etc), plus
82 various auxiliary programs (cp, gcc, etc). It finds these in one
85 * When running as an *installed program*, GHC finds most of this support
86 stuff in the installed library tree. The path to this tree is passed
87 to GHC via the -B flag, and given to initSysTools .
89 * When running *in-place* in a build tree, GHC finds most of this support
90 stuff in the build tree. The path to the build tree is, again passed
93 GHC tells which of the two is the case by seeing whether package.conf
94 is in TopDir [installed] or in TopDir/ghc/driver [inplace] (what a hack).
97 SysTools.initSysProgs figures out exactly where all the auxiliary programs
98 are, and initialises mutable variables to make it easy to call them.
99 To to this, it makes use of definitions in Config.hs, which is a Haskell
100 file containing variables whose value is figured out by the build system.
102 Config.hs contains two sorts of things
104 cGCC, The *names* of the programs
107 etc They do *not* include paths
110 cUNLIT_DIR The *path* to the directory containing unlit, split etc
111 cSPLIT_DIR *relative* to the root of the build tree,
112 for use when running *in-place* in a build tree (only)
116 %************************************************************************
118 \subsection{Global variables to contain system programs}
120 %************************************************************************
123 GLOBAL_VAR(v_Pgm_L, error "pgm_L", String) -- unlit
124 GLOBAL_VAR(v_Pgm_P, error "pgm_P", String) -- cpp
125 GLOBAL_VAR(v_Pgm_c, error "pgm_c", String) -- gcc
126 GLOBAL_VAR(v_Pgm_m, error "pgm_m", String) -- asm code mangler
127 GLOBAL_VAR(v_Pgm_s, error "pgm_s", String) -- asm code splitter
128 GLOBAL_VAR(v_Pgm_a, error "pgm_a", String) -- as
129 GLOBAL_VAR(v_Pgm_l, error "pgm_l", String) -- ld
130 GLOBAL_VAR(v_Pgm_MkDLL, error "pgm_dll", String) -- mkdll
132 GLOBAL_VAR(v_Pgm_PERL, error "pgm_PERL", String) -- perl
133 GLOBAL_VAR(v_Pgm_T, error "pgm_T", String) -- touch
134 GLOBAL_VAR(v_Pgm_CP, error "pgm_CP", String) -- cp
136 GLOBAL_VAR(v_Path_package_config, error "path_package_config", String)
137 GLOBAL_VAR(v_Path_usage, error "ghc_usage.txt", String)
139 -- Parallel system only
140 GLOBAL_VAR(v_Pgm_sysman, error "pgm_sysman", String) -- system manager
144 %************************************************************************
146 \subsection{Initialisation}
148 %************************************************************************
151 initSysTools :: [String] -- Command-line arguments starting "-B"
153 -> IO String -- Set all the mutable variables above, holding
154 -- (a) the system programs
155 -- (b) the package-config file
156 -- (c) the GHC usage message
160 initSysTools minusB_args
161 = do { (am_installed, top_dir) <- getTopDir minusB_args
163 -- for "installed" this is the root of GHC's support files
164 -- for "in-place" it is the root of the build tree
166 ; let installed pgm = top_dir `slash` "extra-bin" `slash` pgm
167 inplace dir pgm = top_dir `slash` dir `slash` pgm
169 ; let pkgconfig_path | am_installed = top_dir `slash` "package.conf"
170 | otherwise = top_dir `slash` cGHC_DRIVER_DIR `slash` "package.conf.inplace"
172 -- Check that the in-place package config exists if
173 -- the installed one does not (we need at least one!)
174 ; config_exists <- doesFileExist pkgconfig_path
175 ; if config_exists then return ()
176 else throwDyn (InstallationError
177 ("Can't find package.conf in " ++ pkgconfig_path))
179 -- The GHC usage help message is found similarly to the package configuration
180 ; let ghc_usage_msg_path | am_installed = installed "ghc-usage.txt"
181 | otherwise = inplace cGHC_DRIVER_DIR "ghc-usage.txt"
184 -- For all systems, unlit, split, mangle are GHC utilities
185 -- architecture-specific stuff is done when building Config.hs
186 ; let unlit_path | am_installed = installed cGHC_UNLIT
187 | otherwise = inplace cGHC_UNLIT_DIR cGHC_UNLIT
189 -- split and mangle are Perl scripts
190 split_script | am_installed = installed cGHC_SPLIT
191 | otherwise = inplace cGHC_SPLIT_DIR cGHC_SPLIT
192 mangle_script | am_installed = installed cGHC_MANGLER
193 | otherwise = inplace cGHC_MANGLER_DIR cGHC_MANGLER
196 #if defined(mingw32_TARGET_OS)
197 -- WINDOWS-SPECIFIC STUFF
198 -- On Windows, gcc and friends are distributed with GHC,
199 -- so when "installed" we look in TopDir/bin
200 -- When "in-place" we look wherever the build-time configure
202 ; let cpp_path | am_installed = installed cRAWCPP
203 | otherwise = cRAWCPP
204 gcc_path | am_installed = installed cGCC
206 perl_path | am_installed = installed cGHC_PERL
207 | otherwise = cGHC_PERL
209 -- 'touch' is a GHC util for Windows, and similarly unlit, mangle
210 ; let touch_path | am_installed = installed cGHC_TOUCHY
211 | otherwise = inplace cGHC_TOUCHY_DIR cGHC_TOUCHY
213 -- On Win32 we don't want to rely on #!/bin/perl, so we prepend
214 -- a call to Perl to get the invocation of split and mangle
215 ; let split_path = perl_path ++ " " ++ split_script
216 mangle_path = perl_path ++ " " ++ mangle_script
218 ; let mkdll_path = cMKDLL
220 -- UNIX-SPECIFIC STUFF
221 -- On Unix, the "standard" tools are assumed to be
222 -- in the same place whether we are running "in-place" or "installed"
223 -- That place is wherever the build-time configure script found them.
224 ; let cpp_path = cRAWCPP
226 touch_path = cGHC_TOUCHY
227 perl_path = cGHC_PERL
228 mkdll_path = panic "Cant build DLLs on a non-Win32 system"
230 -- On Unix, for some historical reason, we do an install-time
231 -- configure to find Perl, and slam that on the front of
232 -- the installed script; so we can invoke them directly
234 -- a call to Perl to get the invocation of split and mangle
235 ; let split_path = split_script
236 mangle_path = mangle_script
240 -- For all systems, copy and remove are provided by the host
241 -- system; architecture-specific stuff is done when building Config.hs
242 ; let cp_path = cGHC_CP
244 -- Other things being equal, as and ld are simply gcc
245 ; let as_path = gcc_path
249 -- Initialise the global vars
250 ; writeIORef v_Path_package_config pkgconfig_path
251 ; writeIORef v_Path_usage ghc_usage_msg_path
253 ; writeIORef v_Pgm_sysman (top_dir ++ "/ghc/rts/parallel/SysMan")
254 -- Hans: this isn't right in general, but you can
255 -- elaborate it in the same way as the others
257 ; writeIORef v_Pgm_L unlit_path
258 ; writeIORef v_Pgm_P cpp_path
259 ; writeIORef v_Pgm_c gcc_path
260 ; writeIORef v_Pgm_m mangle_path
261 ; writeIORef v_Pgm_s split_path
262 ; writeIORef v_Pgm_a as_path
263 ; writeIORef v_Pgm_l ld_path
264 ; writeIORef v_Pgm_MkDLL mkdll_path
265 ; writeIORef v_Pgm_T touch_path
266 ; writeIORef v_Pgm_CP cp_path
267 ; writeIORef v_Pgm_PERL perl_path
273 setPgm is called when a command-line option like
275 is used to override a particular program with a new onw
278 setPgm :: String -> IO ()
279 -- The string is the flag, minus the '-pgm' prefix
280 -- So the first character says which program to override
282 setPgm ('P' : pgm) = writeIORef v_Pgm_P pgm
283 setPgm ('c' : pgm) = writeIORef v_Pgm_c pgm
284 setPgm ('m' : pgm) = writeIORef v_Pgm_m pgm
285 setPgm ('s' : pgm) = writeIORef v_Pgm_s pgm
286 setPgm ('a' : pgm) = writeIORef v_Pgm_a pgm
287 setPgm ('l' : pgm) = writeIORef v_Pgm_l pgm
288 setPgm pgm = unknownFlagErr ("-pgm" ++ pgm)
294 -- for "installed" this is the root of GHC's support files
295 -- for "in-place" it is the root of the build tree
298 -- 1. Set proto_top_dir
299 -- a) look for (the last) -B flag, and use it
300 -- b) if there are no -B flags, get the directory
301 -- where GHC is running
303 -- 2. If package.conf exists in proto_top_dir, we are running
304 -- installed; and TopDir = proto_top_dir
306 -- 3. Otherwise we are running in-place, so
307 -- proto_top_dir will be /...stuff.../ghc/compiler
308 -- Set TopDir to /...stuff..., which is the root of the build tree
310 -- This is very gruesome indeed
312 getTopDir :: [String]
313 -> IO (Bool, -- True <=> am installed, False <=> in-place
317 = do { proto_top_dir <- get_proto
319 -- Discover whether we're running in a build tree or in an installation,
320 -- by looking for the package configuration file.
321 ; am_installed <- doesFileExist (proto_top_dir `slash` "package.conf")
323 ; if am_installed then
324 return (True, proto_top_dir)
326 return (False, remove_suffix proto_top_dir)
329 get_proto | not (null minusbs)
330 = return (dosifyPath (drop 2 (last minusbs)))
332 = do { maybe_exec_dir <- getExecDir -- Get directory of executable
333 ; case maybe_exec_dir of -- (only works on Windows)
334 Nothing -> throwDyn (InstallationError ("missing -B<dir> option"))
335 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 '/'
348 getExecDir = return Nothing
352 %************************************************************************
354 \subsection{Running an external program}
356 %************************************************************************
360 runUnlit :: [String] -> IO ()
361 runUnlit args = do p <- readIORef v_Pgm_L
362 runSomething "Literate pre-processor" p args
364 runCpp :: [String] -> IO ()
365 runCpp args = do p <- readIORef v_Pgm_P
366 runSomething "C pre-processor" p args
368 runCc :: [String] -> IO ()
369 runCc args = do p <- readIORef v_Pgm_c
370 runSomething "C Compiler" p args
372 runMangle :: [String] -> IO ()
373 runMangle args = do p <- readIORef v_Pgm_m
374 runSomething "Mangler" p args
376 runSplit :: [String] -> IO ()
377 runSplit args = do p <- readIORef v_Pgm_s
378 runSomething "Splitter" p args
380 runAs :: [String] -> IO ()
381 runAs args = do p <- readIORef v_Pgm_a
382 runSomething "Assembler" p args
384 runLink :: [String] -> IO ()
385 runLink args = do p <- readIORef v_Pgm_l
386 runSomething "Linker" p args
388 runMkDLL :: [String] -> IO ()
389 runMkDLL args = do p <- readIORef v_Pgm_MkDLL
390 runSomething "Make DLL" p args
392 touch :: String -> String -> IO ()
393 touch purpose arg = do p <- readIORef v_Pgm_T
394 runSomething purpose p [arg]
396 copy :: String -> String -> String -> IO ()
397 copy purpose from to = do p <- readIORef v_Pgm_CP
398 runSomething purpose p [from,to]
402 getSysMan :: IO String -- How to invoke the system manager
403 -- (parallel system only)
404 getSysMan = readIORef v_Pgm_sysman
407 %************************************************************************
409 \subsection{GHC Usage message}
411 %************************************************************************
413 Show the usage message and exit
416 showGhcUsage = do { usage_path <- readIORef v_Path_usage
417 ; usage <- readFile usage_path
419 ; System.exitWith System.ExitSuccess }
422 dump ('$':'$':s) = hPutStr stderr progName >> dump s
423 dump (c:s) = hPutChar stderr c >> dump s
425 packageConfigPath = readIORef v_Path_package_config
429 %************************************************************************
431 \subsection{Managing temporary files
433 %************************************************************************
435 One reason this code is here is because SysTools.system needs to make
439 GLOBAL_VAR(v_FilesToClean, [], [String] )
440 GLOBAL_VAR(v_TmpDir, cDEFAULT_TMPDIR, String )
441 -- v_TmpDir has no closing '/'
445 setTmpDir dir = writeIORef v_TmpDir dir
447 cleanTempFiles :: Int -> IO ()
448 cleanTempFiles verb = do fs <- readIORef v_FilesToClean
449 removeTmpFiles verb fs
451 cleanTempFilesExcept :: Int -> [FilePath] -> IO ()
452 cleanTempFilesExcept verb dont_delete
453 = do fs <- readIORef v_FilesToClean
454 let leftovers = filter (`notElem` dont_delete) fs
455 removeTmpFiles verb leftovers
456 writeIORef v_FilesToClean dont_delete
459 -- find a temporary name that doesn't already exist.
460 newTempName :: Suffix -> IO FilePath
462 = do x <- getProcessID
463 tmp_dir <- readIORef v_TmpDir
464 findTempName tmp_dir x
466 findTempName tmp_dir x
467 = do let filename = tmp_dir ++ "/ghc" ++ show x ++ '.':extn
468 b <- doesFileExist filename
469 if b then findTempName tmp_dir (x+1)
470 else do add v_FilesToClean filename -- clean it up later
473 addFilesToClean :: [FilePath] -> IO ()
474 -- May include wildcards [used by DriverPipeline.run_phase SplitMangle]
475 addFilesToClean files = mapM_ (add v_FilesToClean) files
477 removeTmpFiles :: Int -> [FilePath] -> IO ()
478 removeTmpFiles verb fs
479 = traceCmd "Deleting temp files"
480 ("Deleting: " ++ concat (intersperse " " fs))
483 rm f = removeFile f `catchAllIO`
484 (\exn -> hPutStrLn stderr ("Warning: deleting non-existent " ++ f) >>
490 %************************************************************************
492 \subsection{Running a program}
494 %************************************************************************
497 GLOBAL_VAR(v_Dry_run, False, Bool)
500 setDryRun = writeIORef v_Dry_run True
502 -----------------------------------------------------------------------------
503 -- Running an external program
505 runSomething :: String -- For -v message
506 -> String -- Command name (possibly a full path)
507 -- assumed already dos-ified
508 -> [String] -- Arguments
509 -- runSomthing will dos-ify them
512 runSomething phase_name pgm args
513 = traceCmd phase_name cmd_line $
514 do { exit_code <- System.system cmd_line
515 ; if exit_code /= ExitSuccess
516 then throwDyn (PhaseFailed phase_name exit_code)
520 cmd_line = unwords (pgm : dosifyPaths args)
522 traceCmd :: String -> String -> IO () -> IO ()
523 -- a) trace the command (at two levels of verbosity)
524 -- b) don't do it at all if dry-run is set
525 traceCmd phase_name cmd_line action
526 = do { verb <- dynFlag verbosity
527 ; when (verb >= 2) $ hPutStrLn stderr ("*** " ++ phase_name)
528 ; when (verb >= 3) $ hPutStrLn stderr cmd_line
532 ; n <- readIORef v_Dry_run
536 ; action `catchAllIO` handle_exn verb
539 handle_exn verb exn = do { when (verb >= 2) (hPutStr stderr "\n")
540 ; when (verb >= 3) (hPutStrLn stderr ("Failed: " ++ cmd_line))
541 ; throwDyn (PhaseFailed phase_name (ExitFailure 1)) }
545 %************************************************************************
547 \subsection{Support code}
549 %************************************************************************
553 -----------------------------------------------------------------------------
554 -- Convert filepath into MSDOS form.
556 dosifyPaths :: [String] -> [String]
557 dosifyPath :: String -> String
558 -- dosifyPath does two things
559 -- a) change '/' to '\'
560 -- b) remove initial '/cygdrive/'
562 #if defined(mingw32_TARGET_OS)
563 dosifyPaths xs = map dosifyPath xs
566 = subst '/' '\\' real_stuff
568 -- fully convince myself that /cygdrive/ prefixes cannot
569 -- really appear here.
570 cygdrive_prefix = "/cygdrive/"
573 | cygdrive_prefix `isPrefixOf` stuff = drop (length cygdrive_prefix) stuff
576 subst a b ls = map (\ x -> if x == a then b else x) ls
582 -----------------------------------------------------------------------------
583 -- Path name construction
584 -- At the moment, we always use '/' and rely on dosifyPath
585 -- to switch to DOS pathnames when necessary
587 slash :: String -> String -> String
588 absPath, relPath :: [String] -> String
592 isSlash other = False
595 relPath xs = foldr1 slash xs
597 absPath xs = "" `slash` relPath xs
599 #if defined(mingw32_TARGET_OS)
600 slash s1 s2 = s1 ++ ('\\' : s2)
602 slash s1 s2 = s1 ++ ('/' : s2)
605 -----------------------------------------------------------------------------
606 -- Define myGetProcessId :: IO Int
608 #ifdef mingw32_TARGET_OS
609 foreign import "_getpid" getProcessID :: IO Int -- relies on Int == Int32 on Windows
610 foreign import stdcall "GetCurrentDirectoryA" getCurrentDirectory :: Int32 -> CString -> IO Int32
611 getExecDir :: IO (Maybe String)
612 getExecDir = do len <- getCurrentDirectory 0 nullPtr
613 buf <- mallocArray (fromIntegral len)
614 ret <- getCurrentDirectory len buf
615 if ret == 0 then return Nothing
616 else do s <- peekCString buf
617 destructArray (fromIntegral len) buf
620 getProcessID :: IO Int
621 getProcessID = Posix.getProcessID
622 getExecDir :: IO (Maybe String) = do return Nothing