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"
49 import Control.Exception
55 import System.Environment
57 import SYSTEM_IO_ERROR as IO
58 import System.Directory
62 -- GHC <= 4.08 didn't have rawSystem, and runs into problems with long command
63 -- lines on mingw32, so we disallow it now.
64 #if __GLASGOW_HASKELL__ < 500
65 #error GHC >= 5.00 is required for bootstrapping GHC
68 #ifndef mingw32_HOST_OS
69 #if __GLASGOW_HASKELL__ > 504
70 import qualified System.Posix.Internals
72 import qualified Posix
74 #else /* Must be Win32 */
75 import List ( isPrefixOf )
76 import Util ( dropList )
78 import CString ( CString, peekCString )
83 #if __GLASGOW_HASKELL__ < 603
84 -- rawSystem comes from libghccompat.a in stage1
85 import Compat.RawSystem ( rawSystem )
86 import GHC.IOBase ( IOErrorType(..) )
88 import System.Process ( runInteractiveProcess, getProcessExitCode )
89 import Control.Concurrent( forkIO, newChan, readChan, writeChan )
90 import Data.Char ( isSpace )
91 import FastString ( mkFastString )
92 import SrcLoc ( SrcLoc, mkSrcLoc, noSrcSpan, mkSrcSpan )
97 The configuration story
98 ~~~~~~~~~~~~~~~~~~~~~~~
100 GHC needs various support files (library packages, RTS etc), plus
101 various auxiliary programs (cp, gcc, etc). It finds these in one
104 * When running as an *installed program*, GHC finds most of this support
105 stuff in the installed library tree. The path to this tree is passed
106 to GHC via the -B flag, and given to initSysTools .
108 * When running *in-place* in a build tree, GHC finds most of this support
109 stuff in the build tree. The path to the build tree is, again passed
112 GHC tells which of the two is the case by seeing whether package.conf
113 is in TopDir [installed] or in TopDir/ghc/driver [inplace] (what a hack).
116 SysTools.initSysProgs figures out exactly where all the auxiliary programs
117 are, and initialises mutable variables to make it easy to call them.
118 To to this, it makes use of definitions in Config.hs, which is a Haskell
119 file containing variables whose value is figured out by the build system.
121 Config.hs contains two sorts of things
123 cGCC, The *names* of the programs
126 etc They do *not* include paths
129 cUNLIT_DIR_REL The *path* to the directory containing unlit, split etc
130 cSPLIT_DIR_REL *relative* to the root of the build tree,
131 for use when running *in-place* in a build tree (only)
135 ---------------------------------------------
136 NOTES for an ALTERNATIVE scheme (i.e *not* what is currently implemented):
138 Another hair-brained scheme for simplifying the current tool location
139 nightmare in GHC: Simon originally suggested using another
140 configuration file along the lines of GCC's specs file - which is fine
141 except that it means adding code to read yet another configuration
142 file. What I didn't notice is that the current package.conf is
143 general enough to do this:
146 {name = "tools", import_dirs = [], source_dirs = [],
147 library_dirs = [], hs_libraries = [], extra_libraries = [],
148 include_dirs = [], c_includes = [], package_deps = [],
149 extra_ghc_opts = ["-pgmc/usr/bin/gcc","-pgml${topdir}/bin/unlit", ... etc.],
150 extra_cc_opts = [], extra_ld_opts = []}
152 Which would have the advantage that we get to collect together in one
153 place the path-specific package stuff with the path-specific tool
156 ---------------------------------------------
158 %************************************************************************
160 \subsection{Initialisation}
162 %************************************************************************
165 initSysTools :: Maybe String -- Maybe TopDir path (without the '-B' prefix)
168 -> IO DynFlags -- Set all the mutable variables above, holding
169 -- (a) the system programs
170 -- (b) the package-config file
171 -- (c) the GHC usage message
174 initSysTools mbMinusB dflags
175 = do { (am_installed, top_dir) <- findTopDir mbMinusB
177 -- for "installed" this is the root of GHC's support files
178 -- for "in-place" it is the root of the build tree
179 -- NB: top_dir is assumed to be in standard Unix
180 -- format, '/' separated
182 ; let installed, installed_bin :: FilePath -> FilePath
183 installed_bin pgm = pgmPath top_dir pgm
184 installed file = pgmPath top_dir file
185 inplace dir pgm = pgmPath (top_dir `joinFileName`
186 cPROJECT_DIR `joinFileName` dir) pgm
189 | am_installed = installed "package.conf"
190 | otherwise = inplace cGHC_DRIVER_DIR_REL "package.conf.inplace"
193 | am_installed = installed "ghc-usage.txt"
194 | otherwise = inplace cGHC_DRIVER_DIR_REL "ghc-usage.txt"
197 | am_installed = installed "ghci-usage.txt"
198 | otherwise = inplace cGHC_DRIVER_DIR_REL "ghci-usage.txt"
200 -- For all systems, unlit, split, mangle are GHC utilities
201 -- architecture-specific stuff is done when building Config.hs
203 | am_installed = installed_bin cGHC_UNLIT_PGM
204 | otherwise = inplace cGHC_UNLIT_DIR_REL cGHC_UNLIT_PGM
206 -- split and mangle are Perl scripts
208 | am_installed = installed_bin cGHC_SPLIT_PGM
209 | otherwise = inplace cGHC_SPLIT_DIR_REL cGHC_SPLIT_PGM
212 | am_installed = installed_bin cGHC_MANGLER_PGM
213 | otherwise = inplace cGHC_MANGLER_DIR_REL cGHC_MANGLER_PGM
215 ; let dflags0 = defaultDynFlags
216 #ifndef mingw32_HOST_OS
217 -- check whether TMPDIR is set in the environment
218 ; e_tmpdir <- IO.try (getEnv "TMPDIR") -- fails if not set
220 -- On Win32, consult GetTempPath() for a temp dir.
221 -- => it first tries TMP, TEMP, then finally the
222 -- Windows directory(!). The directory is in short-path
226 let len = (2048::Int)
227 buf <- mallocArray len
228 ret <- getTempPath len buf
230 -- failed, consult TMPDIR.
238 ; let dflags1 = case e_tmpdir of
240 Right d -> setTmpDir d dflags0
242 -- Check that the package config exists
243 ; config_exists <- doesFileExist pkgconfig_path
244 ; when (not config_exists) $
245 throwDyn (InstallationError
246 ("Can't find package.conf as " ++ pkgconfig_path))
248 #if defined(mingw32_HOST_OS)
249 -- WINDOWS-SPECIFIC STUFF
250 -- On Windows, gcc and friends are distributed with GHC,
251 -- so when "installed" we look in TopDir/bin
252 -- When "in-place" we look wherever the build-time configure
254 -- When "install" we tell gcc where its specs file + exes are (-B)
255 -- and also some places to pick up include files. We need
256 -- to be careful to put all necessary exes in the -B place
257 -- (as, ld, cc1, etc) since if they don't get found there, gcc
258 -- then tries to run unadorned "as", "ld", etc, and will
259 -- pick up whatever happens to be lying around in the path,
260 -- possibly including those from a cygwin install on the target,
261 -- which is exactly what we're trying to avoid.
262 ; let gcc_b_arg = Option ("-B" ++ installed "gcc-lib/")
264 | am_installed = (installed_bin "gcc", [gcc_b_arg])
265 | otherwise = (cGCC, [])
266 -- The trailing "/" is absolutely essential; gcc seems
267 -- to construct file names simply by concatenating to
268 -- this -B path with no extra slash We use "/" rather
269 -- than "\\" because otherwise "\\\" is mangled
270 -- later on; although gcc_args are in NATIVE format,
272 -- (see comments with declarations of global variables)
274 -- The quotes round the -B argument are in case TopDir
277 perl_path | am_installed = installed_bin cGHC_PERL
278 | otherwise = cGHC_PERL
280 -- 'touch' is a GHC util for Windows, and similarly unlit, mangle
281 ; let touch_path | am_installed = installed_bin cGHC_TOUCHY_PGM
282 | otherwise = inplace cGHC_TOUCHY_DIR_REL cGHC_TOUCHY_PGM
284 -- On Win32 we don't want to rely on #!/bin/perl, so we prepend
285 -- a call to Perl to get the invocation of split and mangle
286 ; let (split_prog, split_args) = (perl_path, [Option split_script])
287 (mangle_prog, mangle_args) = (perl_path, [Option mangle_script])
289 ; let (mkdll_prog, mkdll_args)
291 (pgmPath (installed "gcc-lib/") cMKDLL,
292 [ Option "--dlltool-name",
293 Option (pgmPath (installed "gcc-lib/") "dlltool"),
294 Option "--driver-name",
295 Option gcc_prog, gcc_b_arg ])
296 | otherwise = (cMKDLL, [])
298 -- UNIX-SPECIFIC STUFF
299 -- On Unix, the "standard" tools are assumed to be
300 -- in the same place whether we are running "in-place" or "installed"
301 -- That place is wherever the build-time configure script found them.
302 ; let gcc_prog = cGCC
305 mkdll_prog = panic "Can't build DLLs on a non-Win32 system"
308 -- On Unix, scripts are invoked using the '#!' method. Binary
309 -- installations of GHC on Unix place the correct line on the front
310 -- of the script at installation time, so we don't want to wire-in
311 -- our knowledge of $(PERL) on the host system here.
312 ; let (split_prog, split_args) = (split_script, [])
313 (mangle_prog, mangle_args) = (mangle_script, [])
316 -- cpp is derived from gcc on all platforms
317 -- HACK, see setPgmP below. We keep 'words' here to remember to fix
318 -- Config.hs one day.
319 ; let cpp_path = (gcc_prog, gcc_args ++
320 (Option "-E"):(map Option (words cRAWCPP_FLAGS)))
322 -- For all systems, copy and remove are provided by the host
323 -- system; architecture-specific stuff is done when building Config.hs
324 ; let cp_path = cGHC_CP
326 -- Other things being equal, as and ld are simply gcc
327 ; let (as_prog,as_args) = (gcc_prog,gcc_args)
328 (ld_prog,ld_args) = (gcc_prog,gcc_args)
331 ghcUsagePath = ghc_usage_msg_path,
332 ghciUsagePath = ghci_usage_msg_path,
334 systemPackageConfig = pkgconfig_path,
338 pgm_c = (gcc_prog,gcc_args),
339 pgm_m = (mangle_prog,mangle_args),
340 pgm_s = (split_prog,split_args),
341 pgm_a = (as_prog,as_args),
342 pgm_l = (ld_prog,ld_args),
343 pgm_dll = (mkdll_prog,mkdll_args),
345 pgm_sysman = top_dir ++ "/ghc/rts/parallel/SysMan"
346 -- Hans: this isn't right in general, but you can
347 -- elaborate it in the same way as the others
351 #if defined(mingw32_HOST_OS)
352 foreign import stdcall unsafe "GetTempPathA" getTempPath :: Int -> CString -> IO Int32
358 -- for "installed" this is the root of GHC's support files
359 -- for "in-place" it is the root of the build tree
362 -- 1. Set proto_top_dir
363 -- if there is no given TopDir path, get the directory
364 -- where GHC is running (only on Windows)
366 -- 2. If package.conf exists in proto_top_dir, we are running
367 -- installed; and TopDir = proto_top_dir
369 -- 3. Otherwise we are running in-place, so
370 -- proto_top_dir will be /...stuff.../ghc/compiler
371 -- Set TopDir to /...stuff..., which is the root of the build tree
373 -- This is very gruesome indeed
375 findTopDir :: Maybe String -- Maybe TopDir path (without the '-B' prefix).
376 -> IO (Bool, -- True <=> am installed, False <=> in-place
377 String) -- TopDir (in Unix format '/' separated)
380 = do { top_dir <- get_proto
381 -- Discover whether we're running in a build tree or in an installation,
382 -- by looking for the package configuration file.
383 ; am_installed <- doesFileExist (top_dir `joinFileName` "package.conf")
385 ; return (am_installed, top_dir)
388 -- get_proto returns a Unix-format path (relying on getBaseDir to do so too)
389 get_proto = case mbMinusB of
390 Just minusb -> return (normalisePath minusb)
392 -> do maybe_exec_dir <- getBaseDir -- Get directory of executable
393 case maybe_exec_dir of -- (only works on Windows;
394 -- returns Nothing on Unix)
395 Nothing -> throwDyn (InstallationError "missing -B<dir> option")
396 Just dir -> return dir
400 %************************************************************************
402 \subsection{Running an external program}
404 %************************************************************************
408 runUnlit :: DynFlags -> [Option] -> IO ()
409 runUnlit dflags args = do
411 runSomething dflags "Literate pre-processor" p args
413 runCpp :: DynFlags -> [Option] -> IO ()
414 runCpp dflags args = do
415 let (p,args0) = pgm_P dflags
416 runSomething dflags "C pre-processor" p (args0 ++ args)
418 runPp :: DynFlags -> [Option] -> IO ()
419 runPp dflags args = do
421 runSomething dflags "Haskell pre-processor" p args
423 runCc :: DynFlags -> [Option] -> IO ()
424 runCc dflags args = do
425 let (p,args0) = pgm_c dflags
426 runSomethingFiltered dflags cc_filter "C Compiler" p (args0++args)
428 -- discard some harmless warnings from gcc that we can't turn off
429 cc_filter str = unlines (do_filter (lines str))
433 | (w:rest) <- dropWhile (isJust .matchRegex r_from) ls,
434 isJust (matchRegex r_warn w)
439 r_from = mkRegex "from.*:[0-9]+"
440 r_warn = mkRegex "warning: call-clobbered register used"
442 runMangle :: DynFlags -> [Option] -> IO ()
443 runMangle dflags args = do
444 let (p,args0) = pgm_m dflags
445 runSomething dflags "Mangler" p (args0++args)
447 runSplit :: DynFlags -> [Option] -> IO ()
448 runSplit dflags args = do
449 let (p,args0) = pgm_s dflags
450 runSomething dflags "Splitter" p (args0++args)
452 runAs :: DynFlags -> [Option] -> IO ()
453 runAs dflags args = do
454 let (p,args0) = pgm_a dflags
455 runSomething dflags "Assembler" p (args0++args)
457 runLink :: DynFlags -> [Option] -> IO ()
458 runLink dflags args = do
459 let (p,args0) = pgm_l dflags
460 runSomething dflags "Linker" p (args0++args)
462 runMkDLL :: DynFlags -> [Option] -> IO ()
463 runMkDLL dflags args = do
464 let (p,args0) = pgm_dll dflags
465 runSomething dflags "Make DLL" p (args0++args)
467 touch :: DynFlags -> String -> String -> IO ()
468 touch dflags purpose arg =
469 runSomething dflags purpose (pgm_T dflags) [FileOption "" arg]
471 copy :: DynFlags -> String -> String -> String -> IO ()
472 copy dflags purpose from to = do
473 showPass dflags purpose
475 h <- openFile to WriteMode
476 ls <- readFile from -- inefficient, but it'll do for now.
477 -- ToDo: speed up via slurping.
482 %************************************************************************
484 \subsection{Managing temporary files
486 %************************************************************************
489 GLOBAL_VAR(v_FilesToClean, [], [String] )
490 GLOBAL_VAR(v_DirsToClean, emptyFM, FiniteMap FilePath FilePath )
494 cleanTempDirs :: DynFlags -> IO ()
496 = do ds <- readIORef v_DirsToClean
497 removeTmpDirs dflags (eltsFM ds)
498 writeIORef v_DirsToClean emptyFM
500 cleanTempFiles :: DynFlags -> IO ()
501 cleanTempFiles dflags
502 = do fs <- readIORef v_FilesToClean
503 removeTmpFiles dflags fs
504 writeIORef v_FilesToClean []
506 cleanTempFilesExcept :: DynFlags -> [FilePath] -> IO ()
507 cleanTempFilesExcept dflags dont_delete
508 = do files <- readIORef v_FilesToClean
509 let (to_keep, to_delete) = partition (`elem` dont_delete) files
510 removeTmpFiles dflags to_delete
511 writeIORef v_FilesToClean to_keep
514 -- find a temporary name that doesn't already exist.
515 newTempName :: DynFlags -> Suffix -> IO FilePath
516 newTempName dflags extn
517 = do d <- getTempDir dflags
519 findTempName (d ++ "/ghc" ++ show x ++ "_") 0
521 findTempName prefix x
522 = do let filename = (prefix ++ show x) `joinFileExt` extn
523 b <- doesFileExist filename
524 if b then findTempName prefix (x+1)
525 else do consIORef v_FilesToClean filename -- clean it up later
528 -- return our temporary directory within tmp_dir, creating one if we
529 -- don't have one yet
530 getTempDir :: DynFlags -> IO FilePath
531 getTempDir dflags@(DynFlags{tmpDir=tmp_dir})
532 = do mapping <- readIORef v_DirsToClean
533 case lookupFM mapping tmp_dir of
536 let prefix = tmp_dir ++ "/ghc" ++ show x ++ "_"
538 = let dirname = prefix ++ show x
539 in do createDirectory dirname
540 let mapping' = addToFM mapping tmp_dir dirname
541 writeIORef v_DirsToClean mapping'
542 debugTraceMsg dflags 2 (ptext SLIT("Created temporary directory:") <+> text dirname)
545 if isAlreadyExistsError e
551 addFilesToClean :: [FilePath] -> IO ()
552 -- May include wildcards [used by DriverPipeline.run_phase SplitMangle]
553 addFilesToClean files = mapM_ (consIORef v_FilesToClean) files
555 removeTmpDirs :: DynFlags -> [FilePath] -> IO ()
556 removeTmpDirs dflags ds
557 = traceCmd dflags "Deleting temp dirs"
558 ("Deleting: " ++ unwords ds)
559 (mapM_ (removeWith dflags removeDirectory) ds)
561 removeTmpFiles :: DynFlags -> [FilePath] -> IO ()
562 removeTmpFiles dflags fs
564 traceCmd dflags "Deleting temp files"
565 ("Deleting: " ++ unwords deletees)
566 (mapM_ (removeWith dflags removeFile) deletees)
568 -- Flat out refuse to delete files that are likely to be source input
569 -- files (is there a worse bug than having a compiler delete your source
572 -- Deleting source files is a sign of a bug elsewhere, so prominently flag
575 | null non_deletees = act
577 putMsg dflags (text "WARNING - NOT deleting source files:" <+> hsep (map text non_deletees))
580 (non_deletees, deletees) = partition isHaskellUserSrcFilename fs
582 removeWith :: DynFlags -> (FilePath -> IO ()) -> FilePath -> IO ()
583 removeWith dflags remover f = remover f `IO.catch`
585 let msg = if isDoesNotExistError e
586 then ptext SLIT("Warning: deleting non-existent") <+> text f
587 else ptext SLIT("Warning: exception raised when deleting")
590 in debugTraceMsg dflags 2 msg
593 -----------------------------------------------------------------------------
594 -- Running an external program
596 runSomething :: DynFlags
597 -> String -- For -v message
598 -> String -- Command name (possibly a full path)
599 -- assumed already dos-ified
600 -> [Option] -- Arguments
601 -- runSomething will dos-ify them
604 runSomething dflags phase_name pgm args =
605 runSomethingFiltered dflags id phase_name pgm args
608 :: DynFlags -> (String->String) -> String -> String -> [Option] -> IO ()
610 runSomethingFiltered dflags filter_fn phase_name pgm args = do
611 let real_args = filter notNull (map showOpt args)
612 traceCmd dflags phase_name (unwords (pgm:real_args)) $ do
613 (exit_code, doesn'tExist) <-
615 rc <- builderMainLoop dflags filter_fn pgm real_args
617 ExitSuccess{} -> return (rc, False)
619 -- rawSystem returns (ExitFailure 127) if the exec failed for any
620 -- reason (eg. the program doesn't exist). This is the only clue
621 -- we have, but we need to report something to the user because in
622 -- the case of a missing program there will otherwise be no output
624 | n == 127 -> return (rc, True)
625 | otherwise -> return (rc, False))
626 -- Should 'rawSystem' generate an IO exception indicating that
627 -- 'pgm' couldn't be run rather than a funky return code, catch
628 -- this here (the win32 version does this, but it doesn't hurt
629 -- to test for this in general.)
631 if IO.isDoesNotExistError err
632 #if defined(mingw32_HOST_OS) && __GLASGOW_HASKELL__ < 604
633 -- the 'compat' version of rawSystem under mingw32 always
634 -- maps 'errno' to EINVAL to failure.
635 || case (ioeGetErrorType err ) of { InvalidArgument{} -> True ; _ -> False}
637 then return (ExitFailure 1, True)
639 case (doesn'tExist, exit_code) of
640 (True, _) -> throwDyn (InstallationError ("could not execute: " ++ pgm))
641 (_, ExitSuccess) -> return ()
642 _ -> throwDyn (PhaseFailed phase_name exit_code)
646 #if __GLASGOW_HASKELL__ < 603
647 builderMainLoop dflags filter_fn pgm real_args = do
648 rawSystem pgm real_args
650 builderMainLoop dflags filter_fn pgm real_args = do
652 (hStdIn, hStdOut, hStdErr, hProcess) <- runInteractiveProcess pgm real_args Nothing Nothing
654 -- and run a loop piping the output from the compiler to the log_action in DynFlags
655 hSetBuffering hStdOut LineBuffering
656 hSetBuffering hStdErr LineBuffering
657 forkIO (readerProc chan hStdOut filter_fn)
658 forkIO (readerProc chan hStdErr filter_fn)
659 rc <- loop chan hProcess 2 1 ExitSuccess
665 -- status starts at zero, and increments each time either
666 -- a reader process gets EOF, or the build proc exits. We wait
667 -- for all of these to happen (status==3).
668 -- ToDo: we should really have a contingency plan in case any of
669 -- the threads dies, such as a timeout.
670 loop chan hProcess 0 0 exitcode = return exitcode
671 loop chan hProcess t p exitcode = do
673 then getProcessExitCode hProcess
676 Just code -> loop chan hProcess t (p-1) code
682 log_action dflags SevInfo noSrcSpan defaultUserStyle msg
683 loop chan hProcess t p exitcode
684 BuildError loc msg -> do
685 log_action dflags SevError (mkSrcSpan loc loc) defaultUserStyle msg
686 loop chan hProcess t p exitcode
688 loop chan hProcess (t-1) p exitcode
689 | otherwise -> loop chan hProcess t p exitcode
691 readerProc chan hdl filter_fn =
692 (do str <- hGetContents hdl
693 loop (linesPlatform (filter_fn str)) Nothing)
696 -- ToDo: check errors more carefully
697 -- ToDo: in the future, the filter should be implemented as
698 -- a stream transformer.
700 loop [] Nothing = return ()
701 loop [] (Just err) = writeChan chan err
704 Just err@(BuildError srcLoc msg)
705 | leading_whitespace l -> do
706 loop ls (Just (BuildError srcLoc (msg $$ text l)))
714 = case matchRegex errRegex l of
716 writeChan chan (BuildMsg (text l))
718 Just (file':lineno':colno':msg:_) -> do
719 let file = mkFastString file'
720 lineno = read lineno'::Int
721 colno = case colno' of
723 _ -> read (init colno') :: Int
724 srcLoc = mkSrcLoc file lineno colno
725 loop ls (Just (BuildError srcLoc (text msg)))
727 leading_whitespace [] = False
728 leading_whitespace (x:_) = isSpace x
730 errRegex = mkRegex "^([^:]*):([0-9]+):([0-9]+:)?(.*)"
734 | BuildError !SrcLoc !SDoc
738 showOpt (FileOption pre f) = pre ++ platformPath f
739 showOpt (Option "") = ""
740 showOpt (Option s) = s
742 traceCmd :: DynFlags -> String -> String -> IO () -> IO ()
743 -- a) trace the command (at two levels of verbosity)
744 -- b) don't do it at all if dry-run is set
745 traceCmd dflags phase_name cmd_line action
746 = do { let verb = verbosity dflags
747 ; showPass dflags phase_name
748 ; debugTraceMsg dflags 3 (text cmd_line)
752 ; unless (dopt Opt_DryRun dflags) $ do {
755 ; action `IO.catch` handle_exn verb
758 handle_exn verb exn = do { debugTraceMsg dflags 2 (char '\n')
759 ; debugTraceMsg dflags 2 (ptext SLIT("Failed:") <+> text cmd_line <+> text (show exn))
760 ; throwDyn (PhaseFailed phase_name (ExitFailure 1)) }
763 %************************************************************************
765 \subsection{Support code}
767 %************************************************************************
770 -----------------------------------------------------------------------------
771 -- Define getBaseDir :: IO (Maybe String)
773 getBaseDir :: IO (Maybe String)
774 #if defined(mingw32_HOST_OS)
775 -- Assuming we are running ghc, accessed by path $()/bin/ghc.exe,
776 -- return the path $(stuff). Note that we drop the "bin/" directory too.
777 getBaseDir = do let len = (2048::Int) -- plenty, PATH_MAX is 512 under Win32.
778 buf <- mallocArray len
779 ret <- getModuleFileName nullPtr buf len
780 if ret == 0 then free buf >> return Nothing
781 else do s <- peekCString buf
783 return (Just (rootDir s))
785 rootDir s = reverse (dropList "/bin/ghc.exe" (reverse (normalisePath s)))
787 foreign import stdcall unsafe "GetModuleFileNameA"
788 getModuleFileName :: Ptr () -> CString -> Int -> IO Int32
790 getBaseDir = return Nothing
793 #ifdef mingw32_HOST_OS
794 foreign import ccall unsafe "_getpid" getProcessID :: IO Int -- relies on Int == Int32 on Windows
795 #elif __GLASGOW_HASKELL__ > 504
796 getProcessID :: IO Int
797 getProcessID = System.Posix.Internals.c_getpid >>= return . fromIntegral
799 getProcessID :: IO Int
800 getProcessID = Posix.getProcessID
803 -- Divvy up text stream into lines, taking platform dependent
804 -- line termination into account.
805 linesPlatform :: String -> [String]
806 #if !defined(mingw32_HOST_OS)
807 linesPlatform ls = lines ls
809 linesPlatform "" = []
812 (as,xs1) -> as : linesPlatform xs1
814 lineBreak "" = ("","")
815 lineBreak ('\r':'\n':xs) = ([],xs)
816 lineBreak ('\n':xs) = ([],xs)
817 lineBreak (x:xs) = let (as,bs) = lineBreak xs in (x:as,bs)