1 -----------------------------------------------------------------------------
3 -- (c) The University of Glasgow 2001-2003
5 -- Access to system tools: gcc, cp, rm etc
7 -----------------------------------------------------------------------------
10 {-# OPTIONS -fno-warn-unused-do-bind #-}
15 -- Interface to system tools
16 runUnlit, runCpp, runCc, -- [Option] -> IO ()
17 runPp, -- [Option] -> IO ()
18 runSplit, -- [Option] -> IO ()
19 runAs, runLink, -- [Option] -> IO ()
27 touch, -- String -> String -> IO ()
31 -- Temporary-file management
34 cleanTempDirs, cleanTempFiles, cleanTempFilesExcept,
41 #include "HsVersions.h"
56 import System.Environment
57 import System.FilePath
59 import System.IO.Error as IO
60 import System.Directory
62 import Data.Maybe ( isNothing )
64 import qualified Data.Map as Map
65 import Text.ParserCombinators.ReadP hiding (char)
66 import qualified Text.ParserCombinators.ReadP as R
68 #ifndef mingw32_HOST_OS
69 import qualified System.Posix.Internals
70 #else /* Must be Win32 */
72 import Foreign.C.String
76 import Control.Concurrent
78 import SrcLoc ( SrcLoc, mkSrcLoc, noSrcSpan, mkSrcSpan )
81 How GHC finds its files
82 ~~~~~~~~~~~~~~~~~~~~~~~
86 GHC needs various support files (library packages, RTS etc), plus
87 various auxiliary programs (cp, gcc, etc). It starts by finding topdir,
88 the root of GHC's support files
91 - ghc always has a shell wrapper that passes a -B<dir> option
94 - ghc never has a shell wrapper.
95 - we can find the location of the ghc binary, which is
96 $topdir/bin/<something>.exe
97 where <something> may be "ghc", "ghc-stage2", or similar
98 - we strip off the "bin/<something>.exe" to leave $topdir.
100 from topdir we can find package.conf, ghc-asm, etc.
103 SysTools.initSysProgs figures out exactly where all the auxiliary programs
104 are, and initialises mutable variables to make it easy to call them.
105 To to this, it makes use of definitions in Config.hs, which is a Haskell
106 file containing variables whose value is figured out by the build system.
108 Config.hs contains two sorts of things
110 cGCC, The *names* of the programs
113 etc They do *not* include paths
116 cUNLIT_DIR The *path* to the directory containing unlit, split etc
117 cSPLIT_DIR *relative* to the root of the build tree,
118 for use when running *in-place* in a build tree (only)
122 ---------------------------------------------
123 NOTES for an ALTERNATIVE scheme (i.e *not* what is currently implemented):
125 Another hair-brained scheme for simplifying the current tool location
126 nightmare in GHC: Simon originally suggested using another
127 configuration file along the lines of GCC's specs file - which is fine
128 except that it means adding code to read yet another configuration
129 file. What I didn't notice is that the current package.conf is
130 general enough to do this:
133 {name = "tools", import_dirs = [], source_dirs = [],
134 library_dirs = [], hs_libraries = [], extra_libraries = [],
135 include_dirs = [], c_includes = [], package_deps = [],
136 extra_ghc_opts = ["-pgmc/usr/bin/gcc","-pgml${topdir}/bin/unlit", ... etc.],
137 extra_cc_opts = [], extra_ld_opts = []}
139 Which would have the advantage that we get to collect together in one
140 place the path-specific package stuff with the path-specific tool
143 ---------------------------------------------
145 %************************************************************************
147 \subsection{Initialisation}
149 %************************************************************************
152 initSysTools :: Maybe String -- Maybe TopDir path (without the '-B' prefix)
153 -> IO Settings -- Set all the mutable variables above, holding
154 -- (a) the system programs
155 -- (b) the package-config file
156 -- (c) the GHC usage message
157 initSysTools mbMinusB
158 = do { top_dir <- findTopDir mbMinusB
160 -- NB: top_dir is assumed to be in standard Unix
161 -- format, '/' separated
163 ; let settingsFile = top_dir </> "settings"
164 installed :: FilePath -> FilePath
165 installed file = top_dir </> file
166 installed_mingw_bin file = top_dir </> ".." </> "mingw" </> "bin" </> file
167 installed_perl_bin file = top_dir </> ".." </> "perl" </> file
169 ; settingsStr <- readFile settingsFile
170 ; mySettings <- case maybeReadFuzzy settingsStr of
174 pgmError ("Can't parse " ++ show settingsFile)
175 ; let getSetting key = case lookup key mySettings of
178 Nothing -> pgmError ("No entry for " ++ show key ++ " in " ++ show settingsFile)
179 ; myExtraGccViaCFlags <- getSetting "GCC extra via C opts"
180 -- On Windows, mingw is distributed with GHC,
181 -- so we look in TopDir/../mingw/bin
182 -- It would perhaps be nice to be able to override this
183 -- with the settings file, but it would be a little fiddly
184 -- to make that possible, so for now you can't.
185 ; gcc_prog <- if isWindowsHost then return $ installed_mingw_bin "gcc"
186 else getSetting "C compiler command"
187 ; gcc_args_str <- if isWindowsHost then return []
188 else getSetting "C compiler flags"
189 ; let gcc_args = map Option (words gcc_args_str)
190 ; perl_path <- if isWindowsHost
191 then return $ installed_perl_bin "perl"
192 else getSetting "perl command"
194 ; let pkgconfig_path = installed "package.conf.d"
195 ghc_usage_msg_path = installed "ghc-usage.txt"
196 ghci_usage_msg_path = installed "ghci-usage.txt"
198 -- For all systems, unlit, split, mangle are GHC utilities
199 -- architecture-specific stuff is done when building Config.hs
200 unlit_path = installed cGHC_UNLIT_PGM
202 -- split is a Perl script
203 split_script = installed cGHC_SPLIT_PGM
205 windres_path = installed_mingw_bin "windres"
207 ; tmpdir <- getTemporaryDirectory
210 -- 'touch' is a GHC util for Windows
212 | isWindowsHost = installed cGHC_TOUCHY_PGM
213 | otherwise = "touch"
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.
216 -- On Unix, scripts are invoked using the '#!' method. Binary
217 -- installations of GHC on Unix place the correct line on the
218 -- front of the script at installation time, so we don't want
219 -- to wire-in our knowledge of $(PERL) on the host system here.
220 (split_prog, split_args)
221 | isWindowsHost = (perl_path, [Option split_script])
222 | otherwise = (split_script, [])
223 (mkdll_prog, mkdll_args)
225 = panic "Can't build DLLs on a non-Win32 system"
227 (installed_mingw_bin cMKDLL, [])
229 -- cpp is derived from gcc on all platforms
230 -- HACK, see setPgmP below. We keep 'words' here to remember to fix
231 -- Config.hs one day.
232 ; let cpp_prog = gcc_prog
233 cpp_args = Option "-E"
234 : map Option (words cRAWCPP_FLAGS)
237 -- Other things being equal, as and ld are simply gcc
238 ; let as_prog = gcc_prog
243 -- We just assume on command line
244 ; let lc_prog = "llc"
247 ; return $ Settings {
248 sTmpDir = normalise tmpdir,
249 sGhcUsagePath = ghc_usage_msg_path,
250 sGhciUsagePath = ghci_usage_msg_path,
252 sRawSettings = mySettings,
253 sExtraGccViaCFlags = words myExtraGccViaCFlags,
254 sSystemPackageConfig = pkgconfig_path,
256 sPgm_P = (cpp_prog, cpp_args),
258 sPgm_c = (gcc_prog, gcc_args),
259 sPgm_s = (split_prog,split_args),
260 sPgm_a = (as_prog, as_args),
261 sPgm_l = (ld_prog, ld_args),
262 sPgm_dll = (mkdll_prog,mkdll_args),
264 sPgm_sysman = top_dir ++ "/ghc/rts/parallel/SysMan",
265 sPgm_windres = windres_path,
266 sPgm_lo = (lo_prog,[]),
267 sPgm_lc = (lc_prog,[]),
268 -- Hans: this isn't right in general, but you can
269 -- elaborate it in the same way as the others
272 then -- this list gets reversed
273 ["-D__PIC__", "-U __PIC__"]
288 -- returns a Unix-format path (relying on getBaseDir to do so too)
289 findTopDir :: Maybe String -- Maybe TopDir path (without the '-B' prefix).
290 -> IO String -- TopDir (in Unix format '/' separated)
291 findTopDir (Just minusb) = return (normalise minusb)
293 = do -- Get directory of executable
294 maybe_exec_dir <- getBaseDir
295 case maybe_exec_dir of
296 -- "Just" on Windows, "Nothing" on unix
297 Nothing -> ghcError (InstallationError "missing -B<dir> option")
298 Just dir -> return dir
302 %************************************************************************
304 \subsection{Running an external program}
306 %************************************************************************
310 runUnlit :: DynFlags -> [Option] -> IO ()
311 runUnlit dflags args = do
313 runSomething dflags "Literate pre-processor" p args
315 runCpp :: DynFlags -> [Option] -> IO ()
316 runCpp dflags args = do
317 let (p,args0) = pgm_P dflags
318 args1 = args0 ++ args
319 args2 = if dopt Opt_WarnIsError dflags
320 then Option "-Werror" : args1
322 mb_env <- getGccEnv args2
323 runSomethingFiltered dflags id "C pre-processor" p args2 mb_env
325 runPp :: DynFlags -> [Option] -> IO ()
326 runPp dflags args = do
328 runSomething dflags "Haskell pre-processor" p args
330 runCc :: DynFlags -> [Option] -> IO ()
331 runCc dflags args = do
332 let (p,args0) = pgm_c dflags
333 args1 = args0 ++ args
334 mb_env <- getGccEnv args1
335 runSomethingFiltered dflags cc_filter "C Compiler" p args1 mb_env
337 -- discard some harmless warnings from gcc that we can't turn off
338 cc_filter = unlines . doFilter . lines
341 gcc gives warnings in chunks like so:
342 In file included from /foo/bar/baz.h:11,
343 from /foo/bar/baz2.h:22,
345 /foo/flibble:14: global register variable ...
346 /foo/flibble:15: warning: call-clobbered r...
347 We break it up into its chunks, remove any call-clobbered register
348 warnings from each chunk, and then delete any chunks that we have
351 doFilter = unChunkWarnings . filterWarnings . chunkWarnings []
352 -- We can't assume that the output will start with an "In file inc..."
353 -- line, so we start off expecting a list of warnings rather than a
355 chunkWarnings :: [String] -- The location stack to use for the next
357 -> [String] -- The remaining lines to look at
358 -> [([String], [String])]
359 chunkWarnings loc_stack [] = [(loc_stack, [])]
360 chunkWarnings loc_stack xs
361 = case break loc_stack_start xs of
362 (warnings, lss:xs') ->
363 case span loc_start_continuation xs' of
365 (loc_stack, warnings) : chunkWarnings (lss : lsc) xs''
366 _ -> [(loc_stack, xs)]
368 filterWarnings :: [([String], [String])] -> [([String], [String])]
369 filterWarnings [] = []
370 -- If the warnings are already empty then we are probably doing
371 -- something wrong, so don't delete anything
372 filterWarnings ((xs, []) : zs) = (xs, []) : filterWarnings zs
373 filterWarnings ((xs, ys) : zs) = case filter wantedWarning ys of
374 [] -> filterWarnings zs
375 ys' -> (xs, ys') : filterWarnings zs
377 unChunkWarnings :: [([String], [String])] -> [String]
378 unChunkWarnings [] = []
379 unChunkWarnings ((xs, ys) : zs) = xs ++ ys ++ unChunkWarnings zs
381 loc_stack_start s = "In file included from " `isPrefixOf` s
382 loc_start_continuation s = " from " `isPrefixOf` s
384 | "warning: call-clobbered register used" `isContainedIn` w = False
387 isContainedIn :: String -> String -> Bool
388 xs `isContainedIn` ys = any (xs `isPrefixOf`) (tails ys)
390 -- If the -B<dir> option is set, add <dir> to PATH. This works around
391 -- a bug in gcc on Windows Vista where it can't find its auxiliary
392 -- binaries (see bug #1110).
393 getGccEnv :: [Option] -> IO (Maybe [(String,String)])
397 else do env <- getEnvironment
398 return (Just (map mangle_path env))
400 (b_dirs, _) = partitionWith get_b_opt opts
402 get_b_opt (Option ('-':'B':dir)) = Left dir
403 get_b_opt other = Right other
405 mangle_path (path,paths) | map toUpper path == "PATH"
406 = (path, '\"' : head b_dirs ++ "\";" ++ paths)
407 mangle_path other = other
409 runSplit :: DynFlags -> [Option] -> IO ()
410 runSplit dflags args = do
411 let (p,args0) = pgm_s dflags
412 runSomething dflags "Splitter" p (args0++args)
414 runAs :: DynFlags -> [Option] -> IO ()
415 runAs dflags args = do
416 let (p,args0) = pgm_a dflags
417 args1 = args0 ++ args
418 mb_env <- getGccEnv args1
419 runSomethingFiltered dflags id "Assembler" p args1 mb_env
421 -- | Run the LLVM Optimiser
422 runLlvmOpt :: DynFlags -> [Option] -> IO ()
423 runLlvmOpt dflags args = do
424 let (p,args0) = pgm_lo dflags
425 runSomething dflags "LLVM Optimiser" p (args0++args)
427 -- | Run the LLVM Compiler
428 runLlvmLlc :: DynFlags -> [Option] -> IO ()
429 runLlvmLlc dflags args = do
430 let (p,args0) = pgm_lc dflags
431 runSomething dflags "LLVM Compiler" p (args0++args)
433 -- | Figure out which version of LLVM we are running this session
434 figureLlvmVersion :: DynFlags -> IO (Maybe Int)
435 figureLlvmVersion dflags = do
436 let (pgm,opts) = pgm_lc dflags
437 args = filter notNull (map showOpt opts)
438 -- we grab the args even though they should be useless just in
439 -- case the user is using a customised 'llc' that requires some
440 -- of the options they've specified. llc doesn't care what other
441 -- options are specified when '-version' is used.
442 args' = args ++ ["-version"]
444 (pin, pout, perr, _) <- runInteractiveProcess pgm args'
447 Low Level Virtual Machine (http://llvm.org/):
448 llvm version 2.8 (Ubuntu 2.8-0Ubuntu1)
451 hSetBinaryMode pout False
453 vline <- hGetLine pout
454 v <- case filter isDigit vline of
455 [] -> fail "no digits!"
456 [x] -> fail $ "only 1 digit! (" ++ show x ++ ")"
457 (x:y:_) -> return ((read [x,y]) :: Int)
464 putMsg dflags $ text $ "Warning: " ++ show err
469 runLink :: DynFlags -> [Option] -> IO ()
470 runLink dflags args = do
471 let (p,args0) = pgm_l dflags
472 args1 = args0 ++ args
473 mb_env <- getGccEnv args1
474 runSomethingFiltered dflags id "Linker" p args1 mb_env
476 runMkDLL :: DynFlags -> [Option] -> IO ()
477 runMkDLL dflags args = do
478 let (p,args0) = pgm_dll dflags
479 args1 = args0 ++ args
480 mb_env <- getGccEnv (args0++args)
481 runSomethingFiltered dflags id "Make DLL" p args1 mb_env
483 runWindres :: DynFlags -> [Option] -> IO ()
484 runWindres dflags args = do
485 let (gcc, gcc_args) = pgm_c dflags
486 windres = pgm_windres dflags
487 quote x = "\"" ++ x ++ "\""
488 args' = -- If windres.exe and gcc.exe are in a directory containing
489 -- spaces then windres fails to run gcc. We therefore need
490 -- to tell it what command to use...
491 Option ("--preprocessor=" ++
492 unwords (map quote (gcc :
493 map showOpt gcc_args ++
494 ["-E", "-xc", "-DRC_INVOKED"])))
495 -- ...but if we do that then if windres calls popen then
496 -- it can't understand the quoting, so we have to use
497 -- --use-temp-file so that it interprets it correctly.
499 : Option "--use-temp-file"
501 mb_env <- getGccEnv gcc_args
502 runSomethingFiltered dflags id "Windres" windres args' mb_env
504 touch :: DynFlags -> String -> String -> IO ()
505 touch dflags purpose arg =
506 runSomething dflags purpose (pgm_T dflags) [FileOption "" arg]
508 copy :: DynFlags -> String -> FilePath -> FilePath -> IO ()
509 copy dflags purpose from to = copyWithHeader dflags purpose Nothing from to
511 copyWithHeader :: DynFlags -> String -> Maybe String -> FilePath -> FilePath
513 copyWithHeader dflags purpose maybe_header from to = do
514 showPass dflags purpose
516 hout <- openBinaryFile to WriteMode
517 hin <- openBinaryFile from ReadMode
518 ls <- hGetContents hin -- inefficient, but it'll do for now. ToDo: speed up
519 maybe (return ()) (hPutStr hout) maybe_header
524 -- | read the contents of the named section in an ELF object as a
526 readElfSection :: DynFlags -> String -> FilePath -> IO (Maybe String)
527 readElfSection _dflags section exe = do
530 args = [Option "-p", Option section, FileOption "" exe]
532 r <- readProcessWithExitCode prog (filter notNull (map showOpt args)) ""
534 (ExitSuccess, out, _err) -> return (doFilter (lines out))
537 doFilter [] = Nothing
538 doFilter (s:r) = case readP_to_S parse s of
542 skipSpaces; R.char '['; skipSpaces; string "0]"; skipSpaces;
546 %************************************************************************
548 \subsection{Managing temporary files
550 %************************************************************************
553 cleanTempDirs :: DynFlags -> IO ()
555 = unless (dopt Opt_KeepTmpFiles dflags)
556 $ do let ref = dirsToClean dflags
558 removeTmpDirs dflags (Map.elems ds)
559 writeIORef ref Map.empty
561 cleanTempFiles :: DynFlags -> IO ()
562 cleanTempFiles dflags
563 = unless (dopt Opt_KeepTmpFiles dflags)
564 $ do let ref = filesToClean dflags
566 removeTmpFiles dflags fs
569 cleanTempFilesExcept :: DynFlags -> [FilePath] -> IO ()
570 cleanTempFilesExcept dflags dont_delete
571 = unless (dopt Opt_KeepTmpFiles dflags)
572 $ do let ref = filesToClean dflags
573 files <- readIORef ref
574 let (to_keep, to_delete) = partition (`elem` dont_delete) files
575 writeIORef ref to_keep
576 removeTmpFiles dflags to_delete
579 -- find a temporary name that doesn't already exist.
580 newTempName :: DynFlags -> Suffix -> IO FilePath
581 newTempName dflags extn
582 = do d <- getTempDir dflags
584 findTempName (d </> "ghc" ++ show x ++ "_") 0
586 findTempName :: FilePath -> Integer -> IO FilePath
587 findTempName prefix x
588 = do let filename = (prefix ++ show x) <.> extn
589 b <- doesFileExist filename
590 if b then findTempName prefix (x+1)
591 else do -- clean it up later
592 consIORef (filesToClean dflags) filename
595 -- return our temporary directory within tmp_dir, creating one if we
596 -- don't have one yet
597 getTempDir :: DynFlags -> IO FilePath
599 = do let ref = dirsToClean dflags
600 tmp_dir = tmpDir dflags
601 mapping <- readIORef ref
602 case Map.lookup tmp_dir mapping of
605 let prefix = tmp_dir </> "ghc" ++ show x ++ "_"
607 mkTempDir :: Integer -> IO FilePath
609 = let dirname = prefix ++ show x
610 in do createDirectory dirname
611 let mapping' = Map.insert tmp_dir dirname mapping
612 writeIORef ref mapping'
613 debugTraceMsg dflags 2 (ptext (sLit "Created temporary directory:") <+> text dirname)
616 if isAlreadyExistsError e
622 addFilesToClean :: DynFlags -> [FilePath] -> IO ()
623 -- May include wildcards [used by DriverPipeline.run_phase SplitMangle]
624 addFilesToClean dflags files = mapM_ (consIORef (filesToClean dflags)) files
626 removeTmpDirs :: DynFlags -> [FilePath] -> IO ()
627 removeTmpDirs dflags ds
628 = traceCmd dflags "Deleting temp dirs"
629 ("Deleting: " ++ unwords ds)
630 (mapM_ (removeWith dflags removeDirectory) ds)
632 removeTmpFiles :: DynFlags -> [FilePath] -> IO ()
633 removeTmpFiles dflags fs
635 traceCmd dflags "Deleting temp files"
636 ("Deleting: " ++ unwords deletees)
637 (mapM_ (removeWith dflags removeFile) deletees)
639 -- Flat out refuse to delete files that are likely to be source input
640 -- files (is there a worse bug than having a compiler delete your source
643 -- Deleting source files is a sign of a bug elsewhere, so prominently flag
646 | null non_deletees = act
648 putMsg dflags (text "WARNING - NOT deleting source files:" <+> hsep (map text non_deletees))
651 (non_deletees, deletees) = partition isHaskellUserSrcFilename fs
653 removeWith :: DynFlags -> (FilePath -> IO ()) -> FilePath -> IO ()
654 removeWith dflags remover f = remover f `catchIO`
656 let msg = if isDoesNotExistError e
657 then ptext (sLit "Warning: deleting non-existent") <+> text f
658 else ptext (sLit "Warning: exception raised when deleting")
661 in debugTraceMsg dflags 2 msg
664 -----------------------------------------------------------------------------
665 -- Running an external program
667 runSomething :: DynFlags
668 -> String -- For -v message
669 -> String -- Command name (possibly a full path)
670 -- assumed already dos-ified
671 -> [Option] -- Arguments
672 -- runSomething will dos-ify them
675 runSomething dflags phase_name pgm args =
676 runSomethingFiltered dflags id phase_name pgm args Nothing
679 :: DynFlags -> (String->String) -> String -> String -> [Option]
680 -> Maybe [(String,String)] -> IO ()
682 runSomethingFiltered dflags filter_fn phase_name pgm args mb_env = do
683 let real_args = filter notNull (map showOpt args)
684 #if __GLASGOW_HASKELL__ >= 701
685 cmdLine = showCommandForUser pgm real_args
687 cmdLine = unwords (pgm:real_args)
689 traceCmd dflags phase_name cmdLine $ do
690 (exit_code, doesn'tExist) <-
692 rc <- builderMainLoop dflags filter_fn pgm real_args mb_env
694 ExitSuccess{} -> return (rc, False)
696 -- rawSystem returns (ExitFailure 127) if the exec failed for any
697 -- reason (eg. the program doesn't exist). This is the only clue
698 -- we have, but we need to report something to the user because in
699 -- the case of a missing program there will otherwise be no output
701 | n == 127 -> return (rc, True)
702 | otherwise -> return (rc, False))
703 -- Should 'rawSystem' generate an IO exception indicating that
704 -- 'pgm' couldn't be run rather than a funky return code, catch
705 -- this here (the win32 version does this, but it doesn't hurt
706 -- to test for this in general.)
708 if IO.isDoesNotExistError err
709 then return (ExitFailure 1, True)
711 case (doesn'tExist, exit_code) of
712 (True, _) -> ghcError (InstallationError ("could not execute: " ++ pgm))
713 (_, ExitSuccess) -> return ()
714 _ -> ghcError (PhaseFailed phase_name exit_code)
716 builderMainLoop :: DynFlags -> (String -> String) -> FilePath
717 -> [String] -> Maybe [(String, String)]
719 builderMainLoop dflags filter_fn pgm real_args mb_env = do
721 (hStdIn, hStdOut, hStdErr, hProcess) <- runInteractiveProcess pgm real_args Nothing mb_env
723 -- and run a loop piping the output from the compiler to the log_action in DynFlags
724 hSetBuffering hStdOut LineBuffering
725 hSetBuffering hStdErr LineBuffering
726 _ <- forkIO (readerProc chan hStdOut filter_fn)
727 _ <- forkIO (readerProc chan hStdErr filter_fn)
728 -- we don't want to finish until 2 streams have been completed
729 -- (stdout and stderr)
730 -- nor until 1 exit code has been retrieved.
731 rc <- loop chan hProcess (2::Integer) (1::Integer) ExitSuccess
732 -- after that, we're done here.
738 -- status starts at zero, and increments each time either
739 -- a reader process gets EOF, or the build proc exits. We wait
740 -- for all of these to happen (status==3).
741 -- ToDo: we should really have a contingency plan in case any of
742 -- the threads dies, such as a timeout.
743 loop _ _ 0 0 exitcode = return exitcode
744 loop chan hProcess t p exitcode = do
746 then getProcessExitCode hProcess
749 Just code -> loop chan hProcess t (p-1) code
755 log_action dflags SevInfo noSrcSpan defaultUserStyle msg
756 loop chan hProcess t p exitcode
757 BuildError loc msg -> do
758 log_action dflags SevError (mkSrcSpan loc loc) defaultUserStyle msg
759 loop chan hProcess t p exitcode
761 loop chan hProcess (t-1) p exitcode
762 | otherwise -> loop chan hProcess t p exitcode
764 readerProc :: Chan BuildMessage -> Handle -> (String -> String) -> IO ()
765 readerProc chan hdl filter_fn =
766 (do str <- hGetContents hdl
767 loop (linesPlatform (filter_fn str)) Nothing)
770 -- ToDo: check errors more carefully
771 -- ToDo: in the future, the filter should be implemented as
772 -- a stream transformer.
774 loop [] Nothing = return ()
775 loop [] (Just err) = writeChan chan err
778 Just err@(BuildError srcLoc msg)
779 | leading_whitespace l -> do
780 loop ls (Just (BuildError srcLoc (msg $$ text l)))
786 _ -> panic "readerProc/loop"
789 = case parseError l of
791 writeChan chan (BuildMsg (text l))
793 Just (file, lineNum, colNum, msg) -> do
794 let srcLoc = mkSrcLoc (mkFastString file) lineNum colNum
795 loop ls (Just (BuildError srcLoc (text msg)))
797 leading_whitespace [] = False
798 leading_whitespace (x:_) = isSpace x
800 parseError :: String -> Maybe (String, Int, Int, String)
801 parseError s0 = case breakColon s0 of
802 Just (filename, s1) ->
803 case breakIntColon s1 of
804 Just (lineNum, s2) ->
805 case breakIntColon s2 of
806 Just (columnNum, s3) ->
807 Just (filename, lineNum, columnNum, s3)
809 Just (filename, lineNum, 0, s2)
813 breakColon :: String -> Maybe (String, String)
814 breakColon xs = case break (':' ==) xs of
815 (ys, _:zs) -> Just (ys, zs)
818 breakIntColon :: String -> Maybe (Int, String)
819 breakIntColon xs = case break (':' ==) xs of
821 | not (null ys) && all isAscii ys && all isDigit ys ->
827 | BuildError !SrcLoc !SDoc
830 traceCmd :: DynFlags -> String -> String -> IO () -> IO ()
831 -- trace the command (at two levels of verbosity)
832 traceCmd dflags phase_name cmd_line action
833 = do { let verb = verbosity dflags
834 ; showPass dflags phase_name
835 ; debugTraceMsg dflags 3 (text cmd_line)
839 ; action `catchIO` handle_exn verb
842 handle_exn _verb exn = do { debugTraceMsg dflags 2 (char '\n')
843 ; debugTraceMsg dflags 2 (ptext (sLit "Failed:") <+> text cmd_line <+> text (show exn))
844 ; ghcError (PhaseFailed phase_name (ExitFailure 1)) }
847 %************************************************************************
849 \subsection{Support code}
851 %************************************************************************
854 -----------------------------------------------------------------------------
855 -- Define getBaseDir :: IO (Maybe String)
857 getBaseDir :: IO (Maybe String)
858 #if defined(mingw32_HOST_OS)
859 -- Assuming we are running ghc, accessed by path $(stuff)/bin/ghc.exe,
860 -- return the path $(stuff)/lib.
861 getBaseDir = try_size 2048 -- plenty, PATH_MAX is 512 under Win32.
863 try_size size = allocaArray (fromIntegral size) $ \buf -> do
864 ret <- c_GetModuleFileName nullPtr buf size
867 _ | ret < size -> fmap (Just . rootDir) $ peekCWString buf
868 | otherwise -> try_size (size * 2)
870 rootDir s = case splitFileName $ normalise s of
872 | lower ghc_exe `elem` ["ghc.exe",
876 case splitFileName $ takeDirectory d of
877 -- ghc is in $topdir/bin/ghc.exe
878 (d', bin) | lower bin == "bin" -> takeDirectory d' </> "lib"
881 where fail = panic ("can't decompose ghc.exe path: " ++ show s)
884 foreign import stdcall unsafe "windows.h GetModuleFileNameW"
885 c_GetModuleFileName :: Ptr () -> CWString -> Word32 -> IO Word32
887 getBaseDir = return Nothing
890 #ifdef mingw32_HOST_OS
891 foreign import ccall unsafe "_getpid" getProcessID :: IO Int -- relies on Int == Int32 on Windows
893 getProcessID :: IO Int
894 getProcessID = System.Posix.Internals.c_getpid >>= return . fromIntegral
897 -- Divvy up text stream into lines, taking platform dependent
898 -- line termination into account.
899 linesPlatform :: String -> [String]
900 #if !defined(mingw32_HOST_OS)
901 linesPlatform ls = lines ls
903 linesPlatform "" = []
906 (as,xs1) -> as : linesPlatform xs1
908 lineBreak "" = ("","")
909 lineBreak ('\r':'\n':xs) = ([],xs)
910 lineBreak ('\n':xs) = ([],xs)
911 lineBreak (x:xs) = let (as,bs) = lineBreak xs in (x:as,bs)