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"
55 import System.Environment
56 import System.FilePath
58 import System.IO.Error as IO
59 import System.Directory
62 import qualified Data.Map as Map
63 import Text.ParserCombinators.ReadP hiding (char)
64 import qualified Text.ParserCombinators.ReadP as R
66 #ifndef mingw32_HOST_OS
67 import qualified System.Posix.Internals
68 #else /* Must be Win32 */
70 import Foreign.C.String
74 import Control.Concurrent
76 import SrcLoc ( SrcLoc, mkSrcLoc, noSrcSpan, mkSrcSpan )
79 How GHC finds its files
80 ~~~~~~~~~~~~~~~~~~~~~~~
84 GHC needs various support files (library packages, RTS etc), plus
85 various auxiliary programs (cp, gcc, etc). It starts by finding topdir,
86 the root of GHC's support files
89 - ghc always has a shell wrapper that passes a -B<dir> option
92 - ghc never has a shell wrapper.
93 - we can find the location of the ghc binary, which is
94 $topdir/bin/<something>.exe
95 where <something> may be "ghc", "ghc-stage2", or similar
96 - we strip off the "bin/<something>.exe" to leave $topdir.
98 from topdir we can find package.conf, ghc-asm, etc.
101 SysTools.initSysProgs figures out exactly where all the auxiliary programs
102 are, and initialises mutable variables to make it easy to call them.
103 To to this, it makes use of definitions in Config.hs, which is a Haskell
104 file containing variables whose value is figured out by the build system.
106 Config.hs contains two sorts of things
108 cGCC, The *names* of the programs
111 etc They do *not* include paths
114 cUNLIT_DIR The *path* to the directory containing unlit, split etc
115 cSPLIT_DIR *relative* to the root of the build tree,
116 for use when running *in-place* in a build tree (only)
120 ---------------------------------------------
121 NOTES for an ALTERNATIVE scheme (i.e *not* what is currently implemented):
123 Another hair-brained scheme for simplifying the current tool location
124 nightmare in GHC: Simon originally suggested using another
125 configuration file along the lines of GCC's specs file - which is fine
126 except that it means adding code to read yet another configuration
127 file. What I didn't notice is that the current package.conf is
128 general enough to do this:
131 {name = "tools", import_dirs = [], source_dirs = [],
132 library_dirs = [], hs_libraries = [], extra_libraries = [],
133 include_dirs = [], c_includes = [], package_deps = [],
134 extra_ghc_opts = ["-pgmc/usr/bin/gcc","-pgml${topdir}/bin/unlit", ... etc.],
135 extra_cc_opts = [], extra_ld_opts = []}
137 Which would have the advantage that we get to collect together in one
138 place the path-specific package stuff with the path-specific tool
141 ---------------------------------------------
143 %************************************************************************
145 \subsection{Initialisation}
147 %************************************************************************
150 initSysTools :: Maybe String -- Maybe TopDir path (without the '-B' prefix)
151 -> IO Settings -- Set all the mutable variables above, holding
152 -- (a) the system programs
153 -- (b) the package-config file
154 -- (c) the GHC usage message
155 initSysTools mbMinusB
156 = do { top_dir <- findTopDir mbMinusB
158 -- NB: top_dir is assumed to be in standard Unix
159 -- format, '/' separated
161 ; let settingsFile = top_dir </> "settings"
162 ; settingsStr <- readFile settingsFile
163 ; mySettings <- case maybeReadFuzzy settingsStr of
167 pgmError ("Can't parse " ++ show settingsFile)
168 ; let getSetting key = case lookup key mySettings of
171 Nothing -> pgmError ("No entry for " ++ show key ++ " in " ++ show settingsFile)
172 ; myExtraGccViaCFlags <- getSetting "GCC extra via C opts"
174 ; let installed :: FilePath -> FilePath
175 installed file = top_dir </> file
176 installed_mingw_bin file = top_dir </> ".." </> "mingw" </> "bin" </> file
177 installed_perl_bin file = top_dir </> ".." </> "perl" </> file
179 ; let pkgconfig_path = installed "package.conf.d"
180 ghc_usage_msg_path = installed "ghc-usage.txt"
181 ghci_usage_msg_path = installed "ghci-usage.txt"
183 -- For all systems, unlit, split, mangle are GHC utilities
184 -- architecture-specific stuff is done when building Config.hs
185 unlit_path = installed cGHC_UNLIT_PGM
187 -- split is a Perl script
188 split_script = installed cGHC_SPLIT_PGM
190 windres_path = installed_mingw_bin "windres"
192 ; tmpdir <- getTemporaryDirectory
194 -- On Windows, mingw is distributed with GHC,
195 -- so we look in TopDir/../mingw/bin
198 | isWindowsHost = installed_mingw_bin "gcc"
201 | isWindowsHost = installed_perl_bin cGHC_PERL
202 | otherwise = cGHC_PERL
203 -- 'touch' is a GHC util for Windows
205 | isWindowsHost = installed cGHC_TOUCHY_PGM
206 | otherwise = "touch"
207 -- On Win32 we don't want to rely on #!/bin/perl, so we prepend
208 -- a call to Perl to get the invocation of split.
209 -- On Unix, scripts are invoked using the '#!' method. Binary
210 -- installations of GHC on Unix place the correct line on the
211 -- front of the script at installation time, so we don't want
212 -- to wire-in our knowledge of $(PERL) on the host system here.
213 (split_prog, split_args)
214 | isWindowsHost = (perl_path, [Option split_script])
215 | otherwise = (split_script, [])
216 (mkdll_prog, mkdll_args)
218 = panic "Can't build DLLs on a non-Win32 system"
220 (installed_mingw_bin cMKDLL, [])
222 -- cpp is derived from gcc on all platforms
223 -- HACK, see setPgmP below. We keep 'words' here to remember to fix
224 -- Config.hs one day.
225 ; let cpp_path = (gcc_prog,
226 (Option "-E"):(map Option (words cRAWCPP_FLAGS)))
228 -- Other things being equal, as and ld are simply gcc
229 ; let as_prog = gcc_prog
232 -- figure out llvm location. (TODO: Acutally implement).
233 ; let lc_prog = "llc"
236 ; return $ Settings {
237 sTmpDir = normalise tmpdir,
238 sGhcUsagePath = ghc_usage_msg_path,
239 sGhciUsagePath = ghci_usage_msg_path,
241 sRawSettings = mySettings,
242 sExtraGccViaCFlags = words myExtraGccViaCFlags,
243 sSystemPackageConfig = pkgconfig_path,
247 sPgm_c = (gcc_prog,[]),
248 sPgm_s = (split_prog,split_args),
249 sPgm_a = (as_prog,[]),
250 sPgm_l = (ld_prog,[]),
251 sPgm_dll = (mkdll_prog,mkdll_args),
253 sPgm_sysman = top_dir ++ "/ghc/rts/parallel/SysMan",
254 sPgm_windres = windres_path,
255 sPgm_lo = (lo_prog,[]),
256 sPgm_lc = (lc_prog,[]),
257 -- Hans: this isn't right in general, but you can
258 -- elaborate it in the same way as the others
261 then -- this list gets reversed
262 ["-D__PIC__", "-U __PIC__"]
277 -- returns a Unix-format path (relying on getBaseDir to do so too)
278 findTopDir :: Maybe String -- Maybe TopDir path (without the '-B' prefix).
279 -> IO String -- TopDir (in Unix format '/' separated)
280 findTopDir (Just minusb) = return (normalise minusb)
282 = do -- Get directory of executable
283 maybe_exec_dir <- getBaseDir
284 case maybe_exec_dir of
285 -- "Just" on Windows, "Nothing" on unix
286 Nothing -> ghcError (InstallationError "missing -B<dir> option")
287 Just dir -> return dir
291 %************************************************************************
293 \subsection{Running an external program}
295 %************************************************************************
299 runUnlit :: DynFlags -> [Option] -> IO ()
300 runUnlit dflags args = do
302 runSomething dflags "Literate pre-processor" p args
304 runCpp :: DynFlags -> [Option] -> IO ()
305 runCpp dflags args = do
306 let (p,args0) = pgm_P dflags
307 args1 = args0 ++ args
308 args2 = if dopt Opt_WarnIsError dflags
309 then Option "-Werror" : args1
311 mb_env <- getGccEnv args2
312 runSomethingFiltered dflags id "C pre-processor" p args2 mb_env
314 runPp :: DynFlags -> [Option] -> IO ()
315 runPp dflags args = do
317 runSomething dflags "Haskell pre-processor" p args
319 runCc :: DynFlags -> [Option] -> IO ()
320 runCc dflags args = do
321 let (p,args0) = pgm_c dflags
322 args1 = args0 ++ args
323 mb_env <- getGccEnv args1
324 runSomethingFiltered dflags cc_filter "C Compiler" p args1 mb_env
326 -- discard some harmless warnings from gcc that we can't turn off
327 cc_filter = unlines . doFilter . lines
330 gcc gives warnings in chunks like so:
331 In file included from /foo/bar/baz.h:11,
332 from /foo/bar/baz2.h:22,
334 /foo/flibble:14: global register variable ...
335 /foo/flibble:15: warning: call-clobbered r...
336 We break it up into its chunks, remove any call-clobbered register
337 warnings from each chunk, and then delete any chunks that we have
340 doFilter = unChunkWarnings . filterWarnings . chunkWarnings []
341 -- We can't assume that the output will start with an "In file inc..."
342 -- line, so we start off expecting a list of warnings rather than a
344 chunkWarnings :: [String] -- The location stack to use for the next
346 -> [String] -- The remaining lines to look at
347 -> [([String], [String])]
348 chunkWarnings loc_stack [] = [(loc_stack, [])]
349 chunkWarnings loc_stack xs
350 = case break loc_stack_start xs of
351 (warnings, lss:xs') ->
352 case span loc_start_continuation xs' of
354 (loc_stack, warnings) : chunkWarnings (lss : lsc) xs''
355 _ -> [(loc_stack, xs)]
357 filterWarnings :: [([String], [String])] -> [([String], [String])]
358 filterWarnings [] = []
359 -- If the warnings are already empty then we are probably doing
360 -- something wrong, so don't delete anything
361 filterWarnings ((xs, []) : zs) = (xs, []) : filterWarnings zs
362 filterWarnings ((xs, ys) : zs) = case filter wantedWarning ys of
363 [] -> filterWarnings zs
364 ys' -> (xs, ys') : filterWarnings zs
366 unChunkWarnings :: [([String], [String])] -> [String]
367 unChunkWarnings [] = []
368 unChunkWarnings ((xs, ys) : zs) = xs ++ ys ++ unChunkWarnings zs
370 loc_stack_start s = "In file included from " `isPrefixOf` s
371 loc_start_continuation s = " from " `isPrefixOf` s
373 | "warning: call-clobbered register used" `isContainedIn` w = False
376 isContainedIn :: String -> String -> Bool
377 xs `isContainedIn` ys = any (xs `isPrefixOf`) (tails ys)
379 -- If the -B<dir> option is set, add <dir> to PATH. This works around
380 -- a bug in gcc on Windows Vista where it can't find its auxiliary
381 -- binaries (see bug #1110).
382 getGccEnv :: [Option] -> IO (Maybe [(String,String)])
386 else do env <- getEnvironment
387 return (Just (map mangle_path env))
389 (b_dirs, _) = partitionWith get_b_opt opts
391 get_b_opt (Option ('-':'B':dir)) = Left dir
392 get_b_opt other = Right other
394 mangle_path (path,paths) | map toUpper path == "PATH"
395 = (path, '\"' : head b_dirs ++ "\";" ++ paths)
396 mangle_path other = other
398 runSplit :: DynFlags -> [Option] -> IO ()
399 runSplit dflags args = do
400 let (p,args0) = pgm_s dflags
401 runSomething dflags "Splitter" p (args0++args)
403 runAs :: DynFlags -> [Option] -> IO ()
404 runAs dflags args = do
405 let (p,args0) = pgm_a dflags
406 args1 = args0 ++ args
407 mb_env <- getGccEnv args1
408 runSomethingFiltered dflags id "Assembler" p args1 mb_env
410 runLlvmOpt :: DynFlags -> [Option] -> IO ()
411 runLlvmOpt dflags args = do
412 let (p,args0) = pgm_lo dflags
413 runSomething dflags "LLVM Optimiser" p (args0++args)
415 runLlvmLlc :: DynFlags -> [Option] -> IO ()
416 runLlvmLlc dflags args = do
417 let (p,args0) = pgm_lc dflags
418 runSomething dflags "LLVM Compiler" p (args0++args)
420 runLink :: DynFlags -> [Option] -> IO ()
421 runLink dflags args = do
422 let (p,args0) = pgm_l dflags
423 args1 = args0 ++ args
424 mb_env <- getGccEnv args1
425 runSomethingFiltered dflags id "Linker" p args1 mb_env
427 runMkDLL :: DynFlags -> [Option] -> IO ()
428 runMkDLL dflags args = do
429 let (p,args0) = pgm_dll dflags
430 args1 = args0 ++ args
431 mb_env <- getGccEnv (args0++args)
432 runSomethingFiltered dflags id "Make DLL" p args1 mb_env
434 runWindres :: DynFlags -> [Option] -> IO ()
435 runWindres dflags args = do
436 let (gcc, gcc_args) = pgm_c dflags
437 windres = pgm_windres dflags
438 quote x = "\"" ++ x ++ "\""
439 args' = -- If windres.exe and gcc.exe are in a directory containing
440 -- spaces then windres fails to run gcc. We therefore need
441 -- to tell it what command to use...
442 Option ("--preprocessor=" ++
443 unwords (map quote (gcc :
444 map showOpt gcc_args ++
445 ["-E", "-xc", "-DRC_INVOKED"])))
446 -- ...but if we do that then if windres calls popen then
447 -- it can't understand the quoting, so we have to use
448 -- --use-temp-file so that it interprets it correctly.
450 : Option "--use-temp-file"
452 mb_env <- getGccEnv gcc_args
453 runSomethingFiltered dflags id "Windres" windres args' mb_env
455 touch :: DynFlags -> String -> String -> IO ()
456 touch dflags purpose arg =
457 runSomething dflags purpose (pgm_T dflags) [FileOption "" arg]
459 copy :: DynFlags -> String -> FilePath -> FilePath -> IO ()
460 copy dflags purpose from to = copyWithHeader dflags purpose Nothing from to
462 copyWithHeader :: DynFlags -> String -> Maybe String -> FilePath -> FilePath
464 copyWithHeader dflags purpose maybe_header from to = do
465 showPass dflags purpose
467 hout <- openBinaryFile to WriteMode
468 hin <- openBinaryFile from ReadMode
469 ls <- hGetContents hin -- inefficient, but it'll do for now. ToDo: speed up
470 maybe (return ()) (hPutStr hout) maybe_header
475 -- | read the contents of the named section in an ELF object as a
477 readElfSection :: DynFlags -> String -> FilePath -> IO (Maybe String)
478 readElfSection _dflags section exe = do
481 args = [Option "-p", Option section, FileOption "" exe]
483 r <- readProcessWithExitCode prog (filter notNull (map showOpt args)) ""
485 (ExitSuccess, out, _err) -> return (doFilter (lines out))
488 doFilter [] = Nothing
489 doFilter (s:r) = case readP_to_S parse s of
493 skipSpaces; R.char '['; skipSpaces; string "0]"; skipSpaces;
497 %************************************************************************
499 \subsection{Managing temporary files
501 %************************************************************************
504 cleanTempDirs :: DynFlags -> IO ()
506 = unless (dopt Opt_KeepTmpFiles dflags)
507 $ do let ref = dirsToClean dflags
509 removeTmpDirs dflags (Map.elems ds)
510 writeIORef ref Map.empty
512 cleanTempFiles :: DynFlags -> IO ()
513 cleanTempFiles dflags
514 = unless (dopt Opt_KeepTmpFiles dflags)
515 $ do let ref = filesToClean dflags
517 removeTmpFiles dflags fs
520 cleanTempFilesExcept :: DynFlags -> [FilePath] -> IO ()
521 cleanTempFilesExcept dflags dont_delete
522 = unless (dopt Opt_KeepTmpFiles dflags)
523 $ do let ref = filesToClean dflags
524 files <- readIORef ref
525 let (to_keep, to_delete) = partition (`elem` dont_delete) files
526 writeIORef ref to_keep
527 removeTmpFiles dflags to_delete
530 -- find a temporary name that doesn't already exist.
531 newTempName :: DynFlags -> Suffix -> IO FilePath
532 newTempName dflags extn
533 = do d <- getTempDir dflags
535 findTempName (d </> "ghc" ++ show x ++ "_") 0
537 findTempName :: FilePath -> Integer -> IO FilePath
538 findTempName prefix x
539 = do let filename = (prefix ++ show x) <.> extn
540 b <- doesFileExist filename
541 if b then findTempName prefix (x+1)
542 else do -- clean it up later
543 consIORef (filesToClean dflags) filename
546 -- return our temporary directory within tmp_dir, creating one if we
547 -- don't have one yet
548 getTempDir :: DynFlags -> IO FilePath
550 = do let ref = dirsToClean dflags
551 tmp_dir = tmpDir dflags
552 mapping <- readIORef ref
553 case Map.lookup tmp_dir mapping of
556 let prefix = tmp_dir </> "ghc" ++ show x ++ "_"
558 mkTempDir :: Integer -> IO FilePath
560 = let dirname = prefix ++ show x
561 in do createDirectory dirname
562 let mapping' = Map.insert tmp_dir dirname mapping
563 writeIORef ref mapping'
564 debugTraceMsg dflags 2 (ptext (sLit "Created temporary directory:") <+> text dirname)
567 if isAlreadyExistsError e
573 addFilesToClean :: DynFlags -> [FilePath] -> IO ()
574 -- May include wildcards [used by DriverPipeline.run_phase SplitMangle]
575 addFilesToClean dflags files = mapM_ (consIORef (filesToClean dflags)) files
577 removeTmpDirs :: DynFlags -> [FilePath] -> IO ()
578 removeTmpDirs dflags ds
579 = traceCmd dflags "Deleting temp dirs"
580 ("Deleting: " ++ unwords ds)
581 (mapM_ (removeWith dflags removeDirectory) ds)
583 removeTmpFiles :: DynFlags -> [FilePath] -> IO ()
584 removeTmpFiles dflags fs
586 traceCmd dflags "Deleting temp files"
587 ("Deleting: " ++ unwords deletees)
588 (mapM_ (removeWith dflags removeFile) deletees)
590 -- Flat out refuse to delete files that are likely to be source input
591 -- files (is there a worse bug than having a compiler delete your source
594 -- Deleting source files is a sign of a bug elsewhere, so prominently flag
597 | null non_deletees = act
599 putMsg dflags (text "WARNING - NOT deleting source files:" <+> hsep (map text non_deletees))
602 (non_deletees, deletees) = partition isHaskellUserSrcFilename fs
604 removeWith :: DynFlags -> (FilePath -> IO ()) -> FilePath -> IO ()
605 removeWith dflags remover f = remover f `catchIO`
607 let msg = if isDoesNotExistError e
608 then ptext (sLit "Warning: deleting non-existent") <+> text f
609 else ptext (sLit "Warning: exception raised when deleting")
612 in debugTraceMsg dflags 2 msg
615 -----------------------------------------------------------------------------
616 -- Running an external program
618 runSomething :: DynFlags
619 -> String -- For -v message
620 -> String -- Command name (possibly a full path)
621 -- assumed already dos-ified
622 -> [Option] -- Arguments
623 -- runSomething will dos-ify them
626 runSomething dflags phase_name pgm args =
627 runSomethingFiltered dflags id phase_name pgm args Nothing
630 :: DynFlags -> (String->String) -> String -> String -> [Option]
631 -> Maybe [(String,String)] -> IO ()
633 runSomethingFiltered dflags filter_fn phase_name pgm args mb_env = do
634 let real_args = filter notNull (map showOpt args)
635 #if __GLASGOW_HASKELL__ >= 701
636 cmdLine = showCommandForUser pgm real_args
638 cmdLine = unwords (pgm:real_args)
640 traceCmd dflags phase_name cmdLine $ do
641 (exit_code, doesn'tExist) <-
643 rc <- builderMainLoop dflags filter_fn pgm real_args mb_env
645 ExitSuccess{} -> return (rc, False)
647 -- rawSystem returns (ExitFailure 127) if the exec failed for any
648 -- reason (eg. the program doesn't exist). This is the only clue
649 -- we have, but we need to report something to the user because in
650 -- the case of a missing program there will otherwise be no output
652 | n == 127 -> return (rc, True)
653 | otherwise -> return (rc, False))
654 -- Should 'rawSystem' generate an IO exception indicating that
655 -- 'pgm' couldn't be run rather than a funky return code, catch
656 -- this here (the win32 version does this, but it doesn't hurt
657 -- to test for this in general.)
659 if IO.isDoesNotExistError err
660 then return (ExitFailure 1, True)
662 case (doesn'tExist, exit_code) of
663 (True, _) -> ghcError (InstallationError ("could not execute: " ++ pgm))
664 (_, ExitSuccess) -> return ()
665 _ -> ghcError (PhaseFailed phase_name exit_code)
667 builderMainLoop :: DynFlags -> (String -> String) -> FilePath
668 -> [String] -> Maybe [(String, String)]
670 builderMainLoop dflags filter_fn pgm real_args mb_env = do
672 (hStdIn, hStdOut, hStdErr, hProcess) <- runInteractiveProcess pgm real_args Nothing mb_env
674 -- and run a loop piping the output from the compiler to the log_action in DynFlags
675 hSetBuffering hStdOut LineBuffering
676 hSetBuffering hStdErr LineBuffering
677 _ <- forkIO (readerProc chan hStdOut filter_fn)
678 _ <- forkIO (readerProc chan hStdErr filter_fn)
679 -- we don't want to finish until 2 streams have been completed
680 -- (stdout and stderr)
681 -- nor until 1 exit code has been retrieved.
682 rc <- loop chan hProcess (2::Integer) (1::Integer) ExitSuccess
683 -- after that, we're done here.
689 -- status starts at zero, and increments each time either
690 -- a reader process gets EOF, or the build proc exits. We wait
691 -- for all of these to happen (status==3).
692 -- ToDo: we should really have a contingency plan in case any of
693 -- the threads dies, such as a timeout.
694 loop _ _ 0 0 exitcode = return exitcode
695 loop chan hProcess t p exitcode = do
697 then getProcessExitCode hProcess
700 Just code -> loop chan hProcess t (p-1) code
706 log_action dflags SevInfo noSrcSpan defaultUserStyle msg
707 loop chan hProcess t p exitcode
708 BuildError loc msg -> do
709 log_action dflags SevError (mkSrcSpan loc loc) defaultUserStyle msg
710 loop chan hProcess t p exitcode
712 loop chan hProcess (t-1) p exitcode
713 | otherwise -> loop chan hProcess t p exitcode
715 readerProc :: Chan BuildMessage -> Handle -> (String -> String) -> IO ()
716 readerProc chan hdl filter_fn =
717 (do str <- hGetContents hdl
718 loop (linesPlatform (filter_fn str)) Nothing)
721 -- ToDo: check errors more carefully
722 -- ToDo: in the future, the filter should be implemented as
723 -- a stream transformer.
725 loop [] Nothing = return ()
726 loop [] (Just err) = writeChan chan err
729 Just err@(BuildError srcLoc msg)
730 | leading_whitespace l -> do
731 loop ls (Just (BuildError srcLoc (msg $$ text l)))
737 _ -> panic "readerProc/loop"
740 = case parseError l of
742 writeChan chan (BuildMsg (text l))
744 Just (file, lineNum, colNum, msg) -> do
745 let srcLoc = mkSrcLoc (mkFastString file) lineNum colNum
746 loop ls (Just (BuildError srcLoc (text msg)))
748 leading_whitespace [] = False
749 leading_whitespace (x:_) = isSpace x
751 parseError :: String -> Maybe (String, Int, Int, String)
752 parseError s0 = case breakColon s0 of
753 Just (filename, s1) ->
754 case breakIntColon s1 of
755 Just (lineNum, s2) ->
756 case breakIntColon s2 of
757 Just (columnNum, s3) ->
758 Just (filename, lineNum, columnNum, s3)
760 Just (filename, lineNum, 0, s2)
764 breakColon :: String -> Maybe (String, String)
765 breakColon xs = case break (':' ==) xs of
766 (ys, _:zs) -> Just (ys, zs)
769 breakIntColon :: String -> Maybe (Int, String)
770 breakIntColon xs = case break (':' ==) xs of
772 | not (null ys) && all isAscii ys && all isDigit ys ->
778 | BuildError !SrcLoc !SDoc
781 traceCmd :: DynFlags -> String -> String -> IO () -> IO ()
782 -- a) trace the command (at two levels of verbosity)
783 -- b) don't do it at all if dry-run is set
784 traceCmd dflags phase_name cmd_line action
785 = do { let verb = verbosity dflags
786 ; showPass dflags phase_name
787 ; debugTraceMsg dflags 3 (text cmd_line)
791 ; unless (dopt Opt_DryRun dflags) $ do {
794 ; action `catchIO` handle_exn verb
797 handle_exn _verb exn = do { debugTraceMsg dflags 2 (char '\n')
798 ; debugTraceMsg dflags 2 (ptext (sLit "Failed:") <+> text cmd_line <+> text (show exn))
799 ; ghcError (PhaseFailed phase_name (ExitFailure 1)) }
802 %************************************************************************
804 \subsection{Support code}
806 %************************************************************************
809 -----------------------------------------------------------------------------
810 -- Define getBaseDir :: IO (Maybe String)
812 getBaseDir :: IO (Maybe String)
813 #if defined(mingw32_HOST_OS)
814 -- Assuming we are running ghc, accessed by path $(stuff)/bin/ghc.exe,
815 -- return the path $(stuff)/lib.
816 getBaseDir = do let len = (2048::Int) -- plenty, PATH_MAX is 512 under Win32.
817 buf <- mallocArray len
818 ret <- getModuleFileName nullPtr buf len
819 if ret == 0 then free buf >> return Nothing
820 else do s <- peekCString buf
822 return (Just (rootDir s))
824 rootDir s = case splitFileName $ normalise s of
826 | lower ghc_exe `elem` ["ghc.exe",
830 case splitFileName $ takeDirectory d of
831 -- ghc is in $topdir/bin/ghc.exe
832 (d', bin) | lower bin == "bin" -> takeDirectory d' </> "lib"
835 where fail = panic ("can't decompose ghc.exe path: " ++ show s)
838 foreign import stdcall unsafe "GetModuleFileNameA"
839 getModuleFileName :: Ptr () -> CString -> Int -> IO Int32
841 getBaseDir = return Nothing
844 #ifdef mingw32_HOST_OS
845 foreign import ccall unsafe "_getpid" getProcessID :: IO Int -- relies on Int == Int32 on Windows
847 getProcessID :: IO Int
848 getProcessID = System.Posix.Internals.c_getpid >>= return . fromIntegral
851 -- Divvy up text stream into lines, taking platform dependent
852 -- line termination into account.
853 linesPlatform :: String -> [String]
854 #if !defined(mingw32_HOST_OS)
855 linesPlatform ls = lines ls
857 linesPlatform "" = []
860 (as,xs1) -> as : linesPlatform xs1
862 lineBreak "" = ("","")
863 lineBreak ('\r':'\n':xs) = ([],xs)
864 lineBreak ('\n':xs) = ([],xs)
865 lineBreak (x:xs) = let (as,bs) = lineBreak xs in (x:as,bs)