Implement function-sections for Haskell code, #8405
[ghc.git] / compiler / main / SysTools.hs
1 {-
2 -----------------------------------------------------------------------------
3 --
4 -- (c) The University of Glasgow 2001-2003
5 --
6 -- Access to system tools: gcc, cp, rm etc
7 --
8 -----------------------------------------------------------------------------
9 -}
10
11 {-# LANGUAGE CPP, ScopedTypeVariables #-}
12
13 module SysTools (
14 -- Initialisation
15 initSysTools,
16
17 -- Interface to system tools
18 runUnlit, runCpp, runCc, -- [Option] -> IO ()
19 runPp, -- [Option] -> IO ()
20 runSplit, -- [Option] -> IO ()
21 runAs, runLink, runLibtool, -- [Option] -> IO ()
22 runMkDLL,
23 runWindres,
24 runLlvmOpt,
25 runLlvmLlc,
26 runClang,
27 figureLlvmVersion,
28
29 getLinkerInfo,
30 getCompilerInfo,
31
32 linkDynLib,
33
34 askCc,
35
36 touch, -- String -> String -> IO ()
37 copy,
38 copyWithHeader,
39
40 -- Temporary-file management
41 setTmpDir,
42 newTempName, newTempLibName,
43 cleanTempDirs, cleanTempFiles, cleanTempFilesExcept,
44 addFilesToClean,
45
46 Option(..),
47
48 -- frameworks
49 getPkgFrameworkOpts,
50 getFrameworkOpts
51
52
53 ) where
54
55 #include "HsVersions.h"
56
57 import DriverPhases
58 import Module
59 import Packages
60 import Config
61 import Outputable
62 import ErrUtils
63 import Panic
64 import Platform
65 import Util
66 import DynFlags
67 import Exception
68
69 import Data.IORef
70 import Control.Monad
71 import System.Exit
72 import System.Environment
73 import System.FilePath
74 import System.IO
75 import System.IO.Error as IO
76 import System.Directory
77 import Data.Char
78 import Data.List
79 import qualified Data.Map as Map
80
81 #ifndef mingw32_HOST_OS
82 import qualified System.Posix.Internals
83 #else /* Must be Win32 */
84 import Foreign
85 import Foreign.C.String
86 #endif
87
88 import System.Process
89 import Control.Concurrent
90 import FastString
91 import SrcLoc ( SrcLoc, mkSrcLoc, noSrcSpan, mkSrcSpan )
92
93 #ifdef mingw32_HOST_OS
94 # if defined(i386_HOST_ARCH)
95 # define WINDOWS_CCONV stdcall
96 # elif defined(x86_64_HOST_ARCH)
97 # define WINDOWS_CCONV ccall
98 # else
99 # error Unknown mingw32 arch
100 # endif
101 #endif
102
103 {-
104 How GHC finds its files
105 ~~~~~~~~~~~~~~~~~~~~~~~
106
107 [Note topdir]
108
109 GHC needs various support files (library packages, RTS etc), plus
110 various auxiliary programs (cp, gcc, etc). It starts by finding topdir,
111 the root of GHC's support files
112
113 On Unix:
114 - ghc always has a shell wrapper that passes a -B<dir> option
115
116 On Windows:
117 - ghc never has a shell wrapper.
118 - we can find the location of the ghc binary, which is
119 $topdir/bin/<something>.exe
120 where <something> may be "ghc", "ghc-stage2", or similar
121 - we strip off the "bin/<something>.exe" to leave $topdir.
122
123 from topdir we can find package.conf, ghc-asm, etc.
124
125
126 SysTools.initSysProgs figures out exactly where all the auxiliary programs
127 are, and initialises mutable variables to make it easy to call them.
128 To to this, it makes use of definitions in Config.hs, which is a Haskell
129 file containing variables whose value is figured out by the build system.
130
131 Config.hs contains two sorts of things
132
133 cGCC, The *names* of the programs
134 cCPP e.g. cGCC = gcc
135 cUNLIT cCPP = gcc -E
136 etc They do *not* include paths
137
138
139 cUNLIT_DIR The *path* to the directory containing unlit, split etc
140 cSPLIT_DIR *relative* to the root of the build tree,
141 for use when running *in-place* in a build tree (only)
142
143
144
145 ---------------------------------------------
146 NOTES for an ALTERNATIVE scheme (i.e *not* what is currently implemented):
147
148 Another hair-brained scheme for simplifying the current tool location
149 nightmare in GHC: Simon originally suggested using another
150 configuration file along the lines of GCC's specs file - which is fine
151 except that it means adding code to read yet another configuration
152 file. What I didn't notice is that the current package.conf is
153 general enough to do this:
154
155 Package
156 {name = "tools", import_dirs = [], source_dirs = [],
157 library_dirs = [], hs_libraries = [], extra_libraries = [],
158 include_dirs = [], c_includes = [], package_deps = [],
159 extra_ghc_opts = ["-pgmc/usr/bin/gcc","-pgml${topdir}/bin/unlit", ... etc.],
160 extra_cc_opts = [], extra_ld_opts = []}
161
162 Which would have the advantage that we get to collect together in one
163 place the path-specific package stuff with the path-specific tool
164 stuff.
165 End of NOTES
166 ---------------------------------------------
167
168 ************************************************************************
169 * *
170 \subsection{Initialisation}
171 * *
172 ************************************************************************
173 -}
174
175 initSysTools :: Maybe String -- Maybe TopDir path (without the '-B' prefix)
176 -> IO Settings -- Set all the mutable variables above, holding
177 -- (a) the system programs
178 -- (b) the package-config file
179 -- (c) the GHC usage message
180 initSysTools mbMinusB
181 = do top_dir <- findTopDir mbMinusB
182 -- see [Note topdir]
183 -- NB: top_dir is assumed to be in standard Unix
184 -- format, '/' separated
185
186 let settingsFile = top_dir </> "settings"
187 platformConstantsFile = top_dir </> "platformConstants"
188 installed :: FilePath -> FilePath
189 installed file = top_dir </> file
190
191 settingsStr <- readFile settingsFile
192 platformConstantsStr <- readFile platformConstantsFile
193 mySettings <- case maybeReadFuzzy settingsStr of
194 Just s ->
195 return s
196 Nothing ->
197 pgmError ("Can't parse " ++ show settingsFile)
198 platformConstants <- case maybeReadFuzzy platformConstantsStr of
199 Just s ->
200 return s
201 Nothing ->
202 pgmError ("Can't parse " ++
203 show platformConstantsFile)
204 let getSetting key = case lookup key mySettings of
205 Just xs ->
206 return $ case stripPrefix "$topdir" xs of
207 Just [] ->
208 top_dir
209 Just xs'@(c:_)
210 | isPathSeparator c ->
211 top_dir ++ xs'
212 _ ->
213 xs
214 Nothing -> pgmError ("No entry for " ++ show key ++ " in " ++ show settingsFile)
215 getBooleanSetting key = case lookup key mySettings of
216 Just "YES" -> return True
217 Just "NO" -> return False
218 Just xs -> pgmError ("Bad value for " ++ show key ++ ": " ++ show xs)
219 Nothing -> pgmError ("No entry for " ++ show key ++ " in " ++ show settingsFile)
220 readSetting key = case lookup key mySettings of
221 Just xs ->
222 case maybeRead xs of
223 Just v -> return v
224 Nothing -> pgmError ("Failed to read " ++ show key ++ " value " ++ show xs)
225 Nothing -> pgmError ("No entry for " ++ show key ++ " in " ++ show settingsFile)
226 crossCompiling <- getBooleanSetting "cross compiling"
227 targetArch <- readSetting "target arch"
228 targetOS <- readSetting "target os"
229 targetWordSize <- readSetting "target word size"
230 targetUnregisterised <- getBooleanSetting "Unregisterised"
231 targetHasGnuNonexecStack <- readSetting "target has GNU nonexec stack"
232 targetHasIdentDirective <- readSetting "target has .ident directive"
233 targetHasSubsectionsViaSymbols <- readSetting "target has subsections via symbols"
234 myExtraGccViaCFlags <- getSetting "GCC extra via C opts"
235 -- On Windows, mingw is distributed with GHC,
236 -- so we look in TopDir/../mingw/bin
237 -- It would perhaps be nice to be able to override this
238 -- with the settings file, but it would be a little fiddly
239 -- to make that possible, so for now you can't.
240 gcc_prog <- getSetting "C compiler command"
241 gcc_args_str <- getSetting "C compiler flags"
242 cpp_prog <- getSetting "Haskell CPP command"
243 cpp_args_str <- getSetting "Haskell CPP flags"
244 let unreg_gcc_args = if targetUnregisterised
245 then ["-DNO_REGS", "-DUSE_MINIINTERPRETER"]
246 else []
247 -- TABLES_NEXT_TO_CODE affects the info table layout.
248 tntc_gcc_args
249 | mkTablesNextToCode targetUnregisterised
250 = ["-DTABLES_NEXT_TO_CODE"]
251 | otherwise = []
252 cpp_args= map Option (words cpp_args_str)
253 gcc_args = map Option (words gcc_args_str
254 ++ unreg_gcc_args
255 ++ tntc_gcc_args)
256 ldSupportsCompactUnwind <- getBooleanSetting "ld supports compact unwind"
257 ldSupportsBuildId <- getBooleanSetting "ld supports build-id"
258 ldSupportsFilelist <- getBooleanSetting "ld supports filelist"
259 ldIsGnuLd <- getBooleanSetting "ld is GNU ld"
260 perl_path <- getSetting "perl command"
261
262 let pkgconfig_path = installed "package.conf.d"
263 ghc_usage_msg_path = installed "ghc-usage.txt"
264 ghci_usage_msg_path = installed "ghci-usage.txt"
265
266 -- For all systems, unlit, split, mangle are GHC utilities
267 -- architecture-specific stuff is done when building Config.hs
268 unlit_path = installed cGHC_UNLIT_PGM
269
270 -- split is a Perl script
271 split_script = installed cGHC_SPLIT_PGM
272
273 windres_path <- getSetting "windres command"
274 libtool_path <- getSetting "libtool command"
275
276 tmpdir <- getTemporaryDirectory
277
278 touch_path <- getSetting "touch command"
279
280 let -- On Win32 we don't want to rely on #!/bin/perl, so we prepend
281 -- a call to Perl to get the invocation of split.
282 -- On Unix, scripts are invoked using the '#!' method. Binary
283 -- installations of GHC on Unix place the correct line on the
284 -- front of the script at installation time, so we don't want
285 -- to wire-in our knowledge of $(PERL) on the host system here.
286 (split_prog, split_args)
287 | isWindowsHost = (perl_path, [Option split_script])
288 | otherwise = (split_script, [])
289 mkdll_prog <- getSetting "dllwrap command"
290 let mkdll_args = []
291
292 -- cpp is derived from gcc on all platforms
293 -- HACK, see setPgmP below. We keep 'words' here to remember to fix
294 -- Config.hs one day.
295
296
297 -- Other things being equal, as and ld are simply gcc
298 gcc_link_args_str <- getSetting "C compiler link flags"
299 let as_prog = gcc_prog
300 as_args = gcc_args
301 ld_prog = gcc_prog
302 ld_args = gcc_args ++ map Option (words gcc_link_args_str)
303
304 -- We just assume on command line
305 lc_prog <- getSetting "LLVM llc command"
306 lo_prog <- getSetting "LLVM opt command"
307
308 let platform = Platform {
309 platformArch = targetArch,
310 platformOS = targetOS,
311 platformWordSize = targetWordSize,
312 platformUnregisterised = targetUnregisterised,
313 platformHasGnuNonexecStack = targetHasGnuNonexecStack,
314 platformHasIdentDirective = targetHasIdentDirective,
315 platformHasSubsectionsViaSymbols = targetHasSubsectionsViaSymbols,
316 platformIsCrossCompiling = crossCompiling
317 }
318
319 return $ Settings {
320 sTargetPlatform = platform,
321 sTmpDir = normalise tmpdir,
322 sGhcUsagePath = ghc_usage_msg_path,
323 sGhciUsagePath = ghci_usage_msg_path,
324 sTopDir = top_dir,
325 sRawSettings = mySettings,
326 sExtraGccViaCFlags = words myExtraGccViaCFlags,
327 sSystemPackageConfig = pkgconfig_path,
328 sLdSupportsCompactUnwind = ldSupportsCompactUnwind,
329 sLdSupportsBuildId = ldSupportsBuildId,
330 sLdSupportsFilelist = ldSupportsFilelist,
331 sLdIsGnuLd = ldIsGnuLd,
332 sProgramName = "ghc",
333 sProjectVersion = cProjectVersion,
334 sPgm_L = unlit_path,
335 sPgm_P = (cpp_prog, cpp_args),
336 sPgm_F = "",
337 sPgm_c = (gcc_prog, gcc_args),
338 sPgm_s = (split_prog,split_args),
339 sPgm_a = (as_prog, as_args),
340 sPgm_l = (ld_prog, ld_args),
341 sPgm_dll = (mkdll_prog,mkdll_args),
342 sPgm_T = touch_path,
343 sPgm_windres = windres_path,
344 sPgm_libtool = libtool_path,
345 sPgm_lo = (lo_prog,[]),
346 sPgm_lc = (lc_prog,[]),
347 sOpt_L = [],
348 sOpt_P = [],
349 sOpt_F = [],
350 sOpt_c = [],
351 sOpt_a = [],
352 sOpt_l = [],
353 sOpt_windres = [],
354 sOpt_lo = [],
355 sOpt_lc = [],
356 sPlatformConstants = platformConstants
357 }
358
359 -- returns a Unix-format path (relying on getBaseDir to do so too)
360 findTopDir :: Maybe String -- Maybe TopDir path (without the '-B' prefix).
361 -> IO String -- TopDir (in Unix format '/' separated)
362 findTopDir (Just minusb) = return (normalise minusb)
363 findTopDir Nothing
364 = do -- Get directory of executable
365 maybe_exec_dir <- getBaseDir
366 case maybe_exec_dir of
367 -- "Just" on Windows, "Nothing" on unix
368 Nothing -> throwGhcExceptionIO (InstallationError "missing -B<dir> option")
369 Just dir -> return dir
370
371 {-
372 ************************************************************************
373 * *
374 \subsection{Running an external program}
375 * *
376 ************************************************************************
377 -}
378
379 runUnlit :: DynFlags -> [Option] -> IO ()
380 runUnlit dflags args = do
381 let prog = pgm_L dflags
382 opts = getOpts dflags opt_L
383 runSomething dflags "Literate pre-processor" prog
384 (map Option opts ++ args)
385
386 runCpp :: DynFlags -> [Option] -> IO ()
387 runCpp dflags args = do
388 let (p,args0) = pgm_P dflags
389 args1 = map Option (getOpts dflags opt_P)
390 args2 = if gopt Opt_WarnIsError dflags
391 then [Option "-Werror"]
392 else []
393 mb_env <- getGccEnv args2
394 runSomethingFiltered dflags id "C pre-processor" p
395 (args0 ++ args1 ++ args2 ++ args) mb_env
396
397 runPp :: DynFlags -> [Option] -> IO ()
398 runPp dflags args = do
399 let prog = pgm_F dflags
400 opts = map Option (getOpts dflags opt_F)
401 runSomething dflags "Haskell pre-processor" prog (args ++ opts)
402
403 runCc :: DynFlags -> [Option] -> IO ()
404 runCc dflags args = do
405 let (p,args0) = pgm_c dflags
406 args1 = map Option (getOpts dflags opt_c)
407 args2 = args0 ++ args1 ++ args
408 mb_env <- getGccEnv args2
409 runSomethingResponseFile dflags cc_filter "C Compiler" p args2 mb_env
410 where
411 -- discard some harmless warnings from gcc that we can't turn off
412 cc_filter = unlines . doFilter . lines
413
414 {-
415 gcc gives warnings in chunks like so:
416 In file included from /foo/bar/baz.h:11,
417 from /foo/bar/baz2.h:22,
418 from wibble.c:33:
419 /foo/flibble:14: global register variable ...
420 /foo/flibble:15: warning: call-clobbered r...
421 We break it up into its chunks, remove any call-clobbered register
422 warnings from each chunk, and then delete any chunks that we have
423 emptied of warnings.
424 -}
425 doFilter = unChunkWarnings . filterWarnings . chunkWarnings []
426 -- We can't assume that the output will start with an "In file inc..."
427 -- line, so we start off expecting a list of warnings rather than a
428 -- location stack.
429 chunkWarnings :: [String] -- The location stack to use for the next
430 -- list of warnings
431 -> [String] -- The remaining lines to look at
432 -> [([String], [String])]
433 chunkWarnings loc_stack [] = [(loc_stack, [])]
434 chunkWarnings loc_stack xs
435 = case break loc_stack_start xs of
436 (warnings, lss:xs') ->
437 case span loc_start_continuation xs' of
438 (lsc, xs'') ->
439 (loc_stack, warnings) : chunkWarnings (lss : lsc) xs''
440 _ -> [(loc_stack, xs)]
441
442 filterWarnings :: [([String], [String])] -> [([String], [String])]
443 filterWarnings [] = []
444 -- If the warnings are already empty then we are probably doing
445 -- something wrong, so don't delete anything
446 filterWarnings ((xs, []) : zs) = (xs, []) : filterWarnings zs
447 filterWarnings ((xs, ys) : zs) = case filter wantedWarning ys of
448 [] -> filterWarnings zs
449 ys' -> (xs, ys') : filterWarnings zs
450
451 unChunkWarnings :: [([String], [String])] -> [String]
452 unChunkWarnings [] = []
453 unChunkWarnings ((xs, ys) : zs) = xs ++ ys ++ unChunkWarnings zs
454
455 loc_stack_start s = "In file included from " `isPrefixOf` s
456 loc_start_continuation s = " from " `isPrefixOf` s
457 wantedWarning w
458 | "warning: call-clobbered register used" `isContainedIn` w = False
459 | otherwise = True
460
461 isContainedIn :: String -> String -> Bool
462 xs `isContainedIn` ys = any (xs `isPrefixOf`) (tails ys)
463
464 askCc :: DynFlags -> [Option] -> IO String
465 askCc dflags args = do
466 let (p,args0) = pgm_c dflags
467 args1 = map Option (getOpts dflags opt_c)
468 args2 = args0 ++ args1 ++ args
469 mb_env <- getGccEnv args2
470 runSomethingWith dflags "gcc" p args2 $ \real_args ->
471 readCreateProcessWithExitCode' (proc p real_args){ env = mb_env }
472
473 -- Similar to System.Process.readCreateProcessWithExitCode, but stderr is
474 -- inherited from the parent process, and output to stderr is not captured.
475 readCreateProcessWithExitCode'
476 :: CreateProcess
477 -> IO (ExitCode, String) -- ^ stdout
478 readCreateProcessWithExitCode' proc = do
479 (_, Just outh, _, pid) <-
480 createProcess proc{ std_out = CreatePipe }
481
482 -- fork off a thread to start consuming the output
483 output <- hGetContents outh
484 outMVar <- newEmptyMVar
485 _ <- forkIO $ evaluate (length output) >> putMVar outMVar ()
486
487 -- wait on the output
488 takeMVar outMVar
489 hClose outh
490
491 -- wait on the process
492 ex <- waitForProcess pid
493
494 return (ex, output)
495
496 readProcessEnvWithExitCode
497 :: String -- ^ program path
498 -> [String] -- ^ program args
499 -> [(String, String)] -- ^ environment to override
500 -> IO (ExitCode, String, String) -- ^ (exit_code, stdout, stderr)
501 readProcessEnvWithExitCode prog args env_update = do
502 current_env <- getEnvironment
503 let new_env = env_update ++ [ (k, v)
504 | let overriden_keys = map fst env_update
505 , (k, v) <- current_env
506 , k `notElem` overriden_keys
507 ]
508 p = proc prog args
509
510 (_stdin, Just stdoh, Just stdeh, pid) <-
511 createProcess p{ std_out = CreatePipe
512 , std_err = CreatePipe
513 , env = Just new_env
514 }
515
516 outMVar <- newEmptyMVar
517 errMVar <- newEmptyMVar
518
519 _ <- forkIO $ do
520 stdo <- hGetContents stdoh
521 _ <- evaluate (length stdo)
522 putMVar outMVar stdo
523
524 _ <- forkIO $ do
525 stde <- hGetContents stdeh
526 _ <- evaluate (length stde)
527 putMVar errMVar stde
528
529 out <- takeMVar outMVar
530 hClose stdoh
531 err <- takeMVar errMVar
532 hClose stdeh
533
534 ex <- waitForProcess pid
535
536 return (ex, out, err)
537
538 -- Don't let gcc localize version info string, #8825
539 en_locale_env :: [(String, String)]
540 en_locale_env = [("LANGUAGE", "en")]
541
542 -- If the -B<dir> option is set, add <dir> to PATH. This works around
543 -- a bug in gcc on Windows Vista where it can't find its auxiliary
544 -- binaries (see bug #1110).
545 getGccEnv :: [Option] -> IO (Maybe [(String,String)])
546 getGccEnv opts =
547 if null b_dirs
548 then return Nothing
549 else do env <- getEnvironment
550 return (Just (map mangle_path env))
551 where
552 (b_dirs, _) = partitionWith get_b_opt opts
553
554 get_b_opt (Option ('-':'B':dir)) = Left dir
555 get_b_opt other = Right other
556
557 mangle_path (path,paths) | map toUpper path == "PATH"
558 = (path, '\"' : head b_dirs ++ "\";" ++ paths)
559 mangle_path other = other
560
561 runSplit :: DynFlags -> [Option] -> IO ()
562 runSplit dflags args = do
563 let (p,args0) = pgm_s dflags
564 runSomething dflags "Splitter" p (args0++args)
565
566 runAs :: DynFlags -> [Option] -> IO ()
567 runAs dflags args = do
568 let (p,args0) = pgm_a dflags
569 args1 = map Option (getOpts dflags opt_a)
570 args2 = args0 ++ args1 ++ args
571 mb_env <- getGccEnv args2
572 runSomethingFiltered dflags id "Assembler" p args2 mb_env
573
574 -- | Run the LLVM Optimiser
575 runLlvmOpt :: DynFlags -> [Option] -> IO ()
576 runLlvmOpt dflags args = do
577 let (p,args0) = pgm_lo dflags
578 args1 = map Option (getOpts dflags opt_lo)
579 runSomething dflags "LLVM Optimiser" p (args0 ++ args1 ++ args)
580
581 -- | Run the LLVM Compiler
582 runLlvmLlc :: DynFlags -> [Option] -> IO ()
583 runLlvmLlc dflags args = do
584 let (p,args0) = pgm_lc dflags
585 args1 = map Option (getOpts dflags opt_lc)
586 runSomething dflags "LLVM Compiler" p (args0 ++ args1 ++ args)
587
588 -- | Run the clang compiler (used as an assembler for the LLVM
589 -- backend on OS X as LLVM doesn't support the OS X system
590 -- assembler)
591 runClang :: DynFlags -> [Option] -> IO ()
592 runClang dflags args = do
593 -- we simply assume its available on the PATH
594 let clang = "clang"
595 -- be careful what options we call clang with
596 -- see #5903 and #7617 for bugs caused by this.
597 (_,args0) = pgm_a dflags
598 args1 = map Option (getOpts dflags opt_a)
599 args2 = args0 ++ args1 ++ args
600 mb_env <- getGccEnv args2
601 Exception.catch (do
602 runSomethingFiltered dflags id "Clang (Assembler)" clang args2 mb_env
603 )
604 (\(err :: SomeException) -> do
605 errorMsg dflags $
606 text ("Error running clang! you need clang installed to use the" ++
607 " LLVM backend") $+$
608 text "(or GHC tried to execute clang incorrectly)"
609 throwIO err
610 )
611
612 -- | Figure out which version of LLVM we are running this session
613 figureLlvmVersion :: DynFlags -> IO (Maybe (Int, Int))
614 figureLlvmVersion dflags = do
615 let (pgm,opts) = pgm_lc dflags
616 args = filter notNull (map showOpt opts)
617 -- we grab the args even though they should be useless just in
618 -- case the user is using a customised 'llc' that requires some
619 -- of the options they've specified. llc doesn't care what other
620 -- options are specified when '-version' is used.
621 args' = args ++ ["-version"]
622 ver <- catchIO (do
623 (pin, pout, perr, _) <- runInteractiveProcess pgm args'
624 Nothing Nothing
625 {- > llc -version
626 LLVM (http://llvm.org/):
627 LLVM version 3.5.2
628 ...
629 -}
630 hSetBinaryMode pout False
631 _ <- hGetLine pout
632 vline <- dropWhile (not . isDigit) `fmap` hGetLine pout
633 v <- case span (/= '.') vline of
634 ("",_) -> fail "no digits!"
635 (x,y) -> return (read x
636 , read $ takeWhile isDigit $ drop 1 y)
637
638 hClose pin
639 hClose pout
640 hClose perr
641 return $ Just v
642 )
643 (\err -> do
644 debugTraceMsg dflags 2
645 (text "Error (figuring out LLVM version):" <+>
646 text (show err))
647 errorMsg dflags $ vcat
648 [ text "Warning:", nest 9 $
649 text "Couldn't figure out LLVM version!" $$
650 text "Make sure you have installed LLVM"]
651 return Nothing)
652 return ver
653
654 {- Note [Windows stack usage]
655
656 See: Trac #8870 (and #8834 for related info)
657
658 On Windows, occasionally we need to grow the stack. In order to do
659 this, we would normally just bump the stack pointer - but there's a
660 catch on Windows.
661
662 If the stack pointer is bumped by more than a single page, then the
663 pages between the initial pointer and the resulting location must be
664 properly committed by the Windows virtual memory subsystem. This is
665 only needed in the event we bump by more than one page (i.e 4097 bytes
666 or more).
667
668 Windows compilers solve this by emitting a call to a special function
669 called _chkstk, which does this committing of the pages for you.
670
671 The reason this was causing a segfault was because due to the fact the
672 new code generator tends to generate larger functions, we needed more
673 stack space in GHC itself. In the x86 codegen, we needed approximately
674 ~12kb of stack space in one go, which caused the process to segfault,
675 as the intervening pages were not committed.
676
677 In the future, we should do the same thing, to make the problem
678 completely go away. In the mean time, we're using a workaround: we
679 instruct the linker to specify the generated PE as having an initial
680 reserved stack size of 8mb, as well as a initial *committed* stack
681 size of 8mb. The default committed size was previously only 4k.
682
683 Theoretically it's possible to still hit this problem if you request a
684 stack bump of more than 8mb in one go. But the amount of code
685 necessary is quite large, and 8mb "should be more than enough for
686 anyone" right now (he said, before millions of lines of code cried out
687 in terror).
688
689 -}
690
691 {- Note [Run-time linker info]
692
693 See also: Trac #5240, Trac #6063, Trac #10110
694
695 Before 'runLink', we need to be sure to get the relevant information
696 about the linker we're using at runtime to see if we need any extra
697 options. For example, GNU ld requires '--reduce-memory-overheads' and
698 '--hash-size=31' in order to use reasonable amounts of memory (see
699 trac #5240.) But this isn't supported in GNU gold.
700
701 Generally, the linker changing from what was detected at ./configure
702 time has always been possible using -pgml, but on Linux it can happen
703 'transparently' by installing packages like binutils-gold, which
704 change what /usr/bin/ld actually points to.
705
706 Clang vs GCC notes:
707
708 For gcc, 'gcc -Wl,--version' gives a bunch of output about how to
709 invoke the linker before the version information string. For 'clang',
710 the version information for 'ld' is all that's output. For this
711 reason, we typically need to slurp up all of the standard error output
712 and look through it.
713
714 Other notes:
715
716 We cache the LinkerInfo inside DynFlags, since clients may link
717 multiple times. The definition of LinkerInfo is there to avoid a
718 circular dependency.
719
720 -}
721
722 {- Note [ELF needed shared libs]
723
724 Some distributions change the link editor's default handling of
725 ELF DT_NEEDED tags to include only those shared objects that are
726 needed to resolve undefined symbols. For Template Haskell we need
727 the last temporary shared library also if it is not needed for the
728 currently linked temporary shared library. We specify --no-as-needed
729 to override the default. This flag exists in GNU ld and GNU gold.
730
731 The flag is only needed on ELF systems. On Windows (PE) and Mac OS X
732 (Mach-O) the flag is not needed.
733
734 -}
735
736 {- Note [Windows static libGCC]
737
738 The GCC versions being upgraded to in #10726 are configured with
739 dynamic linking of libgcc supported. This results in libgcc being
740 linked dynamically when a shared library is created.
741
742 This introduces thus an extra dependency on GCC dll that was not
743 needed before by shared libraries created with GHC. This is a particular
744 issue on Windows because you get a non-obvious error due to this missing
745 dependency. This dependent dll is also not commonly on your path.
746
747 For this reason using the static libgcc is preferred as it preserves
748 the same behaviour that existed before. There are however some very good
749 reasons to have the shared version as well as described on page 181 of
750 https://gcc.gnu.org/onlinedocs/gcc-5.2.0/gcc.pdf :
751
752 "There are several situations in which an application should use the
753 shared ‘libgcc’ instead of the static version. The most common of these
754 is when the application wishes to throw and catch exceptions across different
755 shared libraries. In that case, each of the libraries as well as the application
756 itself should use the shared ‘libgcc’. "
757
758 -}
759
760 neededLinkArgs :: LinkerInfo -> [Option]
761 neededLinkArgs (GnuLD o) = o
762 neededLinkArgs (GnuGold o) = o
763 neededLinkArgs (DarwinLD o) = o
764 neededLinkArgs (SolarisLD o) = o
765 neededLinkArgs UnknownLD = []
766
767 -- Grab linker info and cache it in DynFlags.
768 getLinkerInfo :: DynFlags -> IO LinkerInfo
769 getLinkerInfo dflags = do
770 info <- readIORef (rtldInfo dflags)
771 case info of
772 Just v -> return v
773 Nothing -> do
774 v <- getLinkerInfo' dflags
775 writeIORef (rtldInfo dflags) (Just v)
776 return v
777
778 -- See Note [Run-time linker info].
779 getLinkerInfo' :: DynFlags -> IO LinkerInfo
780 getLinkerInfo' dflags = do
781 let platform = targetPlatform dflags
782 os = platformOS platform
783 (pgm,args0) = pgm_l dflags
784 args1 = map Option (getOpts dflags opt_l)
785 args2 = args0 ++ args1
786 args3 = filter notNull (map showOpt args2)
787
788 -- Try to grab the info from the process output.
789 parseLinkerInfo stdo _stde _exitc
790 | any ("GNU ld" `isPrefixOf`) stdo =
791 -- GNU ld specifically needs to use less memory. This especially
792 -- hurts on small object files. Trac #5240.
793 -- Set DT_NEEDED for all shared libraries. Trac #10110.
794 -- TODO: Investigate if these help or hurt when using split sections.
795 return (GnuLD $ map Option ["-Wl,--hash-size=31",
796 "-Wl,--reduce-memory-overheads",
797 -- ELF specific flag
798 -- see Note [ELF needed shared libs]
799 "-Wl,--no-as-needed"])
800
801 | any ("GNU gold" `isPrefixOf`) stdo =
802 -- GNU gold only needs --no-as-needed. Trac #10110.
803 -- ELF specific flag, see Note [ELF needed shared libs]
804 return (GnuGold [Option "-Wl,--no-as-needed"])
805
806 -- Unknown linker.
807 | otherwise = fail "invalid --version output, or linker is unsupported"
808
809 -- Process the executable call
810 info <- catchIO (do
811 case os of
812 OSSolaris2 ->
813 -- Solaris uses its own Solaris linker. Even all
814 -- GNU C are recommended to configure with Solaris
815 -- linker instead of using GNU binutils linker. Also
816 -- all GCC distributed with Solaris follows this rule
817 -- precisely so we assume here, the Solaris linker is
818 -- used.
819 return $ SolarisLD []
820 OSDarwin ->
821 -- Darwin has neither GNU Gold or GNU LD, but a strange linker
822 -- that doesn't support --version. We can just assume that's
823 -- what we're using.
824 return $ DarwinLD []
825 OSiOS ->
826 -- Ditto for iOS
827 return $ DarwinLD []
828 OSMinGW32 ->
829 -- GHC doesn't support anything but GNU ld on Windows anyway.
830 -- Process creation is also fairly expensive on win32, so
831 -- we short-circuit here.
832 return $ GnuLD $ map Option
833 [ -- Reduce ld memory usage
834 "-Wl,--hash-size=31"
835 , "-Wl,--reduce-memory-overheads"
836 -- Increase default stack, see
837 -- Note [Windows stack usage]
838 -- Force static linking of libGCC
839 -- Note [Windows static libGCC]
840 , "-Xlinker", "--stack=0x800000,0x800000", "-static-libgcc" ]
841 _ -> do
842 -- In practice, we use the compiler as the linker here. Pass
843 -- -Wl,--version to get linker version info.
844 (exitc, stdo, stde) <- readProcessEnvWithExitCode pgm
845 (["-Wl,--version"] ++ args3)
846 en_locale_env
847 -- Split the output by lines to make certain kinds
848 -- of processing easier. In particular, 'clang' and 'gcc'
849 -- have slightly different outputs for '-Wl,--version', but
850 -- it's still easy to figure out.
851 parseLinkerInfo (lines stdo) (lines stde) exitc
852 )
853 (\err -> do
854 debugTraceMsg dflags 2
855 (text "Error (figuring out linker information):" <+>
856 text (show err))
857 errorMsg dflags $ hang (text "Warning:") 9 $
858 text "Couldn't figure out linker information!" $$
859 text "Make sure you're using GNU ld, GNU gold" <+>
860 text "or the built in OS X linker, etc."
861 return UnknownLD)
862 return info
863
864 -- Grab compiler info and cache it in DynFlags.
865 getCompilerInfo :: DynFlags -> IO CompilerInfo
866 getCompilerInfo dflags = do
867 info <- readIORef (rtccInfo dflags)
868 case info of
869 Just v -> return v
870 Nothing -> do
871 v <- getCompilerInfo' dflags
872 writeIORef (rtccInfo dflags) (Just v)
873 return v
874
875 -- See Note [Run-time linker info].
876 getCompilerInfo' :: DynFlags -> IO CompilerInfo
877 getCompilerInfo' dflags = do
878 let (pgm,_) = pgm_c dflags
879 -- Try to grab the info from the process output.
880 parseCompilerInfo _stdo stde _exitc
881 -- Regular GCC
882 | any ("gcc version" `isInfixOf`) stde =
883 return GCC
884 -- Regular clang
885 | any ("clang version" `isInfixOf`) stde =
886 return Clang
887 -- XCode 5.1 clang
888 | any ("Apple LLVM version 5.1" `isPrefixOf`) stde =
889 return AppleClang51
890 -- XCode 5 clang
891 | any ("Apple LLVM version" `isPrefixOf`) stde =
892 return AppleClang
893 -- XCode 4.1 clang
894 | any ("Apple clang version" `isPrefixOf`) stde =
895 return AppleClang
896 -- Unknown linker.
897 | otherwise = fail "invalid -v output, or compiler is unsupported"
898
899 -- Process the executable call
900 info <- catchIO (do
901 (exitc, stdo, stde) <-
902 readProcessEnvWithExitCode pgm ["-v"] en_locale_env
903 -- Split the output by lines to make certain kinds
904 -- of processing easier.
905 parseCompilerInfo (lines stdo) (lines stde) exitc
906 )
907 (\err -> do
908 debugTraceMsg dflags 2
909 (text "Error (figuring out C compiler information):" <+>
910 text (show err))
911 errorMsg dflags $ hang (text "Warning:") 9 $
912 text "Couldn't figure out C compiler information!" $$
913 text "Make sure you're using GNU gcc, or clang"
914 return UnknownCC)
915 return info
916
917 runLink :: DynFlags -> [Option] -> IO ()
918 runLink dflags args = do
919 -- See Note [Run-time linker info]
920 linkargs <- neededLinkArgs `fmap` getLinkerInfo dflags
921 let (p,args0) = pgm_l dflags
922 args1 = map Option (getOpts dflags opt_l)
923 args2 = args0 ++ linkargs ++ args1 ++ args
924 mb_env <- getGccEnv args2
925 runSomethingResponseFile dflags ld_filter "Linker" p args2 mb_env
926 where
927 ld_filter = case (platformOS (targetPlatform dflags)) of
928 OSSolaris2 -> sunos_ld_filter
929 _ -> id
930 {-
931 SunOS/Solaris ld emits harmless warning messages about unresolved
932 symbols in case of compiling into shared library when we do not
933 link against all the required libs. That is the case of GHC which
934 does not link against RTS library explicitly in order to be able to
935 choose the library later based on binary application linking
936 parameters. The warnings look like:
937
938 Undefined first referenced
939 symbol in file
940 stg_ap_n_fast ./T2386_Lib.o
941 stg_upd_frame_info ./T2386_Lib.o
942 templatezmhaskell_LanguageziHaskellziTHziLib_litE_closure ./T2386_Lib.o
943 templatezmhaskell_LanguageziHaskellziTHziLib_appE_closure ./T2386_Lib.o
944 templatezmhaskell_LanguageziHaskellziTHziLib_conE_closure ./T2386_Lib.o
945 templatezmhaskell_LanguageziHaskellziTHziSyntax_mkNameGzud_closure ./T2386_Lib.o
946 newCAF ./T2386_Lib.o
947 stg_bh_upd_frame_info ./T2386_Lib.o
948 stg_ap_ppp_fast ./T2386_Lib.o
949 templatezmhaskell_LanguageziHaskellziTHziLib_stringL_closure ./T2386_Lib.o
950 stg_ap_p_fast ./T2386_Lib.o
951 stg_ap_pp_fast ./T2386_Lib.o
952 ld: warning: symbol referencing errors
953
954 this is actually coming from T2386 testcase. The emitting of those
955 warnings is also a reason why so many TH testcases fail on Solaris.
956
957 Following filter code is SunOS/Solaris linker specific and should
958 filter out only linker warnings. Please note that the logic is a
959 little bit more complex due to the simple reason that we need to preserve
960 any other linker emitted messages. If there are any. Simply speaking
961 if we see "Undefined" and later "ld: warning:..." then we omit all
962 text between (including) the marks. Otherwise we copy the whole output.
963 -}
964 sunos_ld_filter :: String -> String
965 sunos_ld_filter = unlines . sunos_ld_filter' . lines
966 sunos_ld_filter' x = if (undefined_found x && ld_warning_found x)
967 then (ld_prefix x) ++ (ld_postfix x)
968 else x
969 breakStartsWith x y = break (isPrefixOf x) y
970 ld_prefix = fst . breakStartsWith "Undefined"
971 undefined_found = not . null . snd . breakStartsWith "Undefined"
972 ld_warn_break = breakStartsWith "ld: warning: symbol referencing errors"
973 ld_postfix = tail . snd . ld_warn_break
974 ld_warning_found = not . null . snd . ld_warn_break
975
976
977 runLibtool :: DynFlags -> [Option] -> IO ()
978 runLibtool dflags args = do
979 linkargs <- neededLinkArgs `fmap` getLinkerInfo dflags
980 let args1 = map Option (getOpts dflags opt_l)
981 args2 = [Option "-static"] ++ args1 ++ args ++ linkargs
982 libtool = pgm_libtool dflags
983 mb_env <- getGccEnv args2
984 runSomethingFiltered dflags id "Linker" libtool args2 mb_env
985
986 runMkDLL :: DynFlags -> [Option] -> IO ()
987 runMkDLL dflags args = do
988 let (p,args0) = pgm_dll dflags
989 args1 = args0 ++ args
990 mb_env <- getGccEnv (args0++args)
991 runSomethingFiltered dflags id "Make DLL" p args1 mb_env
992
993 runWindres :: DynFlags -> [Option] -> IO ()
994 runWindres dflags args = do
995 let (gcc, gcc_args) = pgm_c dflags
996 windres = pgm_windres dflags
997 opts = map Option (getOpts dflags opt_windres)
998 quote x = "\"" ++ x ++ "\""
999 args' = -- If windres.exe and gcc.exe are in a directory containing
1000 -- spaces then windres fails to run gcc. We therefore need
1001 -- to tell it what command to use...
1002 Option ("--preprocessor=" ++
1003 unwords (map quote (gcc :
1004 map showOpt gcc_args ++
1005 map showOpt opts ++
1006 ["-E", "-xc", "-DRC_INVOKED"])))
1007 -- ...but if we do that then if windres calls popen then
1008 -- it can't understand the quoting, so we have to use
1009 -- --use-temp-file so that it interprets it correctly.
1010 -- See #1828.
1011 : Option "--use-temp-file"
1012 : args
1013 mb_env <- getGccEnv gcc_args
1014 runSomethingFiltered dflags id "Windres" windres args' mb_env
1015
1016 touch :: DynFlags -> String -> String -> IO ()
1017 touch dflags purpose arg =
1018 runSomething dflags purpose (pgm_T dflags) [FileOption "" arg]
1019
1020 copy :: DynFlags -> String -> FilePath -> FilePath -> IO ()
1021 copy dflags purpose from to = copyWithHeader dflags purpose Nothing from to
1022
1023 copyWithHeader :: DynFlags -> String -> Maybe String -> FilePath -> FilePath
1024 -> IO ()
1025 copyWithHeader dflags purpose maybe_header from to = do
1026 showPass dflags purpose
1027
1028 hout <- openBinaryFile to WriteMode
1029 hin <- openBinaryFile from ReadMode
1030 ls <- hGetContents hin -- inefficient, but it'll do for now. ToDo: speed up
1031 maybe (return ()) (header hout) maybe_header
1032 hPutStr hout ls
1033 hClose hout
1034 hClose hin
1035 where
1036 -- write the header string in UTF-8. The header is something like
1037 -- {-# LINE "foo.hs" #-}
1038 -- and we want to make sure a Unicode filename isn't mangled.
1039 header h str = do
1040 hSetEncoding h utf8
1041 hPutStr h str
1042 hSetBinaryMode h True
1043
1044
1045
1046 {-
1047 ************************************************************************
1048 * *
1049 \subsection{Managing temporary files
1050 * *
1051 ************************************************************************
1052 -}
1053
1054 cleanTempDirs :: DynFlags -> IO ()
1055 cleanTempDirs dflags
1056 = unless (gopt Opt_KeepTmpFiles dflags)
1057 $ mask_
1058 $ do let ref = dirsToClean dflags
1059 ds <- atomicModifyIORef' ref $ \ds -> (Map.empty, ds)
1060 removeTmpDirs dflags (Map.elems ds)
1061
1062 cleanTempFiles :: DynFlags -> IO ()
1063 cleanTempFiles dflags
1064 = unless (gopt Opt_KeepTmpFiles dflags)
1065 $ mask_
1066 $ do let ref = filesToClean dflags
1067 fs <- atomicModifyIORef' ref $ \fs -> ([],fs)
1068 removeTmpFiles dflags fs
1069
1070 cleanTempFilesExcept :: DynFlags -> [FilePath] -> IO ()
1071 cleanTempFilesExcept dflags dont_delete
1072 = unless (gopt Opt_KeepTmpFiles dflags)
1073 $ mask_
1074 $ do let ref = filesToClean dflags
1075 to_delete <- atomicModifyIORef' ref $ \files ->
1076 let (to_keep,to_delete) = partition (`elem` dont_delete) files
1077 in (to_keep,to_delete)
1078 removeTmpFiles dflags to_delete
1079
1080
1081 -- Return a unique numeric temp file suffix
1082 newTempSuffix :: DynFlags -> IO Int
1083 newTempSuffix dflags = atomicModifyIORef' (nextTempSuffix dflags) $ \n -> (n+1,n)
1084
1085 -- Find a temporary name that doesn't already exist.
1086 newTempName :: DynFlags -> Suffix -> IO FilePath
1087 newTempName dflags extn
1088 = do d <- getTempDir dflags
1089 findTempName (d </> "ghc_") -- See Note [Deterministic base name]
1090 where
1091 findTempName :: FilePath -> IO FilePath
1092 findTempName prefix
1093 = do n <- newTempSuffix dflags
1094 let filename = prefix ++ show n <.> extn
1095 b <- doesFileExist filename
1096 if b then findTempName prefix
1097 else do -- clean it up later
1098 consIORef (filesToClean dflags) filename
1099 return filename
1100
1101 newTempLibName :: DynFlags -> Suffix -> IO (FilePath, FilePath, String)
1102 newTempLibName dflags extn
1103 = do d <- getTempDir dflags
1104 findTempName d ("ghc_")
1105 where
1106 findTempName :: FilePath -> String -> IO (FilePath, FilePath, String)
1107 findTempName dir prefix
1108 = do n <- newTempSuffix dflags -- See Note [Deterministic base name]
1109 let libname = prefix ++ show n
1110 filename = dir </> "lib" ++ libname <.> extn
1111 b <- doesFileExist filename
1112 if b then findTempName dir prefix
1113 else do -- clean it up later
1114 consIORef (filesToClean dflags) filename
1115 return (filename, dir, libname)
1116
1117
1118 -- Return our temporary directory within tmp_dir, creating one if we
1119 -- don't have one yet.
1120 getTempDir :: DynFlags -> IO FilePath
1121 getTempDir dflags = do
1122 mapping <- readIORef dir_ref
1123 case Map.lookup tmp_dir mapping of
1124 Nothing -> do
1125 pid <- getProcessID
1126 let prefix = tmp_dir </> "ghc" ++ show pid ++ "_"
1127 mask_ $ mkTempDir prefix
1128 Just dir -> return dir
1129 where
1130 tmp_dir = tmpDir dflags
1131 dir_ref = dirsToClean dflags
1132
1133 mkTempDir :: FilePath -> IO FilePath
1134 mkTempDir prefix = do
1135 n <- newTempSuffix dflags
1136 let our_dir = prefix ++ show n
1137
1138 -- 1. Speculatively create our new directory.
1139 createDirectory our_dir
1140
1141 -- 2. Update the dirsToClean mapping unless an entry already exists
1142 -- (i.e. unless another thread beat us to it).
1143 their_dir <- atomicModifyIORef' dir_ref $ \mapping ->
1144 case Map.lookup tmp_dir mapping of
1145 Just dir -> (mapping, Just dir)
1146 Nothing -> (Map.insert tmp_dir our_dir mapping, Nothing)
1147
1148 -- 3. If there was an existing entry, return it and delete the
1149 -- directory we created. Otherwise return the directory we created.
1150 case their_dir of
1151 Nothing -> do
1152 debugTraceMsg dflags 2 $
1153 text "Created temporary directory:" <+> text our_dir
1154 return our_dir
1155 Just dir -> do
1156 removeDirectory our_dir
1157 return dir
1158 `catchIO` \e -> if isAlreadyExistsError e
1159 then mkTempDir prefix else ioError e
1160
1161 -- Note [Deterministic base name]
1162 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1163 --
1164 -- The filename of temporary files, especially the basename of C files, can end
1165 -- up in the output in some form, e.g. as part of linker debug information. In the
1166 -- interest of bit-wise exactly reproducible compilation (#4012), the basename of
1167 -- the temporary file no longer contains random information (it used to contain
1168 -- the process id).
1169 --
1170 -- This is ok, as the temporary directory used contains the pid (see getTempDir).
1171
1172 addFilesToClean :: DynFlags -> [FilePath] -> IO ()
1173 -- May include wildcards [used by DriverPipeline.run_phase SplitMangle]
1174 addFilesToClean dflags new_files
1175 = atomicModifyIORef' (filesToClean dflags) $ \files -> (new_files++files, ())
1176
1177 removeTmpDirs :: DynFlags -> [FilePath] -> IO ()
1178 removeTmpDirs dflags ds
1179 = traceCmd dflags "Deleting temp dirs"
1180 ("Deleting: " ++ unwords ds)
1181 (mapM_ (removeWith dflags removeDirectory) ds)
1182
1183 removeTmpFiles :: DynFlags -> [FilePath] -> IO ()
1184 removeTmpFiles dflags fs
1185 = warnNon $
1186 traceCmd dflags "Deleting temp files"
1187 ("Deleting: " ++ unwords deletees)
1188 (mapM_ (removeWith dflags removeFile) deletees)
1189 where
1190 -- Flat out refuse to delete files that are likely to be source input
1191 -- files (is there a worse bug than having a compiler delete your source
1192 -- files?)
1193 --
1194 -- Deleting source files is a sign of a bug elsewhere, so prominently flag
1195 -- the condition.
1196 warnNon act
1197 | null non_deletees = act
1198 | otherwise = do
1199 putMsg dflags (text "WARNING - NOT deleting source files:" <+> hsep (map text non_deletees))
1200 act
1201
1202 (non_deletees, deletees) = partition isHaskellUserSrcFilename fs
1203
1204 removeWith :: DynFlags -> (FilePath -> IO ()) -> FilePath -> IO ()
1205 removeWith dflags remover f = remover f `catchIO`
1206 (\e ->
1207 let msg = if isDoesNotExistError e
1208 then ptext (sLit "Warning: deleting non-existent") <+> text f
1209 else ptext (sLit "Warning: exception raised when deleting")
1210 <+> text f <> colon
1211 $$ text (show e)
1212 in debugTraceMsg dflags 2 msg
1213 )
1214
1215 -----------------------------------------------------------------------------
1216 -- Running an external program
1217
1218 runSomething :: DynFlags
1219 -> String -- For -v message
1220 -> String -- Command name (possibly a full path)
1221 -- assumed already dos-ified
1222 -> [Option] -- Arguments
1223 -- runSomething will dos-ify them
1224 -> IO ()
1225
1226 runSomething dflags phase_name pgm args =
1227 runSomethingFiltered dflags id phase_name pgm args Nothing
1228
1229 -- | Run a command, placing the arguments in an external response file.
1230 --
1231 -- This command is used in order to avoid overlong command line arguments on
1232 -- Windows. The command line arguments are first written to an external,
1233 -- temporary response file, and then passed to the linker via @filepath.
1234 -- response files for passing them in. See:
1235 --
1236 -- https://gcc.gnu.org/wiki/Response_Files
1237 -- https://ghc.haskell.org/trac/ghc/ticket/10777
1238 runSomethingResponseFile
1239 :: DynFlags -> (String->String) -> String -> String -> [Option]
1240 -> Maybe [(String,String)] -> IO ()
1241
1242 runSomethingResponseFile dflags filter_fn phase_name pgm args mb_env =
1243 runSomethingWith dflags phase_name pgm args $ \real_args -> do
1244 fp <- getResponseFile real_args
1245 let args = ['@':fp]
1246 r <- builderMainLoop dflags filter_fn pgm args mb_env
1247 return (r,())
1248 where
1249 getResponseFile args = do
1250 fp <- newTempName dflags "rsp"
1251 withFile fp WriteMode $ \h -> do
1252 hSetEncoding h utf8
1253 hPutStr h $ unlines $ map escape args
1254 return fp
1255
1256 -- Note: Response files have backslash-escaping, double quoting, and are
1257 -- whitespace separated (some implementations use newline, others any
1258 -- whitespace character). Therefore, escape any backslashes, newlines, and
1259 -- double quotes in the argument, and surround the content with double
1260 -- quotes.
1261 --
1262 -- Another possibility that could be considered would be to convert
1263 -- backslashes in the argument to forward slashes. This would generally do
1264 -- the right thing, since backslashes in general only appear in arguments
1265 -- as part of file paths on Windows, and the forward slash is accepted for
1266 -- those. However, escaping is more reliable, in case somehow a backslash
1267 -- appears in a non-file.
1268 escape x = concat
1269 [ "\""
1270 , concatMap
1271 (\c ->
1272 case c of
1273 '\\' -> "\\\\"
1274 '\n' -> "\\n"
1275 '\"' -> "\\\""
1276 _ -> [c])
1277 x
1278 , "\""
1279 ]
1280
1281 runSomethingFiltered
1282 :: DynFlags -> (String->String) -> String -> String -> [Option]
1283 -> Maybe [(String,String)] -> IO ()
1284
1285 runSomethingFiltered dflags filter_fn phase_name pgm args mb_env = do
1286 runSomethingWith dflags phase_name pgm args $ \real_args -> do
1287 r <- builderMainLoop dflags filter_fn pgm real_args mb_env
1288 return (r,())
1289
1290 runSomethingWith
1291 :: DynFlags -> String -> String -> [Option]
1292 -> ([String] -> IO (ExitCode, a))
1293 -> IO a
1294
1295 runSomethingWith dflags phase_name pgm args io = do
1296 let real_args = filter notNull (map showOpt args)
1297 cmdLine = showCommandForUser pgm real_args
1298 traceCmd dflags phase_name cmdLine $ handleProc pgm phase_name $ io real_args
1299
1300 handleProc :: String -> String -> IO (ExitCode, r) -> IO r
1301 handleProc pgm phase_name proc = do
1302 (rc, r) <- proc `catchIO` handler
1303 case rc of
1304 ExitSuccess{} -> return r
1305 ExitFailure n -> throwGhcExceptionIO (
1306 ProgramError ("`" ++ takeFileName pgm ++ "'" ++
1307 " failed in phase `" ++ phase_name ++ "'." ++
1308 " (Exit code: " ++ show n ++ ")"))
1309 where
1310 handler err =
1311 if IO.isDoesNotExistError err
1312 then does_not_exist
1313 else throwGhcExceptionIO (ProgramError $ show err)
1314
1315 does_not_exist = throwGhcExceptionIO (InstallationError ("could not execute: " ++ pgm))
1316
1317
1318 builderMainLoop :: DynFlags -> (String -> String) -> FilePath
1319 -> [String] -> Maybe [(String, String)]
1320 -> IO ExitCode
1321 builderMainLoop dflags filter_fn pgm real_args mb_env = do
1322 chan <- newChan
1323 (hStdIn, hStdOut, hStdErr, hProcess) <- runInteractiveProcess pgm real_args Nothing mb_env
1324
1325 -- and run a loop piping the output from the compiler to the log_action in DynFlags
1326 hSetBuffering hStdOut LineBuffering
1327 hSetBuffering hStdErr LineBuffering
1328 _ <- forkIO (readerProc chan hStdOut filter_fn)
1329 _ <- forkIO (readerProc chan hStdErr filter_fn)
1330 -- we don't want to finish until 2 streams have been completed
1331 -- (stdout and stderr)
1332 -- nor until 1 exit code has been retrieved.
1333 rc <- loop chan hProcess (2::Integer) (1::Integer) ExitSuccess
1334 -- after that, we're done here.
1335 hClose hStdIn
1336 hClose hStdOut
1337 hClose hStdErr
1338 return rc
1339 where
1340 -- status starts at zero, and increments each time either
1341 -- a reader process gets EOF, or the build proc exits. We wait
1342 -- for all of these to happen (status==3).
1343 -- ToDo: we should really have a contingency plan in case any of
1344 -- the threads dies, such as a timeout.
1345 loop _ _ 0 0 exitcode = return exitcode
1346 loop chan hProcess t p exitcode = do
1347 mb_code <- if p > 0
1348 then getProcessExitCode hProcess
1349 else return Nothing
1350 case mb_code of
1351 Just code -> loop chan hProcess t (p-1) code
1352 Nothing
1353 | t > 0 -> do
1354 msg <- readChan chan
1355 case msg of
1356 BuildMsg msg -> do
1357 log_action dflags dflags SevInfo noSrcSpan defaultUserStyle msg
1358 loop chan hProcess t p exitcode
1359 BuildError loc msg -> do
1360 log_action dflags dflags SevError (mkSrcSpan loc loc) defaultUserStyle msg
1361 loop chan hProcess t p exitcode
1362 EOF ->
1363 loop chan hProcess (t-1) p exitcode
1364 | otherwise -> loop chan hProcess t p exitcode
1365
1366 readerProc :: Chan BuildMessage -> Handle -> (String -> String) -> IO ()
1367 readerProc chan hdl filter_fn =
1368 (do str <- hGetContents hdl
1369 loop (linesPlatform (filter_fn str)) Nothing)
1370 `finally`
1371 writeChan chan EOF
1372 -- ToDo: check errors more carefully
1373 -- ToDo: in the future, the filter should be implemented as
1374 -- a stream transformer.
1375 where
1376 loop [] Nothing = return ()
1377 loop [] (Just err) = writeChan chan err
1378 loop (l:ls) in_err =
1379 case in_err of
1380 Just err@(BuildError srcLoc msg)
1381 | leading_whitespace l -> do
1382 loop ls (Just (BuildError srcLoc (msg $$ text l)))
1383 | otherwise -> do
1384 writeChan chan err
1385 checkError l ls
1386 Nothing -> do
1387 checkError l ls
1388 _ -> panic "readerProc/loop"
1389
1390 checkError l ls
1391 = case parseError l of
1392 Nothing -> do
1393 writeChan chan (BuildMsg (text l))
1394 loop ls Nothing
1395 Just (file, lineNum, colNum, msg) -> do
1396 let srcLoc = mkSrcLoc (mkFastString file) lineNum colNum
1397 loop ls (Just (BuildError srcLoc (text msg)))
1398
1399 leading_whitespace [] = False
1400 leading_whitespace (x:_) = isSpace x
1401
1402 parseError :: String -> Maybe (String, Int, Int, String)
1403 parseError s0 = case breakColon s0 of
1404 Just (filename, s1) ->
1405 case breakIntColon s1 of
1406 Just (lineNum, s2) ->
1407 case breakIntColon s2 of
1408 Just (columnNum, s3) ->
1409 Just (filename, lineNum, columnNum, s3)
1410 Nothing ->
1411 Just (filename, lineNum, 0, s2)
1412 Nothing -> Nothing
1413 Nothing -> Nothing
1414
1415 breakColon :: String -> Maybe (String, String)
1416 breakColon xs = case break (':' ==) xs of
1417 (ys, _:zs) -> Just (ys, zs)
1418 _ -> Nothing
1419
1420 breakIntColon :: String -> Maybe (Int, String)
1421 breakIntColon xs = case break (':' ==) xs of
1422 (ys, _:zs)
1423 | not (null ys) && all isAscii ys && all isDigit ys ->
1424 Just (read ys, zs)
1425 _ -> Nothing
1426
1427 data BuildMessage
1428 = BuildMsg !SDoc
1429 | BuildError !SrcLoc !SDoc
1430 | EOF
1431
1432 traceCmd :: DynFlags -> String -> String -> IO a -> IO a
1433 -- trace the command (at two levels of verbosity)
1434 traceCmd dflags phase_name cmd_line action
1435 = do { let verb = verbosity dflags
1436 ; showPass dflags phase_name
1437 ; debugTraceMsg dflags 3 (text cmd_line)
1438 ; case flushErr dflags of
1439 FlushErr io -> io
1440
1441 -- And run it!
1442 ; action `catchIO` handle_exn verb
1443 }
1444 where
1445 handle_exn _verb exn = do { debugTraceMsg dflags 2 (char '\n')
1446 ; debugTraceMsg dflags 2 (ptext (sLit "Failed:") <+> text cmd_line <+> text (show exn))
1447 ; throwGhcExceptionIO (ProgramError (show exn))}
1448
1449 {-
1450 ************************************************************************
1451 * *
1452 \subsection{Support code}
1453 * *
1454 ************************************************************************
1455 -}
1456
1457 -----------------------------------------------------------------------------
1458 -- Define getBaseDir :: IO (Maybe String)
1459
1460 getBaseDir :: IO (Maybe String)
1461 #if defined(mingw32_HOST_OS)
1462 -- Assuming we are running ghc, accessed by path $(stuff)/bin/ghc.exe,
1463 -- return the path $(stuff)/lib.
1464 getBaseDir = try_size 2048 -- plenty, PATH_MAX is 512 under Win32.
1465 where
1466 try_size size = allocaArray (fromIntegral size) $ \buf -> do
1467 ret <- c_GetModuleFileName nullPtr buf size
1468 case ret of
1469 0 -> return Nothing
1470 _ | ret < size -> fmap (Just . rootDir) $ peekCWString buf
1471 | otherwise -> try_size (size * 2)
1472
1473 rootDir s = case splitFileName $ normalise s of
1474 (d, ghc_exe)
1475 | lower ghc_exe `elem` ["ghc.exe",
1476 "ghc-stage1.exe",
1477 "ghc-stage2.exe",
1478 "ghc-stage3.exe"] ->
1479 case splitFileName $ takeDirectory d of
1480 -- ghc is in $topdir/bin/ghc.exe
1481 (d', bin) | lower bin == "bin" -> takeDirectory d' </> "lib"
1482 _ -> fail
1483 _ -> fail
1484 where fail = panic ("can't decompose ghc.exe path: " ++ show s)
1485 lower = map toLower
1486
1487 foreign import WINDOWS_CCONV unsafe "windows.h GetModuleFileNameW"
1488 c_GetModuleFileName :: Ptr () -> CWString -> Word32 -> IO Word32
1489 #else
1490 getBaseDir = return Nothing
1491 #endif
1492
1493 #ifdef mingw32_HOST_OS
1494 foreign import ccall unsafe "_getpid" getProcessID :: IO Int -- relies on Int == Int32 on Windows
1495 #else
1496 getProcessID :: IO Int
1497 getProcessID = System.Posix.Internals.c_getpid >>= return . fromIntegral
1498 #endif
1499
1500 -- Divvy up text stream into lines, taking platform dependent
1501 -- line termination into account.
1502 linesPlatform :: String -> [String]
1503 #if !defined(mingw32_HOST_OS)
1504 linesPlatform ls = lines ls
1505 #else
1506 linesPlatform "" = []
1507 linesPlatform xs =
1508 case lineBreak xs of
1509 (as,xs1) -> as : linesPlatform xs1
1510 where
1511 lineBreak "" = ("","")
1512 lineBreak ('\r':'\n':xs) = ([],xs)
1513 lineBreak ('\n':xs) = ([],xs)
1514 lineBreak (x:xs) = let (as,bs) = lineBreak xs in (x:as,bs)
1515
1516 #endif
1517
1518 linkDynLib :: DynFlags -> [String] -> [UnitId] -> IO ()
1519 linkDynLib dflags0 o_files dep_packages
1520 = do
1521 let -- This is a rather ugly hack to fix dynamically linked
1522 -- GHC on Windows. If GHC is linked with -threaded, then
1523 -- it links against libHSrts_thr. But if base is linked
1524 -- against libHSrts, then both end up getting loaded,
1525 -- and things go wrong. We therefore link the libraries
1526 -- with the same RTS flags that we link GHC with.
1527 dflags1 = if cGhcThreaded then addWay' WayThreaded dflags0
1528 else dflags0
1529 dflags2 = if cGhcDebugged then addWay' WayDebug dflags1
1530 else dflags1
1531 dflags = updateWays dflags2
1532
1533 verbFlags = getVerbFlags dflags
1534 o_file = outputFile dflags
1535
1536 pkgs <- getPreloadPackagesAnd dflags dep_packages
1537
1538 let pkg_lib_paths = collectLibraryPaths pkgs
1539 let pkg_lib_path_opts = concatMap get_pkg_lib_path_opts pkg_lib_paths
1540 get_pkg_lib_path_opts l
1541 | ( osElfTarget (platformOS (targetPlatform dflags)) ||
1542 osMachOTarget (platformOS (targetPlatform dflags)) ) &&
1543 dynLibLoader dflags == SystemDependent &&
1544 not (gopt Opt_Static dflags)
1545 = ["-L" ++ l, "-Wl,-rpath", "-Wl," ++ l]
1546 | otherwise = ["-L" ++ l]
1547
1548 let lib_paths = libraryPaths dflags
1549 let lib_path_opts = map ("-L"++) lib_paths
1550
1551 -- We don't want to link our dynamic libs against the RTS package,
1552 -- because the RTS lib comes in several flavours and we want to be
1553 -- able to pick the flavour when a binary is linked.
1554 -- On Windows we need to link the RTS import lib as Windows does
1555 -- not allow undefined symbols.
1556 -- The RTS library path is still added to the library search path
1557 -- above in case the RTS is being explicitly linked in (see #3807).
1558 let platform = targetPlatform dflags
1559 os = platformOS platform
1560 pkgs_no_rts = case os of
1561 OSMinGW32 ->
1562 pkgs
1563 _ ->
1564 filter ((/= rtsUnitId) . packageConfigId) pkgs
1565 let pkg_link_opts = let (package_hs_libs, extra_libs, other_flags) = collectLinkOpts dflags pkgs_no_rts
1566 in package_hs_libs ++ extra_libs ++ other_flags
1567
1568 -- probably _stub.o files
1569 -- and last temporary shared object file
1570 let extra_ld_inputs = ldInputs dflags
1571
1572 -- frameworks
1573 pkg_framework_opts <- getPkgFrameworkOpts dflags platform
1574 (map unitId pkgs)
1575 let framework_opts = getFrameworkOpts dflags platform
1576
1577 case os of
1578 OSMinGW32 -> do
1579 -------------------------------------------------------------
1580 -- Making a DLL
1581 -------------------------------------------------------------
1582 let output_fn = case o_file of
1583 Just s -> s
1584 Nothing -> "HSdll.dll"
1585
1586 runLink dflags (
1587 map Option verbFlags
1588 ++ [ Option "-o"
1589 , FileOption "" output_fn
1590 , Option "-shared"
1591 ] ++
1592 [ FileOption "-Wl,--out-implib=" (output_fn ++ ".a")
1593 | gopt Opt_SharedImplib dflags
1594 ]
1595 ++ map (FileOption "") o_files
1596
1597 -- Permit the linker to auto link _symbol to _imp_symbol
1598 -- This lets us link against DLLs without needing an "import library"
1599 ++ [Option "-Wl,--enable-auto-import"]
1600
1601 ++ extra_ld_inputs
1602 ++ map Option (
1603 lib_path_opts
1604 ++ pkg_lib_path_opts
1605 ++ pkg_link_opts
1606 ))
1607 OSDarwin -> do
1608 -------------------------------------------------------------------
1609 -- Making a darwin dylib
1610 -------------------------------------------------------------------
1611 -- About the options used for Darwin:
1612 -- -dynamiclib
1613 -- Apple's way of saying -shared
1614 -- -undefined dynamic_lookup:
1615 -- Without these options, we'd have to specify the correct
1616 -- dependencies for each of the dylibs. Note that we could
1617 -- (and should) do without this for all libraries except
1618 -- the RTS; all we need to do is to pass the correct
1619 -- HSfoo_dyn.dylib files to the link command.
1620 -- This feature requires Mac OS X 10.3 or later; there is
1621 -- a similar feature, -flat_namespace -undefined suppress,
1622 -- which works on earlier versions, but it has other
1623 -- disadvantages.
1624 -- -single_module
1625 -- Build the dynamic library as a single "module", i.e. no
1626 -- dynamic binding nonsense when referring to symbols from
1627 -- within the library. The NCG assumes that this option is
1628 -- specified (on i386, at least).
1629 -- -install_name
1630 -- Mac OS/X stores the path where a dynamic library is (to
1631 -- be) installed in the library itself. It's called the
1632 -- "install name" of the library. Then any library or
1633 -- executable that links against it before it's installed
1634 -- will search for it in its ultimate install location.
1635 -- By default we set the install name to the absolute path
1636 -- at build time, but it can be overridden by the
1637 -- -dylib-install-name option passed to ghc. Cabal does
1638 -- this.
1639 -------------------------------------------------------------------
1640
1641 let output_fn = case o_file of { Just s -> s; Nothing -> "a.out"; }
1642
1643 instName <- case dylibInstallName dflags of
1644 Just n -> return n
1645 Nothing -> return $ "@rpath" `combine` (takeFileName output_fn)
1646 runLink dflags (
1647 map Option verbFlags
1648 ++ [ Option "-dynamiclib"
1649 , Option "-o"
1650 , FileOption "" output_fn
1651 ]
1652 ++ map Option o_files
1653 ++ [ Option "-undefined",
1654 Option "dynamic_lookup",
1655 Option "-single_module" ]
1656 ++ (if platformArch platform == ArchX86_64
1657 then [ ]
1658 else [ Option "-Wl,-read_only_relocs,suppress" ])
1659 ++ [ Option "-install_name", Option instName ]
1660 ++ map Option lib_path_opts
1661 ++ extra_ld_inputs
1662 ++ map Option framework_opts
1663 ++ map Option pkg_lib_path_opts
1664 ++ map Option pkg_link_opts
1665 ++ map Option pkg_framework_opts
1666 )
1667 OSiOS -> throwGhcExceptionIO (ProgramError "dynamic libraries are not supported on iOS target")
1668 _ -> do
1669 -------------------------------------------------------------------
1670 -- Making a DSO
1671 -------------------------------------------------------------------
1672
1673 let output_fn = case o_file of { Just s -> s; Nothing -> "a.out"; }
1674 let bsymbolicFlag = -- we need symbolic linking to resolve
1675 -- non-PIC intra-package-relocations
1676 ["-Wl,-Bsymbolic"]
1677
1678 runLink dflags (
1679 map Option verbFlags
1680 ++ [ Option "-o"
1681 , FileOption "" output_fn
1682 ]
1683 ++ map Option o_files
1684 ++ [ Option "-shared" ]
1685 ++ map Option bsymbolicFlag
1686 -- Set the library soname. We use -h rather than -soname as
1687 -- Solaris 10 doesn't support the latter:
1688 ++ [ Option ("-Wl,-h," ++ takeFileName output_fn) ]
1689 ++ extra_ld_inputs
1690 ++ map Option lib_path_opts
1691 ++ map Option pkg_lib_path_opts
1692 ++ map Option pkg_link_opts
1693 )
1694
1695 getPkgFrameworkOpts :: DynFlags -> Platform -> [UnitId] -> IO [String]
1696 getPkgFrameworkOpts dflags platform dep_packages
1697 | platformUsesFrameworks platform = do
1698 pkg_framework_path_opts <- do
1699 pkg_framework_paths <- getPackageFrameworkPath dflags dep_packages
1700 return $ map ("-F" ++) pkg_framework_paths
1701
1702 pkg_framework_opts <- do
1703 pkg_frameworks <- getPackageFrameworks dflags dep_packages
1704 return $ concat [ ["-framework", fw] | fw <- pkg_frameworks ]
1705
1706 return (pkg_framework_path_opts ++ pkg_framework_opts)
1707
1708 | otherwise = return []
1709
1710 getFrameworkOpts :: DynFlags -> Platform -> [String]
1711 getFrameworkOpts dflags platform
1712 | platformUsesFrameworks platform = framework_path_opts ++ framework_opts
1713 | otherwise = []
1714 where
1715 framework_paths = frameworkPaths dflags
1716 framework_path_opts = map ("-F" ++) framework_paths
1717
1718 frameworks = cmdlineFrameworks dflags
1719 -- reverse because they're added in reverse order from the cmd line:
1720 framework_opts = concat [ ["-framework", fw]
1721 | fw <- reverse frameworks ]