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 ()
22 touch, -- String -> String -> IO ()
27 -- Temporary-file management
30 cleanTempDirs, cleanTempFiles, cleanTempFilesExcept,
37 #include "HsVersions.h"
52 import System.Environment
53 import System.FilePath
55 import System.IO.Error as IO
56 import System.Directory
61 #ifndef mingw32_HOST_OS
62 import qualified System.Posix.Internals
63 #else /* Must be Win32 */
65 import CString ( CString, peekCString )
68 import System.Process ( runInteractiveProcess, getProcessExitCode )
69 import Control.Concurrent
71 import SrcLoc ( SrcLoc, mkSrcLoc, noSrcSpan, mkSrcSpan )
74 How GHC finds its files
75 ~~~~~~~~~~~~~~~~~~~~~~~
79 GHC needs various support files (library packages, RTS etc), plus
80 various auxiliary programs (cp, gcc, etc). It starts by finding topdir,
81 the root of GHC's support files
84 - ghc always has a shell wrapper that passes a -B<dir> option
87 - ghc never has a shell wrapper.
88 - we can find the location of the ghc binary, which is
89 $topdir/bin/<something>.exe
90 where <something> may be "ghc", "ghc-stage2", or similar
91 - we strip off the "bin/<something>.exe" to leave $topdir.
93 from topdir we can find package.conf, ghc-asm, etc.
96 SysTools.initSysProgs figures out exactly where all the auxiliary programs
97 are, and initialises mutable variables to make it easy to call them.
98 To to this, it makes use of definitions in Config.hs, which is a Haskell
99 file containing variables whose value is figured out by the build system.
101 Config.hs contains two sorts of things
103 cGCC, The *names* of the programs
106 etc They do *not* include paths
109 cUNLIT_DIR The *path* to the directory containing unlit, split etc
110 cSPLIT_DIR *relative* to the root of the build tree,
111 for use when running *in-place* in a build tree (only)
115 ---------------------------------------------
116 NOTES for an ALTERNATIVE scheme (i.e *not* what is currently implemented):
118 Another hair-brained scheme for simplifying the current tool location
119 nightmare in GHC: Simon originally suggested using another
120 configuration file along the lines of GCC's specs file - which is fine
121 except that it means adding code to read yet another configuration
122 file. What I didn't notice is that the current package.conf is
123 general enough to do this:
126 {name = "tools", import_dirs = [], source_dirs = [],
127 library_dirs = [], hs_libraries = [], extra_libraries = [],
128 include_dirs = [], c_includes = [], package_deps = [],
129 extra_ghc_opts = ["-pgmc/usr/bin/gcc","-pgml${topdir}/bin/unlit", ... etc.],
130 extra_cc_opts = [], extra_ld_opts = []}
132 Which would have the advantage that we get to collect together in one
133 place the path-specific package stuff with the path-specific tool
136 ---------------------------------------------
138 %************************************************************************
140 \subsection{Initialisation}
142 %************************************************************************
145 initSysTools :: Maybe String -- Maybe TopDir path (without the '-B' prefix)
148 -> IO DynFlags -- Set all the mutable variables above, holding
149 -- (a) the system programs
150 -- (b) the package-config file
151 -- (c) the GHC usage message
154 initSysTools mbMinusB dflags0
155 = do { top_dir <- findTopDir mbMinusB
157 -- NB: top_dir is assumed to be in standard Unix
158 -- format, '/' separated
160 ; let installed :: FilePath -> FilePath
161 installed file = top_dir </> file
162 installed_mingw_bin file = top_dir </> ".." </> "mingw" </> "bin" </> file
164 ; let pkgconfig_path = installed "package.conf"
165 ghc_usage_msg_path = installed "ghc-usage.txt"
166 ghci_usage_msg_path = installed "ghci-usage.txt"
168 -- For all systems, unlit, split, mangle are GHC utilities
169 -- architecture-specific stuff is done when building Config.hs
170 unlit_path = installed cGHC_UNLIT_PGM
172 -- split and mangle are Perl scripts
173 split_script = installed cGHC_SPLIT_PGM
174 mangle_script = installed cGHC_MANGLER_PGM
176 windres_path = installed_mingw_bin "windres"
178 ; tmpdir <- getTemporaryDirectory
179 ; let dflags1 = setTmpDir tmpdir dflags0
181 -- Check that the package config exists
182 ; config_exists <- doesFileExist pkgconfig_path
183 ; when (not config_exists) $
184 ghcError (InstallationError
185 ("Can't find package.conf as " ++ pkgconfig_path))
187 -- On Windows, mingw is distributed with GHC,
188 -- so we look in TopDir/../mingw/bin
191 | isWindowsHost = installed_mingw_bin "gcc"
194 | isWindowsHost = installed cGHC_PERL
195 | otherwise = cGHC_PERL
196 -- 'touch' is a GHC util for Windows
198 | isWindowsHost = installed cGHC_TOUCHY_PGM
199 | otherwise = "touch"
200 -- On Win32 we don't want to rely on #!/bin/perl, so we prepend
201 -- a call to Perl to get the invocation of split and mangle.
202 -- On Unix, scripts are invoked using the '#!' method. Binary
203 -- installations of GHC on Unix place the correct line on the
204 -- front of the script at installation time, so we don't want
205 -- to wire-in our knowledge of $(PERL) on the host system here.
206 (split_prog, split_args)
207 | isWindowsHost = (perl_path, [Option split_script])
208 | otherwise = (split_script, [])
209 (mangle_prog, mangle_args)
210 | isWindowsHost = (perl_path, [Option mangle_script])
211 | otherwise = (mangle_script, [])
212 (mkdll_prog, mkdll_args)
214 = panic "Can't build DLLs on a non-Win32 system"
216 (installed_mingw_bin cMKDLL, [])
218 -- cpp is derived from gcc on all platforms
219 -- HACK, see setPgmP below. We keep 'words' here to remember to fix
220 -- Config.hs one day.
221 ; let cpp_path = (gcc_prog,
222 (Option "-E"):(map Option (words cRAWCPP_FLAGS)))
224 -- Other things being equal, as and ld are simply gcc
225 ; let as_prog = gcc_prog
229 ghcUsagePath = ghc_usage_msg_path,
230 ghciUsagePath = ghci_usage_msg_path,
232 systemPackageConfig = pkgconfig_path,
236 pgm_c = (gcc_prog,[]),
237 pgm_m = (mangle_prog,mangle_args),
238 pgm_s = (split_prog,split_args),
239 pgm_a = (as_prog,[]),
240 pgm_l = (ld_prog,[]),
241 pgm_dll = (mkdll_prog,mkdll_args),
243 pgm_sysman = top_dir ++ "/ghc/rts/parallel/SysMan",
244 pgm_windres = windres_path
245 -- Hans: this isn't right in general, but you can
246 -- elaborate it in the same way as the others
252 -- returns a Unix-format path (relying on getBaseDir to do so too)
253 findTopDir :: Maybe String -- Maybe TopDir path (without the '-B' prefix).
254 -> IO String -- TopDir (in Unix format '/' separated)
255 findTopDir (Just minusb) = return (normalise minusb)
257 = do -- Get directory of executable
258 maybe_exec_dir <- getBaseDir
259 case maybe_exec_dir of
260 -- "Just" on Windows, "Nothing" on unix
261 Nothing -> ghcError (InstallationError "missing -B<dir> option")
262 Just dir -> return dir
266 %************************************************************************
268 \subsection{Running an external program}
270 %************************************************************************
274 runUnlit :: DynFlags -> [Option] -> IO ()
275 runUnlit dflags args = do
277 runSomething dflags "Literate pre-processor" p args
279 runCpp :: DynFlags -> [Option] -> IO ()
280 runCpp dflags args = do
281 let (p,args0) = pgm_P dflags
282 args1 = args0 ++ args
283 args2 = if dopt Opt_WarnIsError dflags
284 then Option "-Werror" : args1
286 mb_env <- getGccEnv args2
287 runSomethingFiltered dflags id "C pre-processor" p args2 mb_env
289 runPp :: DynFlags -> [Option] -> IO ()
290 runPp dflags args = do
292 runSomething dflags "Haskell pre-processor" p args
294 runCc :: DynFlags -> [Option] -> IO ()
295 runCc dflags args = do
296 let (p,args0) = pgm_c dflags
297 args1 = args0 ++ args
298 mb_env <- getGccEnv args1
299 runSomethingFiltered dflags cc_filter "C Compiler" p args1 mb_env
301 -- discard some harmless warnings from gcc that we can't turn off
302 cc_filter = unlines . doFilter . lines
305 gcc gives warnings in chunks like so:
306 In file included from /foo/bar/baz.h:11,
307 from /foo/bar/baz2.h:22,
309 /foo/flibble:14: global register variable ...
310 /foo/flibble:15: warning: call-clobbered r...
311 We break it up into its chunks, remove any call-clobbered register
312 warnings from each chunk, and then delete any chunks that we have
315 doFilter = unChunkWarnings . filterWarnings . chunkWarnings []
316 -- We can't assume that the output will start with an "In file inc..."
317 -- line, so we start off expecting a list of warnings rather than a
319 chunkWarnings :: [String] -- The location stack to use for the next
321 -> [String] -- The remaining lines to look at
322 -> [([String], [String])]
323 chunkWarnings loc_stack [] = [(loc_stack, [])]
324 chunkWarnings loc_stack xs
325 = case break loc_stack_start xs of
326 (warnings, lss:xs') ->
327 case span loc_start_continuation xs' of
329 (loc_stack, warnings) : chunkWarnings (lss : lsc) xs''
330 _ -> [(loc_stack, xs)]
332 filterWarnings :: [([String], [String])] -> [([String], [String])]
333 filterWarnings [] = []
334 -- If the warnings are already empty then we are probably doing
335 -- something wrong, so don't delete anything
336 filterWarnings ((xs, []) : zs) = (xs, []) : filterWarnings zs
337 filterWarnings ((xs, ys) : zs) = case filter wantedWarning ys of
338 [] -> filterWarnings zs
339 ys' -> (xs, ys') : filterWarnings zs
341 unChunkWarnings :: [([String], [String])] -> [String]
342 unChunkWarnings [] = []
343 unChunkWarnings ((xs, ys) : zs) = xs ++ ys ++ unChunkWarnings zs
345 loc_stack_start s = "In file included from " `isPrefixOf` s
346 loc_start_continuation s = " from " `isPrefixOf` s
348 | "warning: call-clobbered register used" `isContainedIn` w = False
351 isContainedIn :: String -> String -> Bool
352 xs `isContainedIn` ys = any (xs `isPrefixOf`) (tails ys)
354 -- If the -B<dir> option is set, add <dir> to PATH. This works around
355 -- a bug in gcc on Windows Vista where it can't find its auxiliary
356 -- binaries (see bug #1110).
357 getGccEnv :: [Option] -> IO (Maybe [(String,String)])
361 else do env <- getEnvironment
362 return (Just (map mangle_path env))
364 (b_dirs, _) = partitionWith get_b_opt opts
366 get_b_opt (Option ('-':'B':dir)) = Left dir
367 get_b_opt other = Right other
369 mangle_path (path,paths) | map toUpper path == "PATH"
370 = (path, '\"' : head b_dirs ++ "\";" ++ paths)
371 mangle_path other = other
373 runMangle :: DynFlags -> [Option] -> IO ()
374 runMangle dflags args = do
375 let (p,args0) = pgm_m dflags
376 runSomething dflags "Mangler" p (args0++args)
378 runSplit :: DynFlags -> [Option] -> IO ()
379 runSplit dflags args = do
380 let (p,args0) = pgm_s dflags
381 runSomething dflags "Splitter" p (args0++args)
383 runAs :: DynFlags -> [Option] -> IO ()
384 runAs dflags args = do
385 let (p,args0) = pgm_a dflags
386 args1 = args0 ++ args
387 mb_env <- getGccEnv args1
388 runSomethingFiltered dflags id "Assembler" p args1 mb_env
390 runLink :: DynFlags -> [Option] -> IO ()
391 runLink dflags args = do
392 let (p,args0) = pgm_l dflags
393 args1 = args0 ++ args
394 mb_env <- getGccEnv args1
395 runSomethingFiltered dflags id "Linker" p args1 mb_env
397 runMkDLL :: DynFlags -> [Option] -> IO ()
398 runMkDLL dflags args = do
399 let (p,args0) = pgm_dll dflags
400 args1 = args0 ++ args
401 mb_env <- getGccEnv (args0++args)
402 runSomethingFiltered dflags id "Make DLL" p args1 mb_env
404 runWindres :: DynFlags -> [Option] -> IO ()
405 runWindres dflags args = do
406 let (_gcc,gcc_args) = pgm_c dflags
407 windres = pgm_windres dflags
408 mb_env <- getGccEnv gcc_args
409 runSomethingFiltered dflags id "Windres" windres args mb_env
411 touch :: DynFlags -> String -> String -> IO ()
412 touch dflags purpose arg =
413 runSomething dflags purpose (pgm_T dflags) [FileOption "" arg]
415 copy :: DynFlags -> String -> FilePath -> FilePath -> IO ()
416 copy dflags purpose from to = copyWithHeader dflags purpose Nothing from to
418 copyWithHeader :: DynFlags -> String -> Maybe String -> FilePath -> FilePath
420 copyWithHeader dflags purpose maybe_header from to = do
421 showPass dflags purpose
423 h <- openFile to WriteMode
424 ls <- readFile from -- inefficient, but it'll do for now.
425 -- ToDo: speed up via slurping.
426 maybe (return ()) (hPutStr h) maybe_header
430 getExtraViaCOpts :: DynFlags -> IO [String]
431 getExtraViaCOpts dflags = do
432 f <- readFile (topDir dflags </> "extra-gcc-opts")
436 %************************************************************************
438 \subsection{Managing temporary files
440 %************************************************************************
443 cleanTempDirs :: DynFlags -> IO ()
445 = unless (dopt Opt_KeepTmpFiles dflags)
446 $ do let ref = dirsToClean dflags
448 removeTmpDirs dflags (eltsFM ds)
449 writeIORef ref emptyFM
451 cleanTempFiles :: DynFlags -> IO ()
452 cleanTempFiles dflags
453 = unless (dopt Opt_KeepTmpFiles dflags)
454 $ do let ref = filesToClean dflags
456 removeTmpFiles dflags fs
459 cleanTempFilesExcept :: DynFlags -> [FilePath] -> IO ()
460 cleanTempFilesExcept dflags dont_delete
461 = unless (dopt Opt_KeepTmpFiles dflags)
462 $ do let ref = filesToClean dflags
463 files <- readIORef ref
464 let (to_keep, to_delete) = partition (`elem` dont_delete) files
465 removeTmpFiles dflags to_delete
466 writeIORef ref to_keep
469 -- find a temporary name that doesn't already exist.
470 newTempName :: DynFlags -> Suffix -> IO FilePath
471 newTempName dflags extn
472 = do d <- getTempDir dflags
474 findTempName (d ++ "/ghc" ++ show x ++ "_") 0
476 findTempName :: FilePath -> Integer -> IO FilePath
477 findTempName prefix x
478 = do let filename = (prefix ++ show x) <.> extn
479 b <- doesFileExist filename
480 if b then findTempName prefix (x+1)
481 else do -- clean it up later
482 consIORef (filesToClean dflags) filename
485 -- return our temporary directory within tmp_dir, creating one if we
486 -- don't have one yet
487 getTempDir :: DynFlags -> IO FilePath
488 getTempDir dflags@(DynFlags{tmpDir=tmp_dir})
489 = do let ref = dirsToClean dflags
490 mapping <- readIORef ref
491 case lookupFM mapping tmp_dir of
494 let prefix = tmp_dir ++ "/ghc" ++ show x ++ "_"
496 mkTempDir :: Integer -> IO FilePath
498 = let dirname = prefix ++ show x
499 in do createDirectory dirname
500 let mapping' = addToFM mapping tmp_dir dirname
501 writeIORef ref mapping'
502 debugTraceMsg dflags 2 (ptext (sLit "Created temporary directory:") <+> text dirname)
505 if isAlreadyExistsError e
511 addFilesToClean :: DynFlags -> [FilePath] -> IO ()
512 -- May include wildcards [used by DriverPipeline.run_phase SplitMangle]
513 addFilesToClean dflags files = mapM_ (consIORef (filesToClean dflags)) files
515 removeTmpDirs :: DynFlags -> [FilePath] -> IO ()
516 removeTmpDirs dflags ds
517 = traceCmd dflags "Deleting temp dirs"
518 ("Deleting: " ++ unwords ds)
519 (mapM_ (removeWith dflags removeDirectory) ds)
521 removeTmpFiles :: DynFlags -> [FilePath] -> IO ()
522 removeTmpFiles dflags fs
524 traceCmd dflags "Deleting temp files"
525 ("Deleting: " ++ unwords deletees)
526 (mapM_ (removeWith dflags removeFile) deletees)
528 -- Flat out refuse to delete files that are likely to be source input
529 -- files (is there a worse bug than having a compiler delete your source
532 -- Deleting source files is a sign of a bug elsewhere, so prominently flag
535 | null non_deletees = act
537 putMsg dflags (text "WARNING - NOT deleting source files:" <+> hsep (map text non_deletees))
540 (non_deletees, deletees) = partition isHaskellUserSrcFilename fs
542 removeWith :: DynFlags -> (FilePath -> IO ()) -> FilePath -> IO ()
543 removeWith dflags remover f = remover f `IO.catch`
545 let msg = if isDoesNotExistError e
546 then ptext (sLit "Warning: deleting non-existent") <+> text f
547 else ptext (sLit "Warning: exception raised when deleting")
550 in debugTraceMsg dflags 2 msg
553 -----------------------------------------------------------------------------
554 -- Running an external program
556 runSomething :: DynFlags
557 -> String -- For -v message
558 -> String -- Command name (possibly a full path)
559 -- assumed already dos-ified
560 -> [Option] -- Arguments
561 -- runSomething will dos-ify them
564 runSomething dflags phase_name pgm args =
565 runSomethingFiltered dflags id phase_name pgm args Nothing
568 :: DynFlags -> (String->String) -> String -> String -> [Option]
569 -> Maybe [(String,String)] -> IO ()
571 runSomethingFiltered dflags filter_fn phase_name pgm args mb_env = do
572 let real_args = filter notNull (map showOpt args)
573 traceCmd dflags phase_name (unwords (pgm:real_args)) $ do
574 (exit_code, doesn'tExist) <-
576 rc <- builderMainLoop dflags filter_fn pgm real_args mb_env
578 ExitSuccess{} -> return (rc, False)
580 -- rawSystem returns (ExitFailure 127) if the exec failed for any
581 -- reason (eg. the program doesn't exist). This is the only clue
582 -- we have, but we need to report something to the user because in
583 -- the case of a missing program there will otherwise be no output
585 | n == 127 -> return (rc, True)
586 | otherwise -> return (rc, False))
587 -- Should 'rawSystem' generate an IO exception indicating that
588 -- 'pgm' couldn't be run rather than a funky return code, catch
589 -- this here (the win32 version does this, but it doesn't hurt
590 -- to test for this in general.)
592 if IO.isDoesNotExistError err
593 then return (ExitFailure 1, True)
595 case (doesn'tExist, exit_code) of
596 (True, _) -> ghcError (InstallationError ("could not execute: " ++ pgm))
597 (_, ExitSuccess) -> return ()
598 _ -> ghcError (PhaseFailed phase_name exit_code)
600 builderMainLoop :: DynFlags -> (String -> String) -> FilePath
601 -> [String] -> Maybe [(String, String)]
603 builderMainLoop dflags filter_fn pgm real_args mb_env = do
605 (hStdIn, hStdOut, hStdErr, hProcess) <- runInteractiveProcess pgm real_args Nothing mb_env
607 -- and run a loop piping the output from the compiler to the log_action in DynFlags
608 hSetBuffering hStdOut LineBuffering
609 hSetBuffering hStdErr LineBuffering
610 forkIO (readerProc chan hStdOut filter_fn)
611 forkIO (readerProc chan hStdErr filter_fn)
612 -- we don't want to finish until 2 streams have been completed
613 -- (stdout and stderr)
614 -- nor until 1 exit code has been retrieved.
615 rc <- loop chan hProcess (2::Integer) (1::Integer) ExitSuccess
616 -- after that, we're done here.
622 -- status starts at zero, and increments each time either
623 -- a reader process gets EOF, or the build proc exits. We wait
624 -- for all of these to happen (status==3).
625 -- ToDo: we should really have a contingency plan in case any of
626 -- the threads dies, such as a timeout.
627 loop _ _ 0 0 exitcode = return exitcode
628 loop chan hProcess t p exitcode = do
630 then getProcessExitCode hProcess
633 Just code -> loop chan hProcess t (p-1) code
639 log_action dflags SevInfo noSrcSpan defaultUserStyle msg
640 loop chan hProcess t p exitcode
641 BuildError loc msg -> do
642 log_action dflags SevError (mkSrcSpan loc loc) defaultUserStyle msg
643 loop chan hProcess t p exitcode
645 loop chan hProcess (t-1) p exitcode
646 | otherwise -> loop chan hProcess t p exitcode
648 readerProc :: Chan BuildMessage -> Handle -> (String -> String) -> IO ()
649 readerProc chan hdl filter_fn =
650 (do str <- hGetContents hdl
651 loop (linesPlatform (filter_fn str)) Nothing)
654 -- ToDo: check errors more carefully
655 -- ToDo: in the future, the filter should be implemented as
656 -- a stream transformer.
658 loop [] Nothing = return ()
659 loop [] (Just err) = writeChan chan err
662 Just err@(BuildError srcLoc msg)
663 | leading_whitespace l -> do
664 loop ls (Just (BuildError srcLoc (msg $$ text l)))
670 _ -> panic "readerProc/loop"
673 = case parseError l of
675 writeChan chan (BuildMsg (text l))
677 Just (file, lineNum, colNum, msg) -> do
678 let srcLoc = mkSrcLoc (mkFastString file) lineNum colNum
679 loop ls (Just (BuildError srcLoc (text msg)))
681 leading_whitespace [] = False
682 leading_whitespace (x:_) = isSpace x
684 parseError :: String -> Maybe (String, Int, Int, String)
685 parseError s0 = case breakColon s0 of
686 Just (filename, s1) ->
687 case breakIntColon s1 of
688 Just (lineNum, s2) ->
689 case breakIntColon s2 of
690 Just (columnNum, s3) ->
691 Just (filename, lineNum, columnNum, s3)
693 Just (filename, lineNum, 0, s2)
697 breakColon :: String -> Maybe (String, String)
698 breakColon xs = case break (':' ==) xs of
699 (ys, _:zs) -> Just (ys, zs)
702 breakIntColon :: String -> Maybe (Int, String)
703 breakIntColon xs = case break (':' ==) xs of
705 | not (null ys) && all isAscii ys && all isDigit ys ->
711 | BuildError !SrcLoc !SDoc
714 showOpt :: Option -> String
715 showOpt (FileOption pre f) = pre ++ f
716 showOpt (Option s) = s
718 traceCmd :: DynFlags -> String -> String -> IO () -> IO ()
719 -- a) trace the command (at two levels of verbosity)
720 -- b) don't do it at all if dry-run is set
721 traceCmd dflags phase_name cmd_line action
722 = do { let verb = verbosity dflags
723 ; showPass dflags phase_name
724 ; debugTraceMsg dflags 3 (text cmd_line)
728 ; unless (dopt Opt_DryRun dflags) $ do {
731 ; action `IO.catch` handle_exn verb
734 handle_exn _verb exn = do { debugTraceMsg dflags 2 (char '\n')
735 ; debugTraceMsg dflags 2 (ptext (sLit "Failed:") <+> text cmd_line <+> text (show exn))
736 ; ghcError (PhaseFailed phase_name (ExitFailure 1)) }
739 %************************************************************************
741 \subsection{Support code}
743 %************************************************************************
746 -----------------------------------------------------------------------------
747 -- Define getBaseDir :: IO (Maybe String)
749 getBaseDir :: IO (Maybe String)
750 #if defined(mingw32_HOST_OS)
751 -- Assuming we are running ghc, accessed by path $(stuff)/bin/ghc.exe,
752 -- return the path $(stuff)/lib.
753 getBaseDir = do let len = (2048::Int) -- plenty, PATH_MAX is 512 under Win32.
754 buf <- mallocArray len
755 ret <- getModuleFileName nullPtr buf len
756 if ret == 0 then free buf >> return Nothing
757 else do s <- peekCString buf
759 return (Just (rootDir s))
761 rootDir s = case splitFileName $ normalise s of
763 | lower ghc_exe `elem` ["ghc.exe",
767 case splitFileName $ takeDirectory d of
768 -- ghc is in $topdir/bin/ghc.exe
769 (d', bin) | lower bin == "bin" -> takeDirectory d' </> "lib"
772 where fail = panic ("can't decompose ghc.exe path: " ++ show s)
775 foreign import stdcall unsafe "GetModuleFileNameA"
776 getModuleFileName :: Ptr () -> CString -> Int -> IO Int32
778 getBaseDir = return Nothing
781 #ifdef mingw32_HOST_OS
782 foreign import ccall unsafe "_getpid" getProcessID :: IO Int -- relies on Int == Int32 on Windows
784 getProcessID :: IO Int
785 getProcessID = System.Posix.Internals.c_getpid >>= return . fromIntegral
788 -- Divvy up text stream into lines, taking platform dependent
789 -- line termination into account.
790 linesPlatform :: String -> [String]
791 #if !defined(mingw32_HOST_OS)
792 linesPlatform ls = lines ls
794 linesPlatform "" = []
797 (as,xs1) -> as : linesPlatform xs1
799 lineBreak "" = ("","")
800 lineBreak ('\r':'\n':xs) = ([],xs)
801 lineBreak ('\n':xs) = ([],xs)
802 lineBreak (x:xs) = let (as,bs) = lineBreak xs in (x:as,bs)