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 ()
21 touch, -- String -> String -> IO ()
22 copy, -- String -> String -> String -> IO ()
23 normalisePath, -- FilePath -> FilePath
25 -- Temporary-file management
28 cleanTempDirs, cleanTempFiles, cleanTempFilesExcept,
32 system, -- String -> IO ExitCode
38 #include "HsVersions.h"
40 import DriverPhases ( isHaskellUserSrcFilename )
43 import ErrUtils ( putMsg, debugTraceMsg, showPass, Severity(..), Messages )
44 import Panic ( GhcException(..) )
45 import Util ( Suffix, global, notNull, consIORef, joinFileName,
46 normalisePath, pgmPath, platformPath, joinFileExt )
47 import DynFlags ( DynFlags(..), DynFlag(..), dopt, Option(..),
48 setTmpDir, defaultDynFlags )
50 import EXCEPTION ( throwDyn, finally )
51 import DATA_IOREF ( IORef, readIORef, writeIORef )
54 import Monad ( when, unless )
55 import System ( ExitCode(..), getEnv, system )
56 import IO ( try, catch, hGetContents,
57 openFile, hPutStr, hClose, hFlush, IOMode(..),
58 stderr, ioError, isDoesNotExistError,
59 isAlreadyExistsError )
60 import Directory ( doesFileExist, removeFile,
61 createDirectory, removeDirectory )
62 import Maybe ( isJust )
63 import List ( partition )
64 import FiniteMap ( FiniteMap, emptyFM, lookupFM, addToFM, eltsFM )
66 -- GHC <= 4.08 didn't have rawSystem, and runs into problems with long command
67 -- lines on mingw32, so we disallow it now.
68 #if __GLASGOW_HASKELL__ < 500
69 #error GHC >= 5.00 is required for bootstrapping GHC
72 #ifndef mingw32_HOST_OS
73 #if __GLASGOW_HASKELL__ > 504
74 import qualified System.Posix.Internals
76 import qualified Posix
78 #else /* Must be Win32 */
79 import List ( isPrefixOf )
80 import Util ( dropList )
82 import CString ( CString, peekCString )
87 #if __GLASGOW_HASKELL__ < 603
88 -- rawSystem comes from libghccompat.a in stage1
89 import Compat.RawSystem ( rawSystem )
90 import GHC.IOBase ( IOErrorType(..) )
91 import System.IO.Error ( ioeGetErrorType )
93 import System.Process ( runInteractiveProcess, getProcessExitCode )
94 import System.IO ( hSetBuffering, hGetLine, BufferMode(..) )
95 import Control.Concurrent( forkIO, newChan, readChan, writeChan )
96 import Data.Char ( isSpace )
97 import FastString ( mkFastString )
98 import SrcLoc ( SrcLoc, mkSrcLoc, noSrcSpan, mkSrcSpan )
103 The configuration story
104 ~~~~~~~~~~~~~~~~~~~~~~~
106 GHC needs various support files (library packages, RTS etc), plus
107 various auxiliary programs (cp, gcc, etc). It finds these in one
110 * When running as an *installed program*, GHC finds most of this support
111 stuff in the installed library tree. The path to this tree is passed
112 to GHC via the -B flag, and given to initSysTools .
114 * When running *in-place* in a build tree, GHC finds most of this support
115 stuff in the build tree. The path to the build tree is, again passed
118 GHC tells which of the two is the case by seeing whether package.conf
119 is in TopDir [installed] or in TopDir/ghc/driver [inplace] (what a hack).
122 SysTools.initSysProgs figures out exactly where all the auxiliary programs
123 are, and initialises mutable variables to make it easy to call them.
124 To to this, it makes use of definitions in Config.hs, which is a Haskell
125 file containing variables whose value is figured out by the build system.
127 Config.hs contains two sorts of things
129 cGCC, The *names* of the programs
132 etc They do *not* include paths
135 cUNLIT_DIR_REL The *path* to the directory containing unlit, split etc
136 cSPLIT_DIR_REL *relative* to the root of the build tree,
137 for use when running *in-place* in a build tree (only)
141 ---------------------------------------------
142 NOTES for an ALTERNATIVE scheme (i.e *not* what is currently implemented):
144 Another hair-brained scheme for simplifying the current tool location
145 nightmare in GHC: Simon originally suggested using another
146 configuration file along the lines of GCC's specs file - which is fine
147 except that it means adding code to read yet another configuration
148 file. What I didn't notice is that the current package.conf is
149 general enough to do this:
152 {name = "tools", import_dirs = [], source_dirs = [],
153 library_dirs = [], hs_libraries = [], extra_libraries = [],
154 include_dirs = [], c_includes = [], package_deps = [],
155 extra_ghc_opts = ["-pgmc/usr/bin/gcc","-pgml${topdir}/bin/unlit", ... etc.],
156 extra_cc_opts = [], extra_ld_opts = []}
158 Which would have the advantage that we get to collect together in one
159 place the path-specific package stuff with the path-specific tool
162 ---------------------------------------------
164 %************************************************************************
166 \subsection{Initialisation}
168 %************************************************************************
171 initSysTools :: Maybe String -- Maybe TopDir path (without the '-B' prefix)
174 -> IO DynFlags -- Set all the mutable variables above, holding
175 -- (a) the system programs
176 -- (b) the package-config file
177 -- (c) the GHC usage message
180 initSysTools mbMinusB dflags
181 = do { (am_installed, top_dir) <- findTopDir mbMinusB
183 -- for "installed" this is the root of GHC's support files
184 -- for "in-place" it is the root of the build tree
185 -- NB: top_dir is assumed to be in standard Unix
186 -- format, '/' separated
188 ; let installed, installed_bin :: FilePath -> FilePath
189 installed_bin pgm = pgmPath top_dir pgm
190 installed file = pgmPath top_dir file
191 inplace dir pgm = pgmPath (top_dir `joinFileName`
192 cPROJECT_DIR `joinFileName` dir) pgm
195 | am_installed = installed "package.conf"
196 | otherwise = inplace cGHC_DRIVER_DIR_REL "package.conf.inplace"
199 | am_installed = installed "ghc-usage.txt"
200 | otherwise = inplace cGHC_DRIVER_DIR_REL "ghc-usage.txt"
203 | am_installed = installed "ghci-usage.txt"
204 | otherwise = inplace cGHC_DRIVER_DIR_REL "ghci-usage.txt"
206 -- For all systems, unlit, split, mangle are GHC utilities
207 -- architecture-specific stuff is done when building Config.hs
209 | am_installed = installed_bin cGHC_UNLIT_PGM
210 | otherwise = inplace cGHC_UNLIT_DIR_REL cGHC_UNLIT_PGM
212 -- split and mangle are Perl scripts
214 | am_installed = installed_bin cGHC_SPLIT_PGM
215 | otherwise = inplace cGHC_SPLIT_DIR_REL cGHC_SPLIT_PGM
218 | am_installed = installed_bin cGHC_MANGLER_PGM
219 | otherwise = inplace cGHC_MANGLER_DIR_REL cGHC_MANGLER_PGM
221 ; let dflags0 = defaultDynFlags
222 #ifndef mingw32_HOST_OS
223 -- check whether TMPDIR is set in the environment
224 ; e_tmpdir <- IO.try (getEnv "TMPDIR") -- fails if not set
226 -- On Win32, consult GetTempPath() for a temp dir.
227 -- => it first tries TMP, TEMP, then finally the
228 -- Windows directory(!). The directory is in short-path
232 let len = (2048::Int)
233 buf <- mallocArray len
234 ret <- getTempPath len buf
236 -- failed, consult TMPDIR.
244 ; let dflags1 = case e_tmpdir of
246 Right d -> setTmpDir d dflags0
248 -- Check that the package config exists
249 ; config_exists <- doesFileExist pkgconfig_path
250 ; when (not config_exists) $
251 throwDyn (InstallationError
252 ("Can't find package.conf as " ++ pkgconfig_path))
254 #if defined(mingw32_HOST_OS)
255 -- WINDOWS-SPECIFIC STUFF
256 -- On Windows, gcc and friends are distributed with GHC,
257 -- so when "installed" we look in TopDir/bin
258 -- When "in-place" we look wherever the build-time configure
260 -- When "install" we tell gcc where its specs file + exes are (-B)
261 -- and also some places to pick up include files. We need
262 -- to be careful to put all necessary exes in the -B place
263 -- (as, ld, cc1, etc) since if they don't get found there, gcc
264 -- then tries to run unadorned "as", "ld", etc, and will
265 -- pick up whatever happens to be lying around in the path,
266 -- possibly including those from a cygwin install on the target,
267 -- which is exactly what we're trying to avoid.
268 ; let gcc_b_arg = Option ("-B" ++ installed "gcc-lib/")
270 | am_installed = (installed_bin "gcc", [gcc_b_arg])
271 | otherwise = (cGCC, [])
272 -- The trailing "/" is absolutely essential; gcc seems
273 -- to construct file names simply by concatenating to
274 -- this -B path with no extra slash We use "/" rather
275 -- than "\\" because otherwise "\\\" is mangled
276 -- later on; although gcc_args are in NATIVE format,
278 -- (see comments with declarations of global variables)
280 -- The quotes round the -B argument are in case TopDir
283 perl_path | am_installed = installed_bin cGHC_PERL
284 | otherwise = cGHC_PERL
286 -- 'touch' is a GHC util for Windows, and similarly unlit, mangle
287 ; let touch_path | am_installed = installed_bin cGHC_TOUCHY_PGM
288 | otherwise = inplace cGHC_TOUCHY_DIR_REL cGHC_TOUCHY_PGM
290 -- On Win32 we don't want to rely on #!/bin/perl, so we prepend
291 -- a call to Perl to get the invocation of split and mangle
292 ; let (split_prog, split_args) = (perl_path, [Option split_script])
293 (mangle_prog, mangle_args) = (perl_path, [Option mangle_script])
295 ; let (mkdll_prog, mkdll_args)
297 (pgmPath (installed "gcc-lib/") cMKDLL,
298 [ Option "--dlltool-name",
299 Option (pgmPath (installed "gcc-lib/") "dlltool"),
300 Option "--driver-name",
301 Option gcc_prog, gcc_b_arg ])
302 | otherwise = (cMKDLL, [])
304 -- UNIX-SPECIFIC STUFF
305 -- On Unix, the "standard" tools are assumed to be
306 -- in the same place whether we are running "in-place" or "installed"
307 -- That place is wherever the build-time configure script found them.
308 ; let gcc_prog = cGCC
311 mkdll_prog = panic "Can't build DLLs on a non-Win32 system"
314 -- On Unix, scripts are invoked using the '#!' method. Binary
315 -- installations of GHC on Unix place the correct line on the front
316 -- of the script at installation time, so we don't want to wire-in
317 -- our knowledge of $(PERL) on the host system here.
318 ; let (split_prog, split_args) = (split_script, [])
319 (mangle_prog, mangle_args) = (mangle_script, [])
322 -- cpp is derived from gcc on all platforms
323 -- HACK, see setPgmP below. We keep 'words' here to remember to fix
324 -- Config.hs one day.
325 ; let cpp_path = (gcc_prog, gcc_args ++
326 (Option "-E"):(map Option (words cRAWCPP_FLAGS)))
328 -- For all systems, copy and remove are provided by the host
329 -- system; architecture-specific stuff is done when building Config.hs
330 ; let cp_path = cGHC_CP
332 -- Other things being equal, as and ld are simply gcc
333 ; let (as_prog,as_args) = (gcc_prog,gcc_args)
334 (ld_prog,ld_args) = (gcc_prog,gcc_args)
337 ghcUsagePath = ghc_usage_msg_path,
338 ghciUsagePath = ghci_usage_msg_path,
340 systemPackageConfig = pkgconfig_path,
344 pgm_c = (gcc_prog,gcc_args),
345 pgm_m = (mangle_prog,mangle_args),
346 pgm_s = (split_prog,split_args),
347 pgm_a = (as_prog,as_args),
348 pgm_l = (ld_prog,ld_args),
349 pgm_dll = (mkdll_prog,mkdll_args),
351 pgm_sysman = top_dir ++ "/ghc/rts/parallel/SysMan"
352 -- Hans: this isn't right in general, but you can
353 -- elaborate it in the same way as the others
357 #if defined(mingw32_HOST_OS)
358 foreign import stdcall unsafe "GetTempPathA" getTempPath :: Int -> CString -> IO Int32
364 -- for "installed" this is the root of GHC's support files
365 -- for "in-place" it is the root of the build tree
368 -- 1. Set proto_top_dir
369 -- if there is no given TopDir path, get the directory
370 -- where GHC is running (only on Windows)
372 -- 2. If package.conf exists in proto_top_dir, we are running
373 -- installed; and TopDir = proto_top_dir
375 -- 3. Otherwise we are running in-place, so
376 -- proto_top_dir will be /...stuff.../ghc/compiler
377 -- Set TopDir to /...stuff..., which is the root of the build tree
379 -- This is very gruesome indeed
381 findTopDir :: Maybe String -- Maybe TopDir path (without the '-B' prefix).
382 -> IO (Bool, -- True <=> am installed, False <=> in-place
383 String) -- TopDir (in Unix format '/' separated)
386 = do { top_dir <- get_proto
387 -- Discover whether we're running in a build tree or in an installation,
388 -- by looking for the package configuration file.
389 ; am_installed <- doesFileExist (top_dir `joinFileName` "package.conf")
391 ; return (am_installed, top_dir)
394 -- get_proto returns a Unix-format path (relying on getBaseDir to do so too)
395 get_proto = case mbMinusB of
396 Just minusb -> return (normalisePath minusb)
398 -> do maybe_exec_dir <- getBaseDir -- Get directory of executable
399 case maybe_exec_dir of -- (only works on Windows;
400 -- returns Nothing on Unix)
401 Nothing -> throwDyn (InstallationError "missing -B<dir> option")
402 Just dir -> return dir
406 %************************************************************************
408 \subsection{Running an external program}
410 %************************************************************************
414 runUnlit :: DynFlags -> [Option] -> IO ()
415 runUnlit dflags args = do
417 runSomething dflags "Literate pre-processor" p args
419 runCpp :: DynFlags -> [Option] -> IO ()
420 runCpp dflags args = do
421 let (p,args0) = pgm_P dflags
422 runSomething dflags "C pre-processor" p (args0 ++ args)
424 runPp :: DynFlags -> [Option] -> IO ()
425 runPp dflags args = do
427 runSomething dflags "Haskell pre-processor" p args
429 runCc :: DynFlags -> [Option] -> IO ()
430 runCc dflags args = do
431 let (p,args0) = pgm_c dflags
432 runSomethingFiltered dflags cc_filter "C Compiler" p (args0++args)
434 -- discard some harmless warnings from gcc that we can't turn off
435 cc_filter str = unlines (do_filter (lines str))
439 | (w:rest) <- dropWhile (isJust .matchRegex r_from) ls,
440 isJust (matchRegex r_warn w)
445 r_from = mkRegex "from.*:[0-9]+"
446 r_warn = mkRegex "warning: call-clobbered register used"
448 runMangle :: DynFlags -> [Option] -> IO ()
449 runMangle dflags args = do
450 let (p,args0) = pgm_m dflags
451 runSomething dflags "Mangler" p (args0++args)
453 runSplit :: DynFlags -> [Option] -> IO ()
454 runSplit dflags args = do
455 let (p,args0) = pgm_s dflags
456 runSomething dflags "Splitter" p (args0++args)
458 runAs :: DynFlags -> [Option] -> IO ()
459 runAs dflags args = do
460 let (p,args0) = pgm_a dflags
461 runSomething dflags "Assembler" p (args0++args)
463 runLink :: DynFlags -> [Option] -> IO ()
464 runLink dflags args = do
465 let (p,args0) = pgm_l dflags
466 runSomething dflags "Linker" p (args0++args)
468 runMkDLL :: DynFlags -> [Option] -> IO ()
469 runMkDLL dflags args = do
470 let (p,args0) = pgm_dll dflags
471 runSomething dflags "Make DLL" p (args0++args)
473 touch :: DynFlags -> String -> String -> IO ()
474 touch dflags purpose arg =
475 runSomething dflags purpose (pgm_T dflags) [FileOption "" arg]
477 copy :: DynFlags -> String -> String -> String -> IO ()
478 copy dflags purpose from to = do
479 showPass dflags purpose
481 h <- openFile to WriteMode
482 ls <- readFile from -- inefficient, but it'll do for now.
483 -- ToDo: speed up via slurping.
488 %************************************************************************
490 \subsection{Managing temporary files
492 %************************************************************************
495 GLOBAL_VAR(v_FilesToClean, [], [String] )
496 GLOBAL_VAR(v_DirsToClean, emptyFM, FiniteMap FilePath FilePath )
500 cleanTempDirs :: DynFlags -> IO ()
502 = do ds <- readIORef v_DirsToClean
503 removeTmpDirs dflags (eltsFM ds)
504 writeIORef v_DirsToClean emptyFM
506 cleanTempFiles :: DynFlags -> IO ()
507 cleanTempFiles dflags
508 = do fs <- readIORef v_FilesToClean
509 removeTmpFiles dflags fs
510 writeIORef v_FilesToClean []
512 cleanTempFilesExcept :: DynFlags -> [FilePath] -> IO ()
513 cleanTempFilesExcept dflags dont_delete
514 = do files <- readIORef v_FilesToClean
515 let (to_keep, to_delete) = partition (`elem` dont_delete) files
516 removeTmpFiles dflags to_delete
517 writeIORef v_FilesToClean to_keep
520 -- find a temporary name that doesn't already exist.
521 newTempName :: DynFlags -> Suffix -> IO FilePath
522 newTempName dflags extn
523 = do d <- getTempDir dflags
525 findTempName (d ++ "/ghc" ++ show x ++ "_") 0
527 findTempName prefix x
528 = do let filename = (prefix ++ show x) `joinFileExt` extn
529 b <- doesFileExist filename
530 if b then findTempName prefix (x+1)
531 else do consIORef v_FilesToClean filename -- clean it up later
534 -- return our temporary directory within tmp_dir, creating one if we
535 -- don't have one yet
536 getTempDir :: DynFlags -> IO FilePath
537 getTempDir dflags@(DynFlags{tmpDir=tmp_dir})
538 = do mapping <- readIORef v_DirsToClean
539 case lookupFM mapping tmp_dir of
542 let prefix = tmp_dir ++ "/ghc" ++ show x ++ "_"
544 = let dirname = prefix ++ show x
545 in do createDirectory dirname
546 let mapping' = addToFM mapping tmp_dir dirname
547 writeIORef v_DirsToClean mapping'
548 debugTraceMsg dflags 2 (ptext SLIT("Created temporary directory:") <+> text dirname)
551 if isAlreadyExistsError e
557 addFilesToClean :: [FilePath] -> IO ()
558 -- May include wildcards [used by DriverPipeline.run_phase SplitMangle]
559 addFilesToClean files = mapM_ (consIORef v_FilesToClean) files
561 removeTmpDirs :: DynFlags -> [FilePath] -> IO ()
562 removeTmpDirs dflags ds
563 = traceCmd dflags "Deleting temp dirs"
564 ("Deleting: " ++ unwords ds)
565 (mapM_ (removeWith dflags removeDirectory) ds)
567 removeTmpFiles :: DynFlags -> [FilePath] -> IO ()
568 removeTmpFiles dflags fs
570 traceCmd dflags "Deleting temp files"
571 ("Deleting: " ++ unwords deletees)
572 (mapM_ (removeWith dflags removeFile) deletees)
574 -- Flat out refuse to delete files that are likely to be source input
575 -- files (is there a worse bug than having a compiler delete your source
578 -- Deleting source files is a sign of a bug elsewhere, so prominently flag
581 | null non_deletees = act
583 putMsg dflags (text "WARNING - NOT deleting source files:" <+> hsep (map text non_deletees))
586 (non_deletees, deletees) = partition isHaskellUserSrcFilename fs
588 removeWith :: DynFlags -> (FilePath -> IO ()) -> FilePath -> IO ()
589 removeWith dflags remover f = remover f `IO.catch`
591 let msg = if isDoesNotExistError e
592 then ptext SLIT("Warning: deleting non-existent") <+> text f
593 else ptext SLIT("Warning: exception raised when deleting")
596 in debugTraceMsg dflags 2 msg
599 -----------------------------------------------------------------------------
600 -- Running an external program
602 runSomething :: DynFlags
603 -> String -- For -v message
604 -> String -- Command name (possibly a full path)
605 -- assumed already dos-ified
606 -> [Option] -- Arguments
607 -- runSomething will dos-ify them
610 runSomething dflags phase_name pgm args =
611 runSomethingFiltered dflags id phase_name pgm args
614 :: DynFlags -> (String->String) -> String -> String -> [Option] -> IO ()
616 runSomethingFiltered dflags filter_fn phase_name pgm args = do
617 let real_args = filter notNull (map showOpt args)
618 traceCmd dflags phase_name (unwords (pgm:real_args)) $ do
619 (exit_code, doesn'tExist) <-
621 rc <- builderMainLoop dflags filter_fn pgm real_args
623 ExitSuccess{} -> return (rc, False)
625 -- rawSystem returns (ExitFailure 127) if the exec failed for any
626 -- reason (eg. the program doesn't exist). This is the only clue
627 -- we have, but we need to report something to the user because in
628 -- the case of a missing program there will otherwise be no output
630 | n == 127 -> return (rc, True)
631 | otherwise -> return (rc, False))
632 -- Should 'rawSystem' generate an IO exception indicating that
633 -- 'pgm' couldn't be run rather than a funky return code, catch
634 -- this here (the win32 version does this, but it doesn't hurt
635 -- to test for this in general.)
637 if IO.isDoesNotExistError err
638 #if defined(mingw32_HOST_OS) && __GLASGOW_HASKELL__ < 604
639 -- the 'compat' version of rawSystem under mingw32 always
640 -- maps 'errno' to EINVAL to failure.
641 || case (ioeGetErrorType err ) of { InvalidArgument{} -> True ; _ -> False}
643 then return (ExitFailure 1, True)
645 case (doesn'tExist, exit_code) of
646 (True, _) -> throwDyn (InstallationError ("could not execute: " ++ pgm))
647 (_, ExitSuccess) -> return ()
648 _ -> throwDyn (PhaseFailed phase_name exit_code)
652 #if __GLASGOW_HASKELL__ < 603
653 builderMainLoop dflags filter_fn pgm real_args = do
654 rawSystem pgm real_args
656 builderMainLoop dflags filter_fn pgm real_args = do
658 (hStdIn, hStdOut, hStdErr, hProcess) <- runInteractiveProcess pgm real_args Nothing Nothing
660 -- and run a loop piping the output from the compiler to the log_action in DynFlags
661 hSetBuffering hStdOut LineBuffering
662 hSetBuffering hStdErr LineBuffering
663 forkIO (readerProc chan hStdOut filter_fn)
664 forkIO (readerProc chan hStdErr filter_fn)
665 rc <- loop chan hProcess 2 1 ExitSuccess
671 -- status starts at zero, and increments each time either
672 -- a reader process gets EOF, or the build proc exits. We wait
673 -- for all of these to happen (status==3).
674 -- ToDo: we should really have a contingency plan in case any of
675 -- the threads dies, such as a timeout.
676 loop chan hProcess 0 0 exitcode = return exitcode
677 loop chan hProcess t p exitcode = do
679 then getProcessExitCode hProcess
682 Just code -> loop chan hProcess t (p-1) code
688 log_action dflags SevInfo noSrcSpan defaultUserStyle msg
689 loop chan hProcess t p exitcode
690 BuildError loc msg -> do
691 log_action dflags SevError (mkSrcSpan loc loc) defaultUserStyle msg
692 loop chan hProcess t p exitcode
694 loop chan hProcess (t-1) p exitcode
695 | otherwise -> loop chan hProcess t p exitcode
697 readerProc chan hdl filter_fn =
698 (do str <- hGetContents hdl
699 loop (linesPlatform (filter_fn str)) Nothing)
702 -- ToDo: check errors more carefully
703 -- ToDo: in the future, the filter should be implemented as
704 -- a stream transformer.
706 loop [] Nothing = return ()
707 loop [] (Just err) = writeChan chan err
710 Just err@(BuildError srcLoc msg)
711 | leading_whitespace l -> do
712 loop ls (Just (BuildError srcLoc (msg $$ text l)))
720 = case matchRegex errRegex l of
722 writeChan chan (BuildMsg (text l))
724 Just (file':lineno':colno':msg:_) -> do
725 let file = mkFastString file'
726 lineno = read lineno'::Int
727 colno = case colno' of
729 _ -> read (init colno') :: Int
730 srcLoc = mkSrcLoc file lineno colno
731 loop ls (Just (BuildError srcLoc (text msg)))
733 leading_whitespace [] = False
734 leading_whitespace (x:_) = isSpace x
736 errRegex = mkRegex "^([^:]*):([0-9]+):([0-9]+:)?(.*)"
740 | BuildError !SrcLoc !SDoc
744 showOpt (FileOption pre f) = pre ++ platformPath f
745 showOpt (Option "") = ""
746 showOpt (Option s) = s
748 traceCmd :: DynFlags -> String -> String -> IO () -> IO ()
749 -- a) trace the command (at two levels of verbosity)
750 -- b) don't do it at all if dry-run is set
751 traceCmd dflags phase_name cmd_line action
752 = do { let verb = verbosity dflags
753 ; showPass dflags phase_name
754 ; debugTraceMsg dflags 3 (text cmd_line)
758 ; unless (dopt Opt_DryRun dflags) $ do {
761 ; action `IO.catch` handle_exn verb
764 handle_exn verb exn = do { debugTraceMsg dflags 2 (char '\n')
765 ; debugTraceMsg dflags 2 (ptext SLIT("Failed:") <+> text cmd_line <+> text (show exn))
766 ; throwDyn (PhaseFailed phase_name (ExitFailure 1)) }
769 %************************************************************************
771 \subsection{Support code}
773 %************************************************************************
776 -----------------------------------------------------------------------------
777 -- Define getBaseDir :: IO (Maybe String)
779 getBaseDir :: IO (Maybe String)
780 #if defined(mingw32_HOST_OS)
781 -- Assuming we are running ghc, accessed by path $()/bin/ghc.exe,
782 -- return the path $(stuff). Note that we drop the "bin/" directory too.
783 getBaseDir = do let len = (2048::Int) -- plenty, PATH_MAX is 512 under Win32.
784 buf <- mallocArray len
785 ret <- getModuleFileName nullPtr buf len
786 if ret == 0 then free buf >> return Nothing
787 else do s <- peekCString buf
789 return (Just (rootDir s))
791 rootDir s = reverse (dropList "/bin/ghc.exe" (reverse (normalisePath s)))
793 foreign import stdcall unsafe "GetModuleFileNameA"
794 getModuleFileName :: Ptr () -> CString -> Int -> IO Int32
796 getBaseDir = return Nothing
799 #ifdef mingw32_HOST_OS
800 foreign import ccall unsafe "_getpid" getProcessID :: IO Int -- relies on Int == Int32 on Windows
801 #elif __GLASGOW_HASKELL__ > 504
802 getProcessID :: IO Int
803 getProcessID = System.Posix.Internals.c_getpid >>= return . fromIntegral
805 getProcessID :: IO Int
806 getProcessID = Posix.getProcessID
809 -- Divvy up text stream into lines, taking platform dependent
810 -- line termination into account.
811 linesPlatform :: String -> [String]
812 #if !defined(mingw32_HOST_OS)
813 linesPlatform ls = lines ls
815 linesPlatform "" = []
818 (as,xs1) -> as : linesPlatform xs1
820 lineBreak "" = ("","")
821 lineBreak ('\r':'\n':xs) = ([],xs)
822 lineBreak ('\n':xs) = ([],xs)
823 lineBreak (x:xs) = let (as,bs) = lineBreak xs in (x:as,bs)