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 ()
26 touch, -- String -> String -> IO ()
30 -- Temporary-file management
33 cleanTempDirs, cleanTempFiles, cleanTempFilesExcept,
40 #include "HsVersions.h"
54 import System.Environment
55 import System.FilePath
57 import System.IO.Error as IO
58 import System.Directory
61 import qualified Data.Map as Map
62 import Text.ParserCombinators.ReadP hiding (char)
63 import qualified Text.ParserCombinators.ReadP as R
65 #ifndef mingw32_HOST_OS
66 import qualified System.Posix.Internals
67 #else /* Must be Win32 */
69 import Foreign.C.String
73 import Control.Concurrent
75 import SrcLoc ( SrcLoc, mkSrcLoc, noSrcSpan, mkSrcSpan )
78 How GHC finds its files
79 ~~~~~~~~~~~~~~~~~~~~~~~
83 GHC needs various support files (library packages, RTS etc), plus
84 various auxiliary programs (cp, gcc, etc). It starts by finding topdir,
85 the root of GHC's support files
88 - ghc always has a shell wrapper that passes a -B<dir> option
91 - ghc never has a shell wrapper.
92 - we can find the location of the ghc binary, which is
93 $topdir/bin/<something>.exe
94 where <something> may be "ghc", "ghc-stage2", or similar
95 - we strip off the "bin/<something>.exe" to leave $topdir.
97 from topdir we can find package.conf, ghc-asm, etc.
100 SysTools.initSysProgs figures out exactly where all the auxiliary programs
101 are, and initialises mutable variables to make it easy to call them.
102 To to this, it makes use of definitions in Config.hs, which is a Haskell
103 file containing variables whose value is figured out by the build system.
105 Config.hs contains two sorts of things
107 cGCC, The *names* of the programs
110 etc They do *not* include paths
113 cUNLIT_DIR The *path* to the directory containing unlit, split etc
114 cSPLIT_DIR *relative* to the root of the build tree,
115 for use when running *in-place* in a build tree (only)
119 ---------------------------------------------
120 NOTES for an ALTERNATIVE scheme (i.e *not* what is currently implemented):
122 Another hair-brained scheme for simplifying the current tool location
123 nightmare in GHC: Simon originally suggested using another
124 configuration file along the lines of GCC's specs file - which is fine
125 except that it means adding code to read yet another configuration
126 file. What I didn't notice is that the current package.conf is
127 general enough to do this:
130 {name = "tools", import_dirs = [], source_dirs = [],
131 library_dirs = [], hs_libraries = [], extra_libraries = [],
132 include_dirs = [], c_includes = [], package_deps = [],
133 extra_ghc_opts = ["-pgmc/usr/bin/gcc","-pgml${topdir}/bin/unlit", ... etc.],
134 extra_cc_opts = [], extra_ld_opts = []}
136 Which would have the advantage that we get to collect together in one
137 place the path-specific package stuff with the path-specific tool
140 ---------------------------------------------
142 %************************************************************************
144 \subsection{Initialisation}
146 %************************************************************************
149 initSysTools :: Maybe String -- Maybe TopDir path (without the '-B' prefix)
150 -> IO Settings -- Set all the mutable variables above, holding
151 -- (a) the system programs
152 -- (b) the package-config file
153 -- (c) the GHC usage message
154 initSysTools mbMinusB
155 = do { top_dir <- findTopDir mbMinusB
157 -- NB: top_dir is assumed to be in standard Unix
158 -- format, '/' separated
160 ; let settingsFile = top_dir </> "settings"
161 ; settingsStr <- readFile settingsFile
162 ; mySettings <- case maybeReadFuzzy settingsStr of
166 pgmError ("Can't parse " ++ show settingsFile)
167 ; let getSetting key = case lookup key mySettings of
170 Nothing -> pgmError ("No entry for " ++ show key ++ " in " ++ show settingsFile)
171 ; myExtraGccViaCFlags <- getSetting "GCC extra via C opts"
173 ; let installed :: FilePath -> FilePath
174 installed file = top_dir </> file
175 installed_mingw_bin file = top_dir </> ".." </> "mingw" </> "bin" </> file
176 installed_perl_bin file = top_dir </> ".." </> "perl" </> file
178 ; let pkgconfig_path = installed "package.conf.d"
179 ghc_usage_msg_path = installed "ghc-usage.txt"
180 ghci_usage_msg_path = installed "ghci-usage.txt"
182 -- For all systems, unlit, split, mangle are GHC utilities
183 -- architecture-specific stuff is done when building Config.hs
184 unlit_path = installed cGHC_UNLIT_PGM
186 -- split is a Perl script
187 split_script = installed cGHC_SPLIT_PGM
189 windres_path = installed_mingw_bin "windres"
191 ; tmpdir <- getTemporaryDirectory
193 -- On Windows, mingw is distributed with GHC,
194 -- so we look in TopDir/../mingw/bin
197 | isWindowsHost = installed_mingw_bin "gcc"
200 | isWindowsHost = installed_perl_bin cGHC_PERL
201 | otherwise = cGHC_PERL
202 -- 'touch' is a GHC util for Windows
204 | isWindowsHost = installed cGHC_TOUCHY_PGM
205 | otherwise = "touch"
206 -- On Win32 we don't want to rely on #!/bin/perl, so we prepend
207 -- a call to Perl to get the invocation of split.
208 -- On Unix, scripts are invoked using the '#!' method. Binary
209 -- installations of GHC on Unix place the correct line on the
210 -- front of the script at installation time, so we don't want
211 -- to wire-in our knowledge of $(PERL) on the host system here.
212 (split_prog, split_args)
213 | isWindowsHost = (perl_path, [Option split_script])
214 | otherwise = (split_script, [])
215 (mkdll_prog, mkdll_args)
217 = panic "Can't build DLLs on a non-Win32 system"
219 (installed_mingw_bin cMKDLL, [])
221 -- cpp is derived from gcc on all platforms
222 -- HACK, see setPgmP below. We keep 'words' here to remember to fix
223 -- Config.hs one day.
224 ; let cpp_path = (gcc_prog,
225 (Option "-E"):(map Option (words cRAWCPP_FLAGS)))
227 -- Other things being equal, as and ld are simply gcc
228 ; let as_prog = gcc_prog
231 -- figure out llvm location. (TODO: Acutally implement).
232 ; let lc_prog = "llc"
235 ; return $ Settings {
236 sTmpDir = normalise tmpdir,
237 sGhcUsagePath = ghc_usage_msg_path,
238 sGhciUsagePath = ghci_usage_msg_path,
240 sRawSettings = mySettings,
241 sExtraGccViaCFlags = words myExtraGccViaCFlags,
242 sSystemPackageConfig = pkgconfig_path,
246 sPgm_c = (gcc_prog,[]),
247 sPgm_s = (split_prog,split_args),
248 sPgm_a = (as_prog,[]),
249 sPgm_l = (ld_prog,[]),
250 sPgm_dll = (mkdll_prog,mkdll_args),
252 sPgm_sysman = top_dir ++ "/ghc/rts/parallel/SysMan",
253 sPgm_windres = windres_path,
254 sPgm_lo = (lo_prog,[]),
255 sPgm_lc = (lc_prog,[])
256 -- Hans: this isn't right in general, but you can
257 -- elaborate it in the same way as the others
263 -- returns a Unix-format path (relying on getBaseDir to do so too)
264 findTopDir :: Maybe String -- Maybe TopDir path (without the '-B' prefix).
265 -> IO String -- TopDir (in Unix format '/' separated)
266 findTopDir (Just minusb) = return (normalise minusb)
268 = do -- Get directory of executable
269 maybe_exec_dir <- getBaseDir
270 case maybe_exec_dir of
271 -- "Just" on Windows, "Nothing" on unix
272 Nothing -> ghcError (InstallationError "missing -B<dir> option")
273 Just dir -> return dir
277 %************************************************************************
279 \subsection{Running an external program}
281 %************************************************************************
285 runUnlit :: DynFlags -> [Option] -> IO ()
286 runUnlit dflags args = do
288 runSomething dflags "Literate pre-processor" p args
290 runCpp :: DynFlags -> [Option] -> IO ()
291 runCpp dflags args = do
292 let (p,args0) = pgm_P dflags
293 args1 = args0 ++ args
294 args2 = if dopt Opt_WarnIsError dflags
295 then Option "-Werror" : args1
297 mb_env <- getGccEnv args2
298 runSomethingFiltered dflags id "C pre-processor" p args2 mb_env
300 runPp :: DynFlags -> [Option] -> IO ()
301 runPp dflags args = do
303 runSomething dflags "Haskell pre-processor" p args
305 runCc :: DynFlags -> [Option] -> IO ()
306 runCc dflags args = do
307 let (p,args0) = pgm_c dflags
308 args1 = args0 ++ args
309 mb_env <- getGccEnv args1
310 runSomethingFiltered dflags cc_filter "C Compiler" p args1 mb_env
312 -- discard some harmless warnings from gcc that we can't turn off
313 cc_filter = unlines . doFilter . lines
316 gcc gives warnings in chunks like so:
317 In file included from /foo/bar/baz.h:11,
318 from /foo/bar/baz2.h:22,
320 /foo/flibble:14: global register variable ...
321 /foo/flibble:15: warning: call-clobbered r...
322 We break it up into its chunks, remove any call-clobbered register
323 warnings from each chunk, and then delete any chunks that we have
326 doFilter = unChunkWarnings . filterWarnings . chunkWarnings []
327 -- We can't assume that the output will start with an "In file inc..."
328 -- line, so we start off expecting a list of warnings rather than a
330 chunkWarnings :: [String] -- The location stack to use for the next
332 -> [String] -- The remaining lines to look at
333 -> [([String], [String])]
334 chunkWarnings loc_stack [] = [(loc_stack, [])]
335 chunkWarnings loc_stack xs
336 = case break loc_stack_start xs of
337 (warnings, lss:xs') ->
338 case span loc_start_continuation xs' of
340 (loc_stack, warnings) : chunkWarnings (lss : lsc) xs''
341 _ -> [(loc_stack, xs)]
343 filterWarnings :: [([String], [String])] -> [([String], [String])]
344 filterWarnings [] = []
345 -- If the warnings are already empty then we are probably doing
346 -- something wrong, so don't delete anything
347 filterWarnings ((xs, []) : zs) = (xs, []) : filterWarnings zs
348 filterWarnings ((xs, ys) : zs) = case filter wantedWarning ys of
349 [] -> filterWarnings zs
350 ys' -> (xs, ys') : filterWarnings zs
352 unChunkWarnings :: [([String], [String])] -> [String]
353 unChunkWarnings [] = []
354 unChunkWarnings ((xs, ys) : zs) = xs ++ ys ++ unChunkWarnings zs
356 loc_stack_start s = "In file included from " `isPrefixOf` s
357 loc_start_continuation s = " from " `isPrefixOf` s
359 | "warning: call-clobbered register used" `isContainedIn` w = False
362 isContainedIn :: String -> String -> Bool
363 xs `isContainedIn` ys = any (xs `isPrefixOf`) (tails ys)
365 -- If the -B<dir> option is set, add <dir> to PATH. This works around
366 -- a bug in gcc on Windows Vista where it can't find its auxiliary
367 -- binaries (see bug #1110).
368 getGccEnv :: [Option] -> IO (Maybe [(String,String)])
372 else do env <- getEnvironment
373 return (Just (map mangle_path env))
375 (b_dirs, _) = partitionWith get_b_opt opts
377 get_b_opt (Option ('-':'B':dir)) = Left dir
378 get_b_opt other = Right other
380 mangle_path (path,paths) | map toUpper path == "PATH"
381 = (path, '\"' : head b_dirs ++ "\";" ++ paths)
382 mangle_path other = other
384 runSplit :: DynFlags -> [Option] -> IO ()
385 runSplit dflags args = do
386 let (p,args0) = pgm_s dflags
387 runSomething dflags "Splitter" p (args0++args)
389 runAs :: DynFlags -> [Option] -> IO ()
390 runAs dflags args = do
391 let (p,args0) = pgm_a dflags
392 args1 = args0 ++ args
393 mb_env <- getGccEnv args1
394 runSomethingFiltered dflags id "Assembler" p args1 mb_env
396 runLlvmOpt :: DynFlags -> [Option] -> IO ()
397 runLlvmOpt dflags args = do
398 let (p,args0) = pgm_lo dflags
399 runSomething dflags "LLVM Optimiser" p (args0++args)
401 runLlvmLlc :: DynFlags -> [Option] -> IO ()
402 runLlvmLlc dflags args = do
403 let (p,args0) = pgm_lc dflags
404 runSomething dflags "LLVM Compiler" p (args0++args)
406 runLink :: DynFlags -> [Option] -> IO ()
407 runLink dflags args = do
408 let (p,args0) = pgm_l dflags
409 args1 = args0 ++ args
410 mb_env <- getGccEnv args1
411 runSomethingFiltered dflags id "Linker" p args1 mb_env
413 runMkDLL :: DynFlags -> [Option] -> IO ()
414 runMkDLL dflags args = do
415 let (p,args0) = pgm_dll dflags
416 args1 = args0 ++ args
417 mb_env <- getGccEnv (args0++args)
418 runSomethingFiltered dflags id "Make DLL" p args1 mb_env
420 runWindres :: DynFlags -> [Option] -> IO ()
421 runWindres dflags args = do
422 let (gcc, gcc_args) = pgm_c dflags
423 windres = pgm_windres dflags
424 quote x = "\"" ++ x ++ "\""
425 args' = -- If windres.exe and gcc.exe are in a directory containing
426 -- spaces then windres fails to run gcc. We therefore need
427 -- to tell it what command to use...
428 Option ("--preprocessor=" ++
429 unwords (map quote (gcc :
430 map showOpt gcc_args ++
431 ["-E", "-xc", "-DRC_INVOKED"])))
432 -- ...but if we do that then if windres calls popen then
433 -- it can't understand the quoting, so we have to use
434 -- --use-temp-file so that it interprets it correctly.
436 : Option "--use-temp-file"
438 mb_env <- getGccEnv gcc_args
439 runSomethingFiltered dflags id "Windres" windres args' mb_env
441 touch :: DynFlags -> String -> String -> IO ()
442 touch dflags purpose arg =
443 runSomething dflags purpose (pgm_T dflags) [FileOption "" arg]
445 copy :: DynFlags -> String -> FilePath -> FilePath -> IO ()
446 copy dflags purpose from to = copyWithHeader dflags purpose Nothing from to
448 copyWithHeader :: DynFlags -> String -> Maybe String -> FilePath -> FilePath
450 copyWithHeader dflags purpose maybe_header from to = do
451 showPass dflags purpose
453 hout <- openBinaryFile to WriteMode
454 hin <- openBinaryFile from ReadMode
455 ls <- hGetContents hin -- inefficient, but it'll do for now. ToDo: speed up
456 maybe (return ()) (hPutStr hout) maybe_header
461 -- | read the contents of the named section in an ELF object as a
463 readElfSection :: DynFlags -> String -> FilePath -> IO (Maybe String)
464 readElfSection _dflags section exe = do
467 args = [Option "-p", Option section, FileOption "" exe]
469 r <- readProcessWithExitCode prog (filter notNull (map showOpt args)) ""
471 (ExitSuccess, out, _err) -> return (doFilter (lines out))
474 doFilter [] = Nothing
475 doFilter (s:r) = case readP_to_S parse s of
479 skipSpaces; R.char '['; skipSpaces; string "0]"; skipSpaces;
483 %************************************************************************
485 \subsection{Managing temporary files
487 %************************************************************************
490 cleanTempDirs :: DynFlags -> IO ()
492 = unless (dopt Opt_KeepTmpFiles dflags)
493 $ do let ref = dirsToClean dflags
495 removeTmpDirs dflags (Map.elems ds)
496 writeIORef ref Map.empty
498 cleanTempFiles :: DynFlags -> IO ()
499 cleanTempFiles dflags
500 = unless (dopt Opt_KeepTmpFiles dflags)
501 $ do let ref = filesToClean dflags
503 removeTmpFiles dflags fs
506 cleanTempFilesExcept :: DynFlags -> [FilePath] -> IO ()
507 cleanTempFilesExcept dflags dont_delete
508 = unless (dopt Opt_KeepTmpFiles dflags)
509 $ do let ref = filesToClean dflags
510 files <- readIORef ref
511 let (to_keep, to_delete) = partition (`elem` dont_delete) files
512 writeIORef ref to_keep
513 removeTmpFiles dflags to_delete
516 -- find a temporary name that doesn't already exist.
517 newTempName :: DynFlags -> Suffix -> IO FilePath
518 newTempName dflags extn
519 = do d <- getTempDir dflags
521 findTempName (d </> "ghc" ++ show x ++ "_") 0
523 findTempName :: FilePath -> Integer -> IO FilePath
524 findTempName prefix x
525 = do let filename = (prefix ++ show x) <.> extn
526 b <- doesFileExist filename
527 if b then findTempName prefix (x+1)
528 else do -- clean it up later
529 consIORef (filesToClean dflags) filename
532 -- return our temporary directory within tmp_dir, creating one if we
533 -- don't have one yet
534 getTempDir :: DynFlags -> IO FilePath
536 = do let ref = dirsToClean dflags
537 tmp_dir = tmpDir dflags
538 mapping <- readIORef ref
539 case Map.lookup tmp_dir mapping of
542 let prefix = tmp_dir </> "ghc" ++ show x ++ "_"
544 mkTempDir :: Integer -> IO FilePath
546 = let dirname = prefix ++ show x
547 in do createDirectory dirname
548 let mapping' = Map.insert tmp_dir dirname mapping
549 writeIORef ref mapping'
550 debugTraceMsg dflags 2 (ptext (sLit "Created temporary directory:") <+> text dirname)
553 if isAlreadyExistsError e
559 addFilesToClean :: DynFlags -> [FilePath] -> IO ()
560 -- May include wildcards [used by DriverPipeline.run_phase SplitMangle]
561 addFilesToClean dflags files = mapM_ (consIORef (filesToClean dflags)) files
563 removeTmpDirs :: DynFlags -> [FilePath] -> IO ()
564 removeTmpDirs dflags ds
565 = traceCmd dflags "Deleting temp dirs"
566 ("Deleting: " ++ unwords ds)
567 (mapM_ (removeWith dflags removeDirectory) ds)
569 removeTmpFiles :: DynFlags -> [FilePath] -> IO ()
570 removeTmpFiles dflags fs
572 traceCmd dflags "Deleting temp files"
573 ("Deleting: " ++ unwords deletees)
574 (mapM_ (removeWith dflags removeFile) deletees)
576 -- Flat out refuse to delete files that are likely to be source input
577 -- files (is there a worse bug than having a compiler delete your source
580 -- Deleting source files is a sign of a bug elsewhere, so prominently flag
583 | null non_deletees = act
585 putMsg dflags (text "WARNING - NOT deleting source files:" <+> hsep (map text non_deletees))
588 (non_deletees, deletees) = partition isHaskellUserSrcFilename fs
590 removeWith :: DynFlags -> (FilePath -> IO ()) -> FilePath -> IO ()
591 removeWith dflags remover f = remover f `catchIO`
593 let msg = if isDoesNotExistError e
594 then ptext (sLit "Warning: deleting non-existent") <+> text f
595 else ptext (sLit "Warning: exception raised when deleting")
598 in debugTraceMsg dflags 2 msg
601 -----------------------------------------------------------------------------
602 -- Running an external program
604 runSomething :: DynFlags
605 -> String -- For -v message
606 -> String -- Command name (possibly a full path)
607 -- assumed already dos-ified
608 -> [Option] -- Arguments
609 -- runSomething will dos-ify them
612 runSomething dflags phase_name pgm args =
613 runSomethingFiltered dflags id phase_name pgm args Nothing
616 :: DynFlags -> (String->String) -> String -> String -> [Option]
617 -> Maybe [(String,String)] -> IO ()
619 runSomethingFiltered dflags filter_fn phase_name pgm args mb_env = do
620 let real_args = filter notNull (map showOpt args)
621 #if __GLASGOW_HASKELL__ >= 701
622 cmdLine = showCommandForUser pgm real_args
624 cmdLine = unwords (pgm:real_args)
626 traceCmd dflags phase_name cmdLine $ do
627 (exit_code, doesn'tExist) <-
629 rc <- builderMainLoop dflags filter_fn pgm real_args mb_env
631 ExitSuccess{} -> return (rc, False)
633 -- rawSystem returns (ExitFailure 127) if the exec failed for any
634 -- reason (eg. the program doesn't exist). This is the only clue
635 -- we have, but we need to report something to the user because in
636 -- the case of a missing program there will otherwise be no output
638 | n == 127 -> return (rc, True)
639 | otherwise -> return (rc, False))
640 -- Should 'rawSystem' generate an IO exception indicating that
641 -- 'pgm' couldn't be run rather than a funky return code, catch
642 -- this here (the win32 version does this, but it doesn't hurt
643 -- to test for this in general.)
645 if IO.isDoesNotExistError err
646 then return (ExitFailure 1, True)
648 case (doesn'tExist, exit_code) of
649 (True, _) -> ghcError (InstallationError ("could not execute: " ++ pgm))
650 (_, ExitSuccess) -> return ()
651 _ -> ghcError (PhaseFailed phase_name exit_code)
653 builderMainLoop :: DynFlags -> (String -> String) -> FilePath
654 -> [String] -> Maybe [(String, String)]
656 builderMainLoop dflags filter_fn pgm real_args mb_env = do
658 (hStdIn, hStdOut, hStdErr, hProcess) <- runInteractiveProcess pgm real_args Nothing mb_env
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 -- we don't want to finish until 2 streams have been completed
666 -- (stdout and stderr)
667 -- nor until 1 exit code has been retrieved.
668 rc <- loop chan hProcess (2::Integer) (1::Integer) ExitSuccess
669 -- after that, we're done here.
675 -- status starts at zero, and increments each time either
676 -- a reader process gets EOF, or the build proc exits. We wait
677 -- for all of these to happen (status==3).
678 -- ToDo: we should really have a contingency plan in case any of
679 -- the threads dies, such as a timeout.
680 loop _ _ 0 0 exitcode = return exitcode
681 loop chan hProcess t p exitcode = do
683 then getProcessExitCode hProcess
686 Just code -> loop chan hProcess t (p-1) code
692 log_action dflags SevInfo noSrcSpan defaultUserStyle msg
693 loop chan hProcess t p exitcode
694 BuildError loc msg -> do
695 log_action dflags SevError (mkSrcSpan loc loc) defaultUserStyle msg
696 loop chan hProcess t p exitcode
698 loop chan hProcess (t-1) p exitcode
699 | otherwise -> loop chan hProcess t p exitcode
701 readerProc :: Chan BuildMessage -> Handle -> (String -> String) -> IO ()
702 readerProc chan hdl filter_fn =
703 (do str <- hGetContents hdl
704 loop (linesPlatform (filter_fn str)) Nothing)
707 -- ToDo: check errors more carefully
708 -- ToDo: in the future, the filter should be implemented as
709 -- a stream transformer.
711 loop [] Nothing = return ()
712 loop [] (Just err) = writeChan chan err
715 Just err@(BuildError srcLoc msg)
716 | leading_whitespace l -> do
717 loop ls (Just (BuildError srcLoc (msg $$ text l)))
723 _ -> panic "readerProc/loop"
726 = case parseError l of
728 writeChan chan (BuildMsg (text l))
730 Just (file, lineNum, colNum, msg) -> do
731 let srcLoc = mkSrcLoc (mkFastString file) lineNum colNum
732 loop ls (Just (BuildError srcLoc (text msg)))
734 leading_whitespace [] = False
735 leading_whitespace (x:_) = isSpace x
737 parseError :: String -> Maybe (String, Int, Int, String)
738 parseError s0 = case breakColon s0 of
739 Just (filename, s1) ->
740 case breakIntColon s1 of
741 Just (lineNum, s2) ->
742 case breakIntColon s2 of
743 Just (columnNum, s3) ->
744 Just (filename, lineNum, columnNum, s3)
746 Just (filename, lineNum, 0, s2)
750 breakColon :: String -> Maybe (String, String)
751 breakColon xs = case break (':' ==) xs of
752 (ys, _:zs) -> Just (ys, zs)
755 breakIntColon :: String -> Maybe (Int, String)
756 breakIntColon xs = case break (':' ==) xs of
758 | not (null ys) && all isAscii ys && all isDigit ys ->
764 | BuildError !SrcLoc !SDoc
767 traceCmd :: DynFlags -> String -> String -> IO () -> IO ()
768 -- a) trace the command (at two levels of verbosity)
769 -- b) don't do it at all if dry-run is set
770 traceCmd dflags phase_name cmd_line action
771 = do { let verb = verbosity dflags
772 ; showPass dflags phase_name
773 ; debugTraceMsg dflags 3 (text cmd_line)
777 ; unless (dopt Opt_DryRun dflags) $ do {
780 ; action `catchIO` handle_exn verb
783 handle_exn _verb exn = do { debugTraceMsg dflags 2 (char '\n')
784 ; debugTraceMsg dflags 2 (ptext (sLit "Failed:") <+> text cmd_line <+> text (show exn))
785 ; ghcError (PhaseFailed phase_name (ExitFailure 1)) }
788 %************************************************************************
790 \subsection{Support code}
792 %************************************************************************
795 -----------------------------------------------------------------------------
796 -- Define getBaseDir :: IO (Maybe String)
798 getBaseDir :: IO (Maybe String)
799 #if defined(mingw32_HOST_OS)
800 -- Assuming we are running ghc, accessed by path $(stuff)/bin/ghc.exe,
801 -- return the path $(stuff)/lib.
802 getBaseDir = do let len = (2048::Int) -- plenty, PATH_MAX is 512 under Win32.
803 buf <- mallocArray len
804 ret <- getModuleFileName nullPtr buf len
805 if ret == 0 then free buf >> return Nothing
806 else do s <- peekCString buf
808 return (Just (rootDir s))
810 rootDir s = case splitFileName $ normalise s of
812 | lower ghc_exe `elem` ["ghc.exe",
816 case splitFileName $ takeDirectory d of
817 -- ghc is in $topdir/bin/ghc.exe
818 (d', bin) | lower bin == "bin" -> takeDirectory d' </> "lib"
821 where fail = panic ("can't decompose ghc.exe path: " ++ show s)
824 foreign import stdcall unsafe "GetModuleFileNameA"
825 getModuleFileName :: Ptr () -> CString -> Int -> IO Int32
827 getBaseDir = return Nothing
830 #ifdef mingw32_HOST_OS
831 foreign import ccall unsafe "_getpid" getProcessID :: IO Int -- relies on Int == Int32 on Windows
833 getProcessID :: IO Int
834 getProcessID = System.Posix.Internals.c_getpid >>= return . fromIntegral
837 -- Divvy up text stream into lines, taking platform dependent
838 -- line termination into account.
839 linesPlatform :: String -> [String]
840 #if !defined(mingw32_HOST_OS)
841 linesPlatform ls = lines ls
843 linesPlatform "" = []
846 (as,xs1) -> as : linesPlatform xs1
848 lineBreak "" = ("","")
849 lineBreak ('\r':'\n':xs) = ([],xs)
850 lineBreak ('\n':xs) = ([],xs)
851 lineBreak (x:xs) = let (as,bs) = lineBreak xs in (x:as,bs)