1 -----------------------------------------------------------------------------
3 -- (c) The University of Glasgow 2001-2003
5 -- Access to system tools: gcc, cp, rm etc
7 -----------------------------------------------------------------------------
14 -- Interface to system tools
15 runUnlit, runCpp, runCc, -- [Option] -> IO ()
16 runPp, -- [Option] -> IO ()
17 runMangle, runSplit, -- [Option] -> IO ()
18 runAs, runLink, -- [Option] -> IO ()
22 touch, -- String -> String -> IO ()
27 -- Temporary-file management
30 cleanTempDirs, cleanTempFiles, cleanTempFilesExcept,
37 #include "HsVersions.h"
48 import Control.Exception
52 import System.Environment
53 import System.FilePath
55 import SYSTEM_IO_ERROR as IO
56 import System.Directory
61 #ifndef mingw32_HOST_OS
62 import qualified System.Posix.Internals
63 #else /* Must be Win32 */
65 import CString ( CString, peekCString )
68 import System.Process ( runInteractiveProcess, getProcessExitCode )
69 import Control.Concurrent
71 import SrcLoc ( SrcLoc, mkSrcLoc, noSrcSpan, mkSrcSpan )
75 The configuration story
76 ~~~~~~~~~~~~~~~~~~~~~~~
78 GHC needs various support files (library packages, RTS etc), plus
79 various auxiliary programs (cp, gcc, etc). It finds these in one
82 * When running as an *installed program*, GHC finds most of this support
83 stuff in the installed library tree. The path to this tree is passed
84 to GHC via the -B flag, and given to initSysTools .
86 * When running *in-place* in a build tree, GHC finds most of this support
87 stuff in the build tree. The path to the build tree is, again passed
90 GHC tells which of the two is the case by seeing whether package.conf
91 is in TopDir [installed] or in TopDir/ghc/driver [inplace] (what a hack).
94 SysTools.initSysProgs figures out exactly where all the auxiliary programs
95 are, and initialises mutable variables to make it easy to call them.
96 To to this, it makes use of definitions in Config.hs, which is a Haskell
97 file containing variables whose value is figured out by the build system.
99 Config.hs contains two sorts of things
101 cGCC, The *names* of the programs
104 etc They do *not* include paths
107 cUNLIT_DIR_REL The *path* to the directory containing unlit, split etc
108 cSPLIT_DIR_REL *relative* to the root of the build tree,
109 for use when running *in-place* in a build tree (only)
113 ---------------------------------------------
114 NOTES for an ALTERNATIVE scheme (i.e *not* what is currently implemented):
116 Another hair-brained scheme for simplifying the current tool location
117 nightmare in GHC: Simon originally suggested using another
118 configuration file along the lines of GCC's specs file - which is fine
119 except that it means adding code to read yet another configuration
120 file. What I didn't notice is that the current package.conf is
121 general enough to do this:
124 {name = "tools", import_dirs = [], source_dirs = [],
125 library_dirs = [], hs_libraries = [], extra_libraries = [],
126 include_dirs = [], c_includes = [], package_deps = [],
127 extra_ghc_opts = ["-pgmc/usr/bin/gcc","-pgml${topdir}/bin/unlit", ... etc.],
128 extra_cc_opts = [], extra_ld_opts = []}
130 Which would have the advantage that we get to collect together in one
131 place the path-specific package stuff with the path-specific tool
134 ---------------------------------------------
136 %************************************************************************
138 \subsection{Initialisation}
140 %************************************************************************
143 initSysTools :: Maybe String -- Maybe TopDir path (without the '-B' prefix)
146 -> IO DynFlags -- Set all the mutable variables above, holding
147 -- (a) the system programs
148 -- (b) the package-config file
149 -- (c) the GHC usage message
152 initSysTools mbMinusB dflags0
153 = do { (am_installed, top_dir) <- findTopDir mbMinusB
155 -- for "installed" this is the root of GHC's support files
156 -- for "in-place" it is the root of the build tree
157 -- NB: top_dir is assumed to be in standard Unix
158 -- format, '/' separated
160 ; let installed, installed_bin :: FilePath -> FilePath
161 installed_bin pgm = top_dir </> pgm
162 installed file = top_dir </> file
163 inplace dir pgm = top_dir </> dir </> pgm
166 | am_installed = installed "package.conf"
167 | otherwise = inplace cGHC_DRIVER_DIR_REL "package.conf.inplace"
170 | am_installed = installed "ghc-usage.txt"
171 | otherwise = inplace cGHC_DRIVER_DIR_REL "ghc-usage.txt"
174 | am_installed = installed "ghci-usage.txt"
175 | otherwise = inplace cGHC_DRIVER_DIR_REL "ghci-usage.txt"
177 -- For all systems, unlit, split, mangle are GHC utilities
178 -- architecture-specific stuff is done when building Config.hs
180 | am_installed = installed_bin cGHC_UNLIT_PGM
181 | otherwise = inplace cGHC_UNLIT_DIR_REL cGHC_UNLIT_PGM
183 -- split and mangle are Perl scripts
185 | am_installed = installed_bin cGHC_SPLIT_PGM
186 | otherwise = inplace cGHC_SPLIT_DIR_REL cGHC_SPLIT_PGM
189 | am_installed = installed_bin cGHC_MANGLER_PGM
190 | otherwise = inplace cGHC_MANGLER_DIR_REL cGHC_MANGLER_PGM
193 | am_installed = installed_bin "bin/windres"
194 | otherwise = "windres"
196 ; tmpdir <- getTemporaryDirectory
197 ; let dflags1 = setTmpDir tmpdir dflags0
199 -- Check that the package config exists
200 ; config_exists <- doesFileExist pkgconfig_path
201 ; when (not config_exists) $
202 throwDyn (InstallationError
203 ("Can't find package.conf as " ++ pkgconfig_path))
205 -- On Windows, gcc and friends are distributed with GHC,
206 -- so when "installed" we look in TopDir/bin
207 -- When "in-place", or when not on Windows, we look wherever
208 -- the build-time configure script found them
210 -- The trailing "/" is absolutely essential; gcc seems
211 -- to construct file names simply by concatenating to
212 -- this -B path with no extra slash We use "/" rather
213 -- than "\\" because otherwise "\\\" is mangled
214 -- later on; although gcc_args are in NATIVE format,
216 -- (see comments with declarations of global variables)
217 gcc_b_arg = Option ("-B" ++ installed "gcc-lib/")
219 | isWindowsHost && am_installed
220 -- We tell gcc where its specs file + exes are (-B)
221 -- and also some places to pick up include files. We need
222 -- to be careful to put all necessary exes in the -B place
223 -- (as, ld, cc1, etc) since if they don't get found there,
224 -- gcc then tries to run unadorned "as", "ld", etc, and
225 -- will pick up whatever happens to be lying around in
226 -- the path, possibly including those from a cygwin
227 -- install on the target, which is exactly what we're
229 = (installed_bin "gcc", [gcc_b_arg])
230 | otherwise = (cGCC, [])
232 | isWindowsHost && am_installed = installed_bin cGHC_PERL
233 | otherwise = cGHC_PERL
234 -- 'touch' is a GHC util for Windows
238 then installed_bin cGHC_TOUCHY_PGM
239 else inplace cGHC_TOUCHY_DIR_REL cGHC_TOUCHY_PGM
240 | otherwise = "touch"
241 -- On Win32 we don't want to rely on #!/bin/perl, so we prepend
242 -- a call to Perl to get the invocation of split and mangle.
243 -- On Unix, scripts are invoked using the '#!' method. Binary
244 -- installations of GHC on Unix place the correct line on the
245 -- front of the script at installation time, so we don't want
246 -- to wire-in our knowledge of $(PERL) on the host system here.
247 (split_prog, split_args)
248 | isWindowsHost = (perl_path, [Option split_script])
249 | otherwise = (split_script, [])
250 (mangle_prog, mangle_args)
251 | isWindowsHost = (perl_path, [Option mangle_script])
252 | otherwise = (mangle_script, [])
253 (mkdll_prog, mkdll_args)
255 = panic "Can't build DLLs on a non-Win32 system"
257 (installed "gcc-lib/" </> cMKDLL,
258 [ Option "--dlltool-name",
259 Option (installed "gcc-lib/" </> "dlltool"),
260 Option "--driver-name",
261 Option gcc_prog, gcc_b_arg ])
262 | otherwise = (cMKDLL, [])
264 -- cpp is derived from gcc on all platforms
265 -- HACK, see setPgmP below. We keep 'words' here to remember to fix
266 -- Config.hs one day.
267 ; let cpp_path = (gcc_prog, gcc_args ++
268 (Option "-E"):(map Option (words cRAWCPP_FLAGS)))
270 -- Other things being equal, as and ld are simply gcc
271 ; let (as_prog,as_args) = (gcc_prog,gcc_args)
272 (ld_prog,ld_args) = (gcc_prog,gcc_args)
275 ghcUsagePath = ghc_usage_msg_path,
276 ghciUsagePath = ghci_usage_msg_path,
278 systemPackageConfig = pkgconfig_path,
282 pgm_c = (gcc_prog,gcc_args),
283 pgm_m = (mangle_prog,mangle_args),
284 pgm_s = (split_prog,split_args),
285 pgm_a = (as_prog,as_args),
286 pgm_l = (ld_prog,ld_args),
287 pgm_dll = (mkdll_prog,mkdll_args),
289 pgm_sysman = top_dir ++ "/ghc/rts/parallel/SysMan",
290 pgm_windres = windres_path
291 -- Hans: this isn't right in general, but you can
292 -- elaborate it in the same way as the others
299 -- for "installed" this is the root of GHC's support files
300 -- for "in-place" it is the root of the build tree
303 -- 1. Set proto_top_dir
304 -- if there is no given TopDir path, get the directory
305 -- where GHC is running (only on Windows)
307 -- 2. If package.conf exists in proto_top_dir, we are running
308 -- installed; and TopDir = proto_top_dir
310 -- 3. Otherwise we are running in-place, so
311 -- proto_top_dir will be /...stuff.../ghc/compiler
312 -- Set TopDir to /...stuff..., which is the root of the build tree
314 -- This is very gruesome indeed
316 findTopDir :: Maybe String -- Maybe TopDir path (without the '-B' prefix).
317 -> IO (Bool, -- True <=> am installed, False <=> in-place
318 String) -- TopDir (in Unix format '/' separated)
321 = do { top_dir <- get_proto
322 -- Discover whether we're running in a build tree or in an installation,
323 -- by looking for the package configuration file.
324 ; am_installed <- doesFileExist (top_dir </> "package.conf")
326 ; return (am_installed, top_dir)
329 -- get_proto returns a Unix-format path (relying on getBaseDir to do so too)
330 get_proto = case mbMinusB of
331 Just minusb -> return (normalise minusb)
333 -> do maybe_exec_dir <- getBaseDir -- Get directory of executable
334 case maybe_exec_dir of -- (only works on Windows;
335 -- returns Nothing on Unix)
336 Nothing -> throwDyn (InstallationError "missing -B<dir> option")
337 Just dir -> return dir
341 %************************************************************************
343 \subsection{Running an external program}
345 %************************************************************************
349 runUnlit :: DynFlags -> [Option] -> IO ()
350 runUnlit dflags args = do
352 runSomething dflags "Literate pre-processor" p args
354 runCpp :: DynFlags -> [Option] -> IO ()
355 runCpp dflags args = do
356 let (p,args0) = pgm_P dflags
357 args1 = args0 ++ args
358 mb_env <- getGccEnv args1
359 runSomethingFiltered dflags id "C pre-processor" p args1 mb_env
361 runPp :: DynFlags -> [Option] -> IO ()
362 runPp dflags args = do
364 runSomething dflags "Haskell pre-processor" p args
366 runCc :: DynFlags -> [Option] -> IO ()
367 runCc dflags args = do
368 let (p,args0) = pgm_c dflags
369 args1 = args0 ++ args
370 mb_env <- getGccEnv args1
371 runSomethingFiltered dflags cc_filter "C Compiler" p args1 mb_env
373 -- discard some harmless warnings from gcc that we can't turn off
374 cc_filter = unlines . doFilter . lines
377 gcc gives warnings in chunks like so:
378 In file included from /foo/bar/baz.h:11,
379 from /foo/bar/baz2.h:22,
381 /foo/flibble:14: global register variable ...
382 /foo/flibble:15: warning: call-clobbered r...
383 We break it up into its chunks, remove any call-clobbered register
384 warnings from each chunk, and then delete any chunks that we have
387 doFilter = unChunkWarnings . filterWarnings . chunkWarnings []
388 -- We can't assume that the output will start with an "In file inc..."
389 -- line, so we start off expecting a list of warnings rather than a
391 chunkWarnings :: [String] -- The location stack to use for the next
393 -> [String] -- The remaining lines to look at
394 -> [([String], [String])]
395 chunkWarnings loc_stack [] = [(loc_stack, [])]
396 chunkWarnings loc_stack xs
397 = case break loc_stack_start xs of
398 (warnings, lss:xs') ->
399 case span loc_start_continuation xs' of
401 (loc_stack, warnings) : chunkWarnings (lss : lsc) xs''
402 _ -> [(loc_stack, xs)]
404 filterWarnings :: [([String], [String])] -> [([String], [String])]
405 filterWarnings [] = []
406 -- If the warnings are already empty then we are probably doing
407 -- something wrong, so don't delete anything
408 filterWarnings ((xs, []) : zs) = (xs, []) : filterWarnings zs
409 filterWarnings ((xs, ys) : zs) = case filter wantedWarning ys of
410 [] -> filterWarnings zs
411 ys' -> (xs, ys') : filterWarnings zs
413 unChunkWarnings :: [([String], [String])] -> [String]
414 unChunkWarnings [] = []
415 unChunkWarnings ((xs, ys) : zs) = xs ++ ys ++ unChunkWarnings zs
417 loc_stack_start s = "In file included from " `isPrefixOf` s
418 loc_start_continuation s = " from " `isPrefixOf` s
420 | "warning: call-clobbered register used" `isContainedIn` w = False
423 isContainedIn :: String -> String -> Bool
424 xs `isContainedIn` ys = any (xs `isPrefixOf`) (tails ys)
426 -- If the -B<dir> option is set, add <dir> to PATH. This works around
427 -- a bug in gcc on Windows Vista where it can't find its auxiliary
428 -- binaries (see bug #1110).
429 getGccEnv :: [Option] -> IO (Maybe [(String,String)])
431 #if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ < 603
436 else do env <- getEnvironment
437 return (Just (map mangle_path env))
439 (b_dirs, _) = partitionWith get_b_opt opts
441 get_b_opt (Option ('-':'B':dir)) = Left dir
442 get_b_opt other = Right other
444 mangle_path (path,paths) | map toUpper path == "PATH"
445 = (path, '\"' : head b_dirs ++ "\";" ++ paths)
446 mangle_path other = other
449 runMangle :: DynFlags -> [Option] -> IO ()
450 runMangle dflags args = do
451 let (p,args0) = pgm_m dflags
452 runSomething dflags "Mangler" p (args0++args)
454 runSplit :: DynFlags -> [Option] -> IO ()
455 runSplit dflags args = do
456 let (p,args0) = pgm_s dflags
457 runSomething dflags "Splitter" p (args0++args)
459 runAs :: DynFlags -> [Option] -> IO ()
460 runAs dflags args = do
461 let (p,args0) = pgm_a dflags
462 args1 = args0 ++ args
463 mb_env <- getGccEnv args1
464 runSomethingFiltered dflags id "Assembler" p args1 mb_env
466 runLink :: DynFlags -> [Option] -> IO ()
467 runLink dflags args = do
468 let (p,args0) = pgm_l dflags
469 args1 = args0 ++ args
470 mb_env <- getGccEnv args1
471 runSomethingFiltered dflags id "Linker" p args1 mb_env
473 runMkDLL :: DynFlags -> [Option] -> IO ()
474 runMkDLL dflags args = do
475 let (p,args0) = pgm_dll dflags
476 args1 = args0 ++ args
477 mb_env <- getGccEnv (args0++args)
478 runSomethingFiltered dflags id "Make DLL" p args1 mb_env
480 runWindres :: DynFlags -> [Option] -> IO ()
481 runWindres dflags args = do
482 let (gcc,gcc_args) = pgm_c dflags
483 windres = pgm_windres dflags
484 mb_env <- getGccEnv gcc_args
485 runSomethingFiltered dflags id "Windres" windres
486 -- we must tell windres where to find gcc: it might not be on PATH
487 (Option ("--preprocessor=" ++
488 unwords (map quote (gcc : map showOpt gcc_args ++
489 ["-E", "-xc", "-DRC_INVOKED"])))
490 -- -- use-temp-file is required for windres to interpret the
491 -- quoting in the preprocessor arg above correctly. Without
492 -- this, windres calls the preprocessor with popen, which gets
493 -- the quoting wrong (discovered by experimentation and
494 -- reading the windres sources). See #1828.
495 : Option "--use-temp-file"
497 -- we must use the PATH workaround here too, since windres invokes gcc
500 quote x = '\"' : x ++ "\""
502 touch :: DynFlags -> String -> String -> IO ()
503 touch dflags purpose arg =
504 runSomething dflags purpose (pgm_T dflags) [FileOption "" arg]
506 copy :: DynFlags -> String -> FilePath -> FilePath -> IO ()
507 copy dflags purpose from to = copyWithHeader dflags purpose Nothing from to
509 copyWithHeader :: DynFlags -> String -> Maybe String -> FilePath -> FilePath
511 copyWithHeader dflags purpose maybe_header from to = do
512 showPass dflags purpose
514 h <- openFile to WriteMode
515 ls <- readFile from -- inefficient, but it'll do for now.
516 -- ToDo: speed up via slurping.
517 maybe (return ()) (hPutStr h) maybe_header
521 getExtraViaCOpts :: DynFlags -> IO [String]
522 getExtraViaCOpts dflags = do
523 f <- readFile (topDir dflags </> "extra-gcc-opts")
527 %************************************************************************
529 \subsection{Managing temporary files
531 %************************************************************************
534 GLOBAL_VAR(v_FilesToClean, [], [String] )
535 GLOBAL_VAR(v_DirsToClean, emptyFM, FiniteMap FilePath FilePath )
539 cleanTempDirs :: DynFlags -> IO ()
541 = unless (dopt Opt_KeepTmpFiles dflags)
542 $ do ds <- readIORef v_DirsToClean
543 removeTmpDirs dflags (eltsFM ds)
544 writeIORef v_DirsToClean emptyFM
546 cleanTempFiles :: DynFlags -> IO ()
547 cleanTempFiles dflags
548 = unless (dopt Opt_KeepTmpFiles dflags)
549 $ do fs <- readIORef v_FilesToClean
550 removeTmpFiles dflags fs
551 writeIORef v_FilesToClean []
553 cleanTempFilesExcept :: DynFlags -> [FilePath] -> IO ()
554 cleanTempFilesExcept dflags dont_delete
555 = unless (dopt Opt_KeepTmpFiles dflags)
556 $ do files <- readIORef v_FilesToClean
557 let (to_keep, to_delete) = partition (`elem` dont_delete) files
558 removeTmpFiles dflags to_delete
559 writeIORef v_FilesToClean to_keep
562 -- find a temporary name that doesn't already exist.
563 newTempName :: DynFlags -> Suffix -> IO FilePath
564 newTempName dflags extn
565 = do d <- getTempDir dflags
567 findTempName (d ++ "/ghc" ++ show x ++ "_") 0
569 findTempName :: FilePath -> Integer -> IO FilePath
570 findTempName prefix x
571 = do let filename = (prefix ++ show x) <.> extn
572 b <- doesFileExist filename
573 if b then findTempName prefix (x+1)
574 else do consIORef v_FilesToClean filename -- clean it up later
577 -- return our temporary directory within tmp_dir, creating one if we
578 -- don't have one yet
579 getTempDir :: DynFlags -> IO FilePath
580 getTempDir dflags@(DynFlags{tmpDir=tmp_dir})
581 = do mapping <- readIORef v_DirsToClean
582 case lookupFM mapping tmp_dir of
585 let prefix = tmp_dir ++ "/ghc" ++ show x ++ "_"
587 mkTempDir :: Integer -> IO FilePath
589 = let dirname = prefix ++ show x
590 in do createDirectory dirname
591 let mapping' = addToFM mapping tmp_dir dirname
592 writeIORef v_DirsToClean mapping'
593 debugTraceMsg dflags 2 (ptext (sLit "Created temporary directory:") <+> text dirname)
596 if isAlreadyExistsError e
602 addFilesToClean :: [FilePath] -> IO ()
603 -- May include wildcards [used by DriverPipeline.run_phase SplitMangle]
604 addFilesToClean files = mapM_ (consIORef v_FilesToClean) files
606 removeTmpDirs :: DynFlags -> [FilePath] -> IO ()
607 removeTmpDirs dflags ds
608 = traceCmd dflags "Deleting temp dirs"
609 ("Deleting: " ++ unwords ds)
610 (mapM_ (removeWith dflags removeDirectory) ds)
612 removeTmpFiles :: DynFlags -> [FilePath] -> IO ()
613 removeTmpFiles dflags fs
615 traceCmd dflags "Deleting temp files"
616 ("Deleting: " ++ unwords deletees)
617 (mapM_ (removeWith dflags removeFile) deletees)
619 -- Flat out refuse to delete files that are likely to be source input
620 -- files (is there a worse bug than having a compiler delete your source
623 -- Deleting source files is a sign of a bug elsewhere, so prominently flag
626 | null non_deletees = act
628 putMsg dflags (text "WARNING - NOT deleting source files:" <+> hsep (map text non_deletees))
631 (non_deletees, deletees) = partition isHaskellUserSrcFilename fs
633 removeWith :: DynFlags -> (FilePath -> IO ()) -> FilePath -> IO ()
634 removeWith dflags remover f = remover f `IO.catch`
636 let msg = if isDoesNotExistError e
637 then ptext (sLit "Warning: deleting non-existent") <+> text f
638 else ptext (sLit "Warning: exception raised when deleting")
641 in debugTraceMsg dflags 2 msg
644 -----------------------------------------------------------------------------
645 -- Running an external program
647 runSomething :: DynFlags
648 -> String -- For -v message
649 -> String -- Command name (possibly a full path)
650 -- assumed already dos-ified
651 -> [Option] -- Arguments
652 -- runSomething will dos-ify them
655 runSomething dflags phase_name pgm args =
656 runSomethingFiltered dflags id phase_name pgm args Nothing
659 :: DynFlags -> (String->String) -> String -> String -> [Option]
660 -> Maybe [(String,String)] -> IO ()
662 runSomethingFiltered dflags filter_fn phase_name pgm args mb_env = do
663 let real_args = filter notNull (map showOpt args)
664 traceCmd dflags phase_name (unwords (pgm:real_args)) $ do
665 (exit_code, doesn'tExist) <-
667 rc <- builderMainLoop dflags filter_fn pgm real_args mb_env
669 ExitSuccess{} -> return (rc, False)
671 -- rawSystem returns (ExitFailure 127) if the exec failed for any
672 -- reason (eg. the program doesn't exist). This is the only clue
673 -- we have, but we need to report something to the user because in
674 -- the case of a missing program there will otherwise be no output
676 | n == 127 -> return (rc, True)
677 | otherwise -> return (rc, False))
678 -- Should 'rawSystem' generate an IO exception indicating that
679 -- 'pgm' couldn't be run rather than a funky return code, catch
680 -- this here (the win32 version does this, but it doesn't hurt
681 -- to test for this in general.)
683 if IO.isDoesNotExistError err
684 #if defined(mingw32_HOST_OS) && __GLASGOW_HASKELL__ < 604
685 -- the 'compat' version of rawSystem under mingw32 always
686 -- maps 'errno' to EINVAL to failure.
687 || case (ioeGetErrorType err ) of { InvalidArgument{} -> True ; _ -> False}
689 then return (ExitFailure 1, True)
691 case (doesn'tExist, exit_code) of
692 (True, _) -> throwDyn (InstallationError ("could not execute: " ++ pgm))
693 (_, ExitSuccess) -> return ()
694 _ -> throwDyn (PhaseFailed phase_name exit_code)
696 builderMainLoop :: DynFlags -> (String -> String) -> FilePath
697 -> [String] -> Maybe [(String, String)]
699 #if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ < 603
700 builderMainLoop dflags filter_fn pgm real_args mb_env = do
701 rawSystem pgm real_args
703 builderMainLoop dflags filter_fn pgm real_args mb_env = do
705 (hStdIn, hStdOut, hStdErr, hProcess) <- runInteractiveProcess pgm real_args Nothing mb_env
707 -- and run a loop piping the output from the compiler to the log_action in DynFlags
708 hSetBuffering hStdOut LineBuffering
709 hSetBuffering hStdErr LineBuffering
710 forkIO (readerProc chan hStdOut filter_fn)
711 forkIO (readerProc chan hStdErr filter_fn)
712 -- we don't want to finish until 2 streams have been completed
713 -- (stdout and stderr)
714 -- nor until 1 exit code has been retrieved.
715 rc <- loop chan hProcess (2::Integer) (1::Integer) ExitSuccess
716 -- after that, we're done here.
722 -- status starts at zero, and increments each time either
723 -- a reader process gets EOF, or the build proc exits. We wait
724 -- for all of these to happen (status==3).
725 -- ToDo: we should really have a contingency plan in case any of
726 -- the threads dies, such as a timeout.
727 loop _ _ 0 0 exitcode = return exitcode
728 loop chan hProcess t p exitcode = do
730 then getProcessExitCode hProcess
733 Just code -> loop chan hProcess t (p-1) code
739 log_action dflags SevInfo noSrcSpan defaultUserStyle msg
740 loop chan hProcess t p exitcode
741 BuildError loc msg -> do
742 log_action dflags SevError (mkSrcSpan loc loc) defaultUserStyle msg
743 loop chan hProcess t p exitcode
745 loop chan hProcess (t-1) p exitcode
746 | otherwise -> loop chan hProcess t p exitcode
748 readerProc :: Chan BuildMessage -> Handle -> (String -> String) -> IO ()
749 readerProc chan hdl filter_fn =
750 (do str <- hGetContents hdl
751 loop (linesPlatform (filter_fn str)) Nothing)
754 -- ToDo: check errors more carefully
755 -- ToDo: in the future, the filter should be implemented as
756 -- a stream transformer.
758 loop [] Nothing = return ()
759 loop [] (Just err) = writeChan chan err
762 Just err@(BuildError srcLoc msg)
763 | leading_whitespace l -> do
764 loop ls (Just (BuildError srcLoc (msg $$ text l)))
770 _ -> panic "readerProc/loop"
773 = case parseError l of
775 writeChan chan (BuildMsg (text l))
777 Just (file, lineNum, colNum, msg) -> do
778 let srcLoc = mkSrcLoc (mkFastString file) lineNum colNum
779 loop ls (Just (BuildError srcLoc (text msg)))
781 leading_whitespace [] = False
782 leading_whitespace (x:_) = isSpace x
784 parseError :: String -> Maybe (String, Int, Int, String)
785 parseError s0 = case breakColon s0 of
786 Just (filename, s1) ->
787 case breakIntColon s1 of
788 Just (lineNum, s2) ->
789 case breakIntColon s2 of
790 Just (columnNum, s3) ->
791 Just (filename, lineNum, columnNum, s3)
793 Just (filename, lineNum, 0, s2)
797 breakColon :: String -> Maybe (String, String)
798 breakColon xs = case break (':' ==) xs of
799 (ys, _:zs) -> Just (ys, zs)
802 breakIntColon :: String -> Maybe (Int, String)
803 breakIntColon xs = case break (':' ==) xs of
805 | not (null ys) && all isAscii ys && all isDigit ys ->
811 | BuildError !SrcLoc !SDoc
815 showOpt :: Option -> String
816 showOpt (FileOption pre f) = pre ++ f
817 showOpt (Option s) = s
819 traceCmd :: DynFlags -> String -> String -> IO () -> IO ()
820 -- a) trace the command (at two levels of verbosity)
821 -- b) don't do it at all if dry-run is set
822 traceCmd dflags phase_name cmd_line action
823 = do { let verb = verbosity dflags
824 ; showPass dflags phase_name
825 ; debugTraceMsg dflags 3 (text cmd_line)
829 ; unless (dopt Opt_DryRun dflags) $ do {
832 ; action `IO.catch` handle_exn verb
835 handle_exn _verb exn = do { debugTraceMsg dflags 2 (char '\n')
836 ; debugTraceMsg dflags 2 (ptext (sLit "Failed:") <+> text cmd_line <+> text (show exn))
837 ; throwDyn (PhaseFailed phase_name (ExitFailure 1)) }
840 %************************************************************************
842 \subsection{Support code}
844 %************************************************************************
847 -----------------------------------------------------------------------------
848 -- Define getBaseDir :: IO (Maybe String)
850 getBaseDir :: IO (Maybe String)
851 #if defined(mingw32_HOST_OS)
852 -- Assuming we are running ghc, accessed by path $()/bin/ghc.exe,
853 -- return the path $(stuff). Note that we drop the "bin/" directory too.
854 getBaseDir = do let len = (2048::Int) -- plenty, PATH_MAX is 512 under Win32.
855 buf <- mallocArray len
856 ret <- getModuleFileName nullPtr buf len
857 if ret == 0 then free buf >> return Nothing
858 else do s <- peekCString buf
860 return (Just (rootDir s))
862 rootDir s = case splitFileName $ normalise s of
864 case splitFileName $ takeDirectory d of
865 (d', "bin") -> takeDirectory d'
866 _ -> panic ("Expected \"bin\" in " ++ show s)
867 _ -> panic ("Expected \"ghc.exe\" in " ++ show s)
869 foreign import stdcall unsafe "GetModuleFileNameA"
870 getModuleFileName :: Ptr () -> CString -> Int -> IO Int32
872 getBaseDir = return Nothing
875 #ifdef mingw32_HOST_OS
876 foreign import ccall unsafe "_getpid" getProcessID :: IO Int -- relies on Int == Int32 on Windows
878 getProcessID :: IO Int
879 getProcessID = System.Posix.Internals.c_getpid >>= return . fromIntegral
882 -- Divvy up text stream into lines, taking platform dependent
883 -- line termination into account.
884 linesPlatform :: String -> [String]
885 #if !defined(mingw32_HOST_OS)
886 linesPlatform ls = lines ls
888 linesPlatform "" = []
891 (as,xs1) -> as : linesPlatform xs1
893 lineBreak "" = ("","")
894 lineBreak ('\r':'\n':xs) = ([],xs)
895 lineBreak ('\n':xs) = ([],xs)
896 lineBreak (x:xs) = let (as,bs) = lineBreak xs in (x:as,bs)