9f1307d7983dfbabbabb303aeac35c35ff652e0f
[ghc.git] / compiler / ghci / Linker.hs
1 {-# LANGUAGE CPP, NondecreasingIndentation, TupleSections, RecordWildCards #-}
2 {-# LANGUAGE BangPatterns #-}
3 {-# OPTIONS_GHC -fno-cse #-}
4 -- -fno-cse is needed for GLOBAL_VAR's to behave properly
5
6 --
7 -- (c) The University of Glasgow 2002-2006
8 --
9 -- | The dynamic linker for GHCi.
10 --
11 -- This module deals with the top-level issues of dynamic linking,
12 -- calling the object-code linker and the byte-code linker where
13 -- necessary.
14 module Linker ( getHValue, showLinkerState,
15 linkExpr, linkDecls, unload, withExtendedLinkEnv,
16 extendLinkEnv, deleteFromLinkEnv,
17 extendLoadedPkgs,
18 linkPackages,initDynLinker,linkModule,
19 linkCmdLineLibs
20 ) where
21
22 #include "HsVersions.h"
23
24 import GhcPrelude
25
26 import GHCi
27 import GHCi.RemoteTypes
28 import LoadIface
29 import ByteCodeLink
30 import ByteCodeAsm
31 import ByteCodeTypes
32 import TcRnMonad
33 import Packages
34 import DriverPhases
35 import Finder
36 import HscTypes
37 import Name
38 import NameEnv
39 import Module
40 import ListSetOps
41 import DynFlags
42 import BasicTypes
43 import Outputable
44 import Panic
45 import Util
46 import ErrUtils
47 import SrcLoc
48 import qualified Maybes
49 import UniqDSet
50 import FastString
51 import Platform
52 import SysTools
53 import FileCleanup
54
55 -- Standard libraries
56 import Control.Monad
57
58 import Data.Char (isSpace)
59 import Data.IORef
60 import Data.List
61 import Data.Maybe
62 import Control.Concurrent.MVar
63
64 import System.FilePath
65 import System.Directory
66 import System.IO.Unsafe
67 import System.Environment (lookupEnv)
68
69 #if defined(mingw32_HOST_OS)
70 import System.Win32.Info (getSystemDirectory)
71 #endif
72
73 import Exception
74
75 -- needed for 2nd stage
76 #if STAGE >= 2
77 import Foreign (Ptr)
78 #endif
79
80 {- **********************************************************************
81
82 The Linker's state
83
84 ********************************************************************* -}
85
86 {-
87 The persistent linker state *must* match the actual state of the
88 C dynamic linker at all times, so we keep it in a private global variable.
89
90 The global IORef used for PersistentLinkerState actually contains another MVar,
91 which in turn contains a Maybe PersistentLinkerState. The MVar serves to ensure
92 mutual exclusion between multiple loaded copies of the GHC library. The Maybe
93 may be Nothing to indicate that the linker has not yet been initialised.
94
95 The PersistentLinkerState maps Names to actual closures (for
96 interpreted code only), for use during linking.
97 -}
98 #if STAGE < 2
99 GLOBAL_VAR_M( v_PersistentLinkerState
100 , newMVar Nothing
101 , MVar (Maybe PersistentLinkerState))
102 #else
103 SHARED_GLOBAL_VAR_M( v_PersistentLinkerState
104 , getOrSetLibHSghcPersistentLinkerState
105 , "getOrSetLibHSghcPersistentLinkerState"
106 , newMVar Nothing
107 , MVar (Maybe PersistentLinkerState))
108 #endif
109
110 uninitialised :: a
111 uninitialised = panic "Dynamic linker not initialised"
112
113 modifyPLS_ :: (PersistentLinkerState -> IO PersistentLinkerState) -> IO ()
114 modifyPLS_ f = readIORef v_PersistentLinkerState
115 >>= flip modifyMVar_ (fmap pure . f . fromMaybe uninitialised)
116
117 modifyPLS :: (PersistentLinkerState -> IO (PersistentLinkerState, a)) -> IO a
118 modifyPLS f = readIORef v_PersistentLinkerState
119 >>= flip modifyMVar (fmapFst pure . f . fromMaybe uninitialised)
120 where fmapFst f = fmap (\(x, y) -> (f x, y))
121
122 readPLS :: IO PersistentLinkerState
123 readPLS = readIORef v_PersistentLinkerState
124 >>= fmap (fromMaybe uninitialised) . readMVar
125
126 modifyMbPLS_
127 :: (Maybe PersistentLinkerState -> IO (Maybe PersistentLinkerState)) -> IO ()
128 modifyMbPLS_ f = readIORef v_PersistentLinkerState >>= flip modifyMVar_ f
129
130 data PersistentLinkerState
131 = PersistentLinkerState {
132
133 -- Current global mapping from Names to their true values
134 closure_env :: ClosureEnv,
135
136 -- The current global mapping from RdrNames of DataCons to
137 -- info table addresses.
138 -- When a new Unlinked is linked into the running image, or an existing
139 -- module in the image is replaced, the itbl_env must be updated
140 -- appropriately.
141 itbl_env :: !ItblEnv,
142
143 -- The currently loaded interpreted modules (home package)
144 bcos_loaded :: ![Linkable],
145
146 -- And the currently-loaded compiled modules (home package)
147 objs_loaded :: ![Linkable],
148
149 -- The currently-loaded packages; always object code
150 -- Held, as usual, in dependency order; though I am not sure if
151 -- that is really important
152 pkgs_loaded :: ![LinkerUnitId],
153
154 -- we need to remember the name of previous temporary DLL/.so
155 -- libraries so we can link them (see #10322)
156 temp_sos :: ![(FilePath, String)] }
157
158
159 emptyPLS :: DynFlags -> PersistentLinkerState
160 emptyPLS _ = PersistentLinkerState {
161 closure_env = emptyNameEnv,
162 itbl_env = emptyNameEnv,
163 pkgs_loaded = init_pkgs,
164 bcos_loaded = [],
165 objs_loaded = [],
166 temp_sos = [] }
167
168 -- Packages that don't need loading, because the compiler
169 -- shares them with the interpreted program.
170 --
171 -- The linker's symbol table is populated with RTS symbols using an
172 -- explicit list. See rts/Linker.c for details.
173 where init_pkgs = map toInstalledUnitId [rtsUnitId]
174
175
176 extendLoadedPkgs :: [InstalledUnitId] -> IO ()
177 extendLoadedPkgs pkgs =
178 modifyPLS_ $ \s ->
179 return s{ pkgs_loaded = pkgs ++ pkgs_loaded s }
180
181 extendLinkEnv :: [(Name,ForeignHValue)] -> IO ()
182 extendLinkEnv new_bindings =
183 modifyPLS_ $ \pls@PersistentLinkerState{..} -> do
184 let new_ce = extendClosureEnv closure_env new_bindings
185 return $! pls{ closure_env = new_ce }
186 -- strictness is important for not retaining old copies of the pls
187
188 deleteFromLinkEnv :: [Name] -> IO ()
189 deleteFromLinkEnv to_remove =
190 modifyPLS_ $ \pls -> do
191 let ce = closure_env pls
192 let new_ce = delListFromNameEnv ce to_remove
193 return pls{ closure_env = new_ce }
194
195 -- | Get the 'HValue' associated with the given name.
196 --
197 -- May cause loading the module that contains the name.
198 --
199 -- Throws a 'ProgramError' if loading fails or the name cannot be found.
200 getHValue :: HscEnv -> Name -> IO ForeignHValue
201 getHValue hsc_env name = do
202 initDynLinker hsc_env
203 pls <- modifyPLS $ \pls -> do
204 if (isExternalName name) then do
205 (pls', ok) <- linkDependencies hsc_env pls noSrcSpan
206 [nameModule name]
207 if (failed ok) then throwGhcExceptionIO (ProgramError "")
208 else return (pls', pls')
209 else
210 return (pls, pls)
211 case lookupNameEnv (closure_env pls) name of
212 Just (_,aa) -> return aa
213 Nothing
214 -> ASSERT2(isExternalName name, ppr name)
215 do let sym_to_find = nameToCLabel name "closure"
216 m <- lookupClosure hsc_env (unpackFS sym_to_find)
217 case m of
218 Just hvref -> mkFinalizedHValue hsc_env hvref
219 Nothing -> linkFail "ByteCodeLink.lookupCE"
220 (unpackFS sym_to_find)
221
222 linkDependencies :: HscEnv -> PersistentLinkerState
223 -> SrcSpan -> [Module]
224 -> IO (PersistentLinkerState, SuccessFlag)
225 linkDependencies hsc_env pls span needed_mods = do
226 -- initDynLinker (hsc_dflags hsc_env)
227 let hpt = hsc_HPT hsc_env
228 dflags = hsc_dflags hsc_env
229 -- The interpreter and dynamic linker can only handle object code built
230 -- the "normal" way, i.e. no non-std ways like profiling or ticky-ticky.
231 -- So here we check the build tag: if we're building a non-standard way
232 -- then we need to find & link object files built the "normal" way.
233 maybe_normal_osuf <- checkNonStdWay dflags span
234
235 -- Find what packages and linkables are required
236 (lnks, pkgs) <- getLinkDeps hsc_env hpt pls
237 maybe_normal_osuf span needed_mods
238
239 -- Link the packages and modules required
240 pls1 <- linkPackages' hsc_env pkgs pls
241 linkModules hsc_env pls1 lnks
242
243
244 -- | Temporarily extend the linker state.
245
246 withExtendedLinkEnv :: (ExceptionMonad m) =>
247 [(Name,ForeignHValue)] -> m a -> m a
248 withExtendedLinkEnv new_env action
249 = gbracket (liftIO $ extendLinkEnv new_env)
250 (\_ -> reset_old_env)
251 (\_ -> action)
252 where
253 -- Remember that the linker state might be side-effected
254 -- during the execution of the IO action, and we don't want to
255 -- lose those changes (we might have linked a new module or
256 -- package), so the reset action only removes the names we
257 -- added earlier.
258 reset_old_env = liftIO $ do
259 modifyPLS_ $ \pls ->
260 let cur = closure_env pls
261 new = delListFromNameEnv cur (map fst new_env)
262 in return pls{ closure_env = new }
263
264
265 -- | Display the persistent linker state.
266 showLinkerState :: DynFlags -> IO ()
267 showLinkerState dflags
268 = do pls <- readPLS
269 putLogMsg dflags NoReason SevDump noSrcSpan
270 (defaultDumpStyle dflags)
271 (vcat [text "----- Linker state -----",
272 text "Pkgs:" <+> ppr (pkgs_loaded pls),
273 text "Objs:" <+> ppr (objs_loaded pls),
274 text "BCOs:" <+> ppr (bcos_loaded pls)])
275
276
277 {- **********************************************************************
278
279 Initialisation
280
281 ********************************************************************* -}
282
283 -- | Initialise the dynamic linker. This entails
284 --
285 -- a) Calling the C initialisation procedure,
286 --
287 -- b) Loading any packages specified on the command line,
288 --
289 -- c) Loading any packages specified on the command line, now held in the
290 -- @-l@ options in @v_Opt_l@,
291 --
292 -- d) Loading any @.o\/.dll@ files specified on the command line, now held
293 -- in @ldInputs@,
294 --
295 -- e) Loading any MacOS frameworks.
296 --
297 -- NOTE: This function is idempotent; if called more than once, it does
298 -- nothing. This is useful in Template Haskell, where we call it before
299 -- trying to link.
300 --
301 initDynLinker :: HscEnv -> IO ()
302 initDynLinker hsc_env =
303 modifyMbPLS_ $ \pls -> do
304 case pls of
305 Just _ -> return pls
306 Nothing -> Just <$> reallyInitDynLinker hsc_env
307
308 reallyInitDynLinker :: HscEnv -> IO PersistentLinkerState
309 reallyInitDynLinker hsc_env = do
310 -- Initialise the linker state
311 let dflags = hsc_dflags hsc_env
312 pls0 = emptyPLS dflags
313
314 -- (a) initialise the C dynamic linker
315 initObjLinker hsc_env
316
317 -- (b) Load packages from the command-line (Note [preload packages])
318 pls <- linkPackages' hsc_env (preloadPackages (pkgState dflags)) pls0
319
320 -- steps (c), (d) and (e)
321 linkCmdLineLibs' hsc_env pls
322
323
324 linkCmdLineLibs :: HscEnv -> IO ()
325 linkCmdLineLibs hsc_env = do
326 initDynLinker hsc_env
327 modifyPLS_ $ \pls -> do
328 linkCmdLineLibs' hsc_env pls
329
330 linkCmdLineLibs' :: HscEnv -> PersistentLinkerState -> IO PersistentLinkerState
331 linkCmdLineLibs' hsc_env pls =
332 do
333 let dflags@(DynFlags { ldInputs = cmdline_ld_inputs
334 , libraryPaths = lib_paths_base})
335 = hsc_dflags hsc_env
336
337 -- (c) Link libraries from the command-line
338 let minus_ls_1 = [ lib | Option ('-':'l':lib) <- cmdline_ld_inputs ]
339
340 -- On Windows we want to add libpthread by default just as GCC would.
341 -- However because we don't know the actual name of pthread's dll we
342 -- need to defer this to the locateLib call so we can't initialize it
343 -- inside of the rts. Instead we do it here to be able to find the
344 -- import library for pthreads. See Trac #13210.
345 let platform = targetPlatform dflags
346 os = platformOS platform
347 minus_ls = case os of
348 OSMinGW32 -> "pthread" : minus_ls_1
349 _ -> minus_ls_1
350 -- See Note [Fork/Exec Windows]
351 gcc_paths <- getGCCPaths dflags os
352
353 lib_paths_env <- addEnvPaths "LIBRARY_PATH" lib_paths_base
354
355 maybePutStrLn dflags "Search directories (user):"
356 maybePutStr dflags (unlines $ map (" "++) lib_paths_env)
357 maybePutStrLn dflags "Search directories (gcc):"
358 maybePutStr dflags (unlines $ map (" "++) gcc_paths)
359
360 libspecs
361 <- mapM (locateLib hsc_env False lib_paths_env gcc_paths) minus_ls
362
363 -- (d) Link .o files from the command-line
364 classified_ld_inputs <- mapM (classifyLdInput dflags)
365 [ f | FileOption _ f <- cmdline_ld_inputs ]
366
367 -- (e) Link any MacOS frameworks
368 let platform = targetPlatform dflags
369 let (framework_paths, frameworks) =
370 if platformUsesFrameworks platform
371 then (frameworkPaths dflags, cmdlineFrameworks dflags)
372 else ([],[])
373
374 -- Finally do (c),(d),(e)
375 let cmdline_lib_specs = catMaybes classified_ld_inputs
376 ++ libspecs
377 ++ map Framework frameworks
378 if null cmdline_lib_specs then return pls
379 else do
380
381 -- Add directories to library search paths, this only has an effect
382 -- on Windows. On Unix OSes this function is a NOP.
383 let all_paths = let paths = takeDirectory (fst $ sPgm_c $ settings dflags)
384 : framework_paths
385 ++ lib_paths_base
386 ++ [ takeDirectory dll | DLLPath dll <- libspecs ]
387 in nub $ map normalise paths
388 let lib_paths = nub $ lib_paths_base ++ gcc_paths
389 all_paths_env <- addEnvPaths "LD_LIBRARY_PATH" all_paths
390 pathCache <- mapM (addLibrarySearchPath hsc_env) all_paths_env
391
392 pls1 <- foldM (preloadLib hsc_env lib_paths framework_paths) pls
393 cmdline_lib_specs
394 maybePutStr dflags "final link ... "
395 ok <- resolveObjs hsc_env
396
397 -- DLLs are loaded, reset the search paths
398 mapM_ (removeLibrarySearchPath hsc_env) $ reverse pathCache
399
400 if succeeded ok then maybePutStrLn dflags "done"
401 else throwGhcExceptionIO (ProgramError "linking extra libraries/objects failed")
402
403 return pls1
404
405 {- Note [preload packages]
406
407 Why do we need to preload packages from the command line? This is an
408 explanation copied from #2437:
409
410 I tried to implement the suggestion from #3560, thinking it would be
411 easy, but there are two reasons we link in packages eagerly when they
412 are mentioned on the command line:
413
414 * So that you can link in extra object files or libraries that
415 depend on the packages. e.g. ghc -package foo -lbar where bar is a
416 C library that depends on something in foo. So we could link in
417 foo eagerly if and only if there are extra C libs or objects to
418 link in, but....
419
420 * Haskell code can depend on a C function exported by a package, and
421 the normal dependency tracking that TH uses can't know about these
422 dependencies. The test ghcilink004 relies on this, for example.
423
424 I conclude that we need two -package flags: one that says "this is a
425 package I want to make available", and one that says "this is a
426 package I want to link in eagerly". Would that be too complicated for
427 users?
428 -}
429
430 classifyLdInput :: DynFlags -> FilePath -> IO (Maybe LibrarySpec)
431 classifyLdInput dflags f
432 | isObjectFilename platform f = return (Just (Object f))
433 | isDynLibFilename platform f = return (Just (DLLPath f))
434 | otherwise = do
435 putLogMsg dflags NoReason SevInfo noSrcSpan
436 (defaultUserStyle dflags)
437 (text ("Warning: ignoring unrecognised input `" ++ f ++ "'"))
438 return Nothing
439 where platform = targetPlatform dflags
440
441 preloadLib
442 :: HscEnv -> [String] -> [String] -> PersistentLinkerState
443 -> LibrarySpec -> IO PersistentLinkerState
444 preloadLib hsc_env lib_paths framework_paths pls lib_spec = do
445 maybePutStr dflags ("Loading object " ++ showLS lib_spec ++ " ... ")
446 case lib_spec of
447 Object static_ish -> do
448 (b, pls1) <- preload_static lib_paths static_ish
449 maybePutStrLn dflags (if b then "done" else "not found")
450 return pls1
451
452 Archive static_ish -> do
453 b <- preload_static_archive lib_paths static_ish
454 maybePutStrLn dflags (if b then "done" else "not found")
455 return pls
456
457 DLL dll_unadorned -> do
458 maybe_errstr <- loadDLL hsc_env (mkSOName platform dll_unadorned)
459 case maybe_errstr of
460 Nothing -> maybePutStrLn dflags "done"
461 Just mm | platformOS platform /= OSDarwin ->
462 preloadFailed mm lib_paths lib_spec
463 Just mm | otherwise -> do
464 -- As a backup, on Darwin, try to also load a .so file
465 -- since (apparently) some things install that way - see
466 -- ticket #8770.
467 let libfile = ("lib" ++ dll_unadorned) <.> "so"
468 err2 <- loadDLL hsc_env libfile
469 case err2 of
470 Nothing -> maybePutStrLn dflags "done"
471 Just _ -> preloadFailed mm lib_paths lib_spec
472 return pls
473
474 DLLPath dll_path -> do
475 do maybe_errstr <- loadDLL hsc_env dll_path
476 case maybe_errstr of
477 Nothing -> maybePutStrLn dflags "done"
478 Just mm -> preloadFailed mm lib_paths lib_spec
479 return pls
480
481 Framework framework ->
482 if platformUsesFrameworks (targetPlatform dflags)
483 then do maybe_errstr <- loadFramework hsc_env framework_paths framework
484 case maybe_errstr of
485 Nothing -> maybePutStrLn dflags "done"
486 Just mm -> preloadFailed mm framework_paths lib_spec
487 return pls
488 else panic "preloadLib Framework"
489
490 where
491 dflags = hsc_dflags hsc_env
492
493 platform = targetPlatform dflags
494
495 preloadFailed :: String -> [String] -> LibrarySpec -> IO ()
496 preloadFailed sys_errmsg paths spec
497 = do maybePutStr dflags "failed.\n"
498 throwGhcExceptionIO $
499 CmdLineError (
500 "user specified .o/.so/.DLL could not be loaded ("
501 ++ sys_errmsg ++ ")\nWhilst trying to load: "
502 ++ showLS spec ++ "\nAdditional directories searched:"
503 ++ (if null paths then " (none)" else
504 intercalate "\n" (map (" "++) paths)))
505
506 -- Not interested in the paths in the static case.
507 preload_static _paths name
508 = do b <- doesFileExist name
509 if not b then return (False, pls)
510 else if dynamicGhc
511 then do pls1 <- dynLoadObjs hsc_env pls [name]
512 return (True, pls1)
513 else do loadObj hsc_env name
514 return (True, pls)
515
516 preload_static_archive _paths name
517 = do b <- doesFileExist name
518 if not b then return False
519 else do if dynamicGhc
520 then throwGhcExceptionIO $
521 CmdLineError dynamic_msg
522 else loadArchive hsc_env name
523 return True
524 where
525 dynamic_msg = unlines
526 [ "User-specified static library could not be loaded ("
527 ++ name ++ ")"
528 , "Loading static libraries is not supported in this configuration."
529 , "Try using a dynamic library instead."
530 ]
531
532
533 {- **********************************************************************
534
535 Link a byte-code expression
536
537 ********************************************************************* -}
538
539 -- | Link a single expression, /including/ first linking packages and
540 -- modules that this expression depends on.
541 --
542 -- Raises an IO exception ('ProgramError') if it can't find a compiled
543 -- version of the dependents to link.
544 --
545 linkExpr :: HscEnv -> SrcSpan -> UnlinkedBCO -> IO ForeignHValue
546 linkExpr hsc_env span root_ul_bco
547 = do {
548 -- Initialise the linker (if it's not been done already)
549 ; initDynLinker hsc_env
550
551 -- Take lock for the actual work.
552 ; modifyPLS $ \pls0 -> do {
553
554 -- Link the packages and modules required
555 ; (pls, ok) <- linkDependencies hsc_env pls0 span needed_mods
556 ; if failed ok then
557 throwGhcExceptionIO (ProgramError "")
558 else do {
559
560 -- Link the expression itself
561 let ie = itbl_env pls
562 ce = closure_env pls
563
564 -- Link the necessary packages and linkables
565
566 ; let nobreakarray = error "no break array"
567 bco_ix = mkNameEnv [(unlinkedBCOName root_ul_bco, 0)]
568 ; resolved <- linkBCO hsc_env ie ce bco_ix nobreakarray root_ul_bco
569 ; [root_hvref] <- createBCOs hsc_env [resolved]
570 ; fhv <- mkFinalizedHValue hsc_env root_hvref
571 ; return (pls, fhv)
572 }}}
573 where
574 free_names = uniqDSetToList (bcoFreeNames root_ul_bco)
575
576 needed_mods :: [Module]
577 needed_mods = [ nameModule n | n <- free_names,
578 isExternalName n, -- Names from other modules
579 not (isWiredInName n) -- Exclude wired-in names
580 ] -- (see note below)
581 -- Exclude wired-in names because we may not have read
582 -- their interface files, so getLinkDeps will fail
583 -- All wired-in names are in the base package, which we link
584 -- by default, so we can safely ignore them here.
585
586 dieWith :: DynFlags -> SrcSpan -> MsgDoc -> IO a
587 dieWith dflags span msg = throwGhcExceptionIO (ProgramError (showSDoc dflags (mkLocMessage SevFatal span msg)))
588
589
590 checkNonStdWay :: DynFlags -> SrcSpan -> IO (Maybe FilePath)
591 checkNonStdWay dflags srcspan
592 | gopt Opt_ExternalInterpreter dflags = return Nothing
593 -- with -fexternal-interpreter we load the .o files, whatever way
594 -- they were built. If they were built for a non-std way, then
595 -- we will use the appropriate variant of the iserv binary to load them.
596
597 | interpWays == haskellWays = return Nothing
598 -- Only if we are compiling with the same ways as GHC is built
599 -- with, can we dynamically load those object files. (see #3604)
600
601 | objectSuf dflags == normalObjectSuffix && not (null haskellWays)
602 = failNonStd dflags srcspan
603
604 | otherwise = return (Just (interpTag ++ "o"))
605 where
606 haskellWays = filter (not . wayRTSOnly) (ways dflags)
607 interpTag = case mkBuildTag interpWays of
608 "" -> ""
609 tag -> tag ++ "_"
610
611 normalObjectSuffix :: String
612 normalObjectSuffix = phaseInputExt StopLn
613
614 failNonStd :: DynFlags -> SrcSpan -> IO (Maybe FilePath)
615 failNonStd dflags srcspan = dieWith dflags srcspan $
616 text "Cannot load" <+> compWay <+>
617 text "objects when GHC is built" <+> ghciWay $$
618 text "To fix this, either:" $$
619 text " (1) Use -fexternal-interpreter, or" $$
620 text " (2) Build the program twice: once" <+>
621 ghciWay <> text ", and then" $$
622 text " with" <+> compWay <+>
623 text "using -osuf to set a different object file suffix."
624 where compWay
625 | WayDyn `elem` ways dflags = text "-dynamic"
626 | WayProf `elem` ways dflags = text "-prof"
627 | otherwise = text "normal"
628 ghciWay
629 | dynamicGhc = text "with -dynamic"
630 | rtsIsProfiled = text "with -prof"
631 | otherwise = text "the normal way"
632
633 getLinkDeps :: HscEnv -> HomePackageTable
634 -> PersistentLinkerState
635 -> Maybe FilePath -- replace object suffices?
636 -> SrcSpan -- for error messages
637 -> [Module] -- If you need these
638 -> IO ([Linkable], [InstalledUnitId]) -- ... then link these first
639 -- Fails with an IO exception if it can't find enough files
640
641 getLinkDeps hsc_env hpt pls replace_osuf span mods
642 -- Find all the packages and linkables that a set of modules depends on
643 = do {
644 -- 1. Find the dependent home-pkg-modules/packages from each iface
645 -- (omitting modules from the interactive package, which is already linked)
646 ; (mods_s, pkgs_s) <- follow_deps (filterOut isInteractiveModule mods)
647 emptyUniqDSet emptyUniqDSet;
648
649 ; let {
650 -- 2. Exclude ones already linked
651 -- Main reason: avoid findModule calls in get_linkable
652 mods_needed = mods_s `minusList` linked_mods ;
653 pkgs_needed = pkgs_s `minusList` pkgs_loaded pls ;
654
655 linked_mods = map (moduleName.linkableModule)
656 (objs_loaded pls ++ bcos_loaded pls) }
657
658 -- 3. For each dependent module, find its linkable
659 -- This will either be in the HPT or (in the case of one-shot
660 -- compilation) we may need to use maybe_getFileLinkable
661 ; let { osuf = objectSuf dflags }
662 ; lnks_needed <- mapM (get_linkable osuf) mods_needed
663
664 ; return (lnks_needed, pkgs_needed) }
665 where
666 dflags = hsc_dflags hsc_env
667 this_pkg = thisPackage dflags
668
669 -- The ModIface contains the transitive closure of the module dependencies
670 -- within the current package, *except* for boot modules: if we encounter
671 -- a boot module, we have to find its real interface and discover the
672 -- dependencies of that. Hence we need to traverse the dependency
673 -- tree recursively. See bug #936, testcase ghci/prog007.
674 follow_deps :: [Module] -- modules to follow
675 -> UniqDSet ModuleName -- accum. module dependencies
676 -> UniqDSet InstalledUnitId -- accum. package dependencies
677 -> IO ([ModuleName], [InstalledUnitId]) -- result
678 follow_deps [] acc_mods acc_pkgs
679 = return (uniqDSetToList acc_mods, uniqDSetToList acc_pkgs)
680 follow_deps (mod:mods) acc_mods acc_pkgs
681 = do
682 mb_iface <- initIfaceCheck (text "getLinkDeps") hsc_env $
683 loadInterface msg mod (ImportByUser False)
684 iface <- case mb_iface of
685 Maybes.Failed err -> throwGhcExceptionIO (ProgramError (showSDoc dflags err))
686 Maybes.Succeeded iface -> return iface
687
688 when (mi_boot iface) $ link_boot_mod_error mod
689
690 let
691 pkg = moduleUnitId mod
692 deps = mi_deps iface
693
694 pkg_deps = dep_pkgs deps
695 (boot_deps, mod_deps) = partitionWith is_boot (dep_mods deps)
696 where is_boot (m,True) = Left m
697 is_boot (m,False) = Right m
698
699 boot_deps' = filter (not . (`elementOfUniqDSet` acc_mods)) boot_deps
700 acc_mods' = addListToUniqDSet acc_mods (moduleName mod : mod_deps)
701 acc_pkgs' = addListToUniqDSet acc_pkgs $ map fst pkg_deps
702 --
703 if pkg /= this_pkg
704 then follow_deps mods acc_mods (addOneToUniqDSet acc_pkgs' (toInstalledUnitId pkg))
705 else follow_deps (map (mkModule this_pkg) boot_deps' ++ mods)
706 acc_mods' acc_pkgs'
707 where
708 msg = text "need to link module" <+> ppr mod <+>
709 text "due to use of Template Haskell"
710
711
712 link_boot_mod_error mod =
713 throwGhcExceptionIO (ProgramError (showSDoc dflags (
714 text "module" <+> ppr mod <+>
715 text "cannot be linked; it is only available as a boot module")))
716
717 no_obj :: Outputable a => a -> IO b
718 no_obj mod = dieWith dflags span $
719 text "cannot find object file for module " <>
720 quotes (ppr mod) $$
721 while_linking_expr
722
723 while_linking_expr = text "while linking an interpreted expression"
724
725 -- This one is a build-system bug
726
727 get_linkable osuf mod_name -- A home-package module
728 | Just mod_info <- lookupHpt hpt mod_name
729 = adjust_linkable (Maybes.expectJust "getLinkDeps" (hm_linkable mod_info))
730 | otherwise
731 = do -- It's not in the HPT because we are in one shot mode,
732 -- so use the Finder to get a ModLocation...
733 mb_stuff <- findHomeModule hsc_env mod_name
734 case mb_stuff of
735 Found loc mod -> found loc mod
736 _ -> no_obj mod_name
737 where
738 found loc mod = do {
739 -- ...and then find the linkable for it
740 mb_lnk <- findObjectLinkableMaybe mod loc ;
741 case mb_lnk of {
742 Nothing -> no_obj mod ;
743 Just lnk -> adjust_linkable lnk
744 }}
745
746 adjust_linkable lnk
747 | Just new_osuf <- replace_osuf = do
748 new_uls <- mapM (adjust_ul new_osuf)
749 (linkableUnlinked lnk)
750 return lnk{ linkableUnlinked=new_uls }
751 | otherwise =
752 return lnk
753
754 adjust_ul new_osuf (DotO file) = do
755 MASSERT(osuf `isSuffixOf` file)
756 let file_base = fromJust (stripExtension osuf file)
757 new_file = file_base <.> new_osuf
758 ok <- doesFileExist new_file
759 if (not ok)
760 then dieWith dflags span $
761 text "cannot find object file "
762 <> quotes (text new_file) $$ while_linking_expr
763 else return (DotO new_file)
764 adjust_ul _ (DotA fp) = panic ("adjust_ul DotA " ++ show fp)
765 adjust_ul _ (DotDLL fp) = panic ("adjust_ul DotDLL " ++ show fp)
766 adjust_ul _ l@(BCOs {}) = return l
767
768
769
770 {- **********************************************************************
771
772 Loading a Decls statement
773
774 ********************************************************************* -}
775
776 linkDecls :: HscEnv -> SrcSpan -> CompiledByteCode -> IO ()
777 linkDecls hsc_env span cbc@CompiledByteCode{..} = do
778 -- Initialise the linker (if it's not been done already)
779 initDynLinker hsc_env
780
781 -- Take lock for the actual work.
782 modifyPLS $ \pls0 -> do
783
784 -- Link the packages and modules required
785 (pls, ok) <- linkDependencies hsc_env pls0 span needed_mods
786 if failed ok
787 then throwGhcExceptionIO (ProgramError "")
788 else do
789
790 -- Link the expression itself
791 let ie = plusNameEnv (itbl_env pls) bc_itbls
792 ce = closure_env pls
793
794 -- Link the necessary packages and linkables
795 new_bindings <- linkSomeBCOs hsc_env ie ce [cbc]
796 nms_fhvs <- makeForeignNamedHValueRefs hsc_env new_bindings
797 let pls2 = pls { closure_env = extendClosureEnv ce nms_fhvs
798 , itbl_env = ie }
799 return (pls2, ())
800 where
801 free_names = uniqDSetToList $
802 foldr (unionUniqDSets . bcoFreeNames) emptyUniqDSet bc_bcos
803
804 needed_mods :: [Module]
805 needed_mods = [ nameModule n | n <- free_names,
806 isExternalName n, -- Names from other modules
807 not (isWiredInName n) -- Exclude wired-in names
808 ] -- (see note below)
809 -- Exclude wired-in names because we may not have read
810 -- their interface files, so getLinkDeps will fail
811 -- All wired-in names are in the base package, which we link
812 -- by default, so we can safely ignore them here.
813
814 {- **********************************************************************
815
816 Loading a single module
817
818 ********************************************************************* -}
819
820 linkModule :: HscEnv -> Module -> IO ()
821 linkModule hsc_env mod = do
822 initDynLinker hsc_env
823 modifyPLS_ $ \pls -> do
824 (pls', ok) <- linkDependencies hsc_env pls noSrcSpan [mod]
825 if (failed ok) then throwGhcExceptionIO (ProgramError "could not link module")
826 else return pls'
827
828 {- **********************************************************************
829
830 Link some linkables
831 The linkables may consist of a mixture of
832 byte-code modules and object modules
833
834 ********************************************************************* -}
835
836 linkModules :: HscEnv -> PersistentLinkerState -> [Linkable]
837 -> IO (PersistentLinkerState, SuccessFlag)
838 linkModules hsc_env pls linkables
839 = mask_ $ do -- don't want to be interrupted by ^C in here
840
841 let (objs, bcos) = partition isObjectLinkable
842 (concatMap partitionLinkable linkables)
843
844 -- Load objects first; they can't depend on BCOs
845 (pls1, ok_flag) <- dynLinkObjs hsc_env pls objs
846
847 if failed ok_flag then
848 return (pls1, Failed)
849 else do
850 pls2 <- dynLinkBCOs hsc_env pls1 bcos
851 return (pls2, Succeeded)
852
853
854 -- HACK to support f-x-dynamic in the interpreter; no other purpose
855 partitionLinkable :: Linkable -> [Linkable]
856 partitionLinkable li
857 = let li_uls = linkableUnlinked li
858 li_uls_obj = filter isObject li_uls
859 li_uls_bco = filter isInterpretable li_uls
860 in
861 case (li_uls_obj, li_uls_bco) of
862 (_:_, _:_) -> [li {linkableUnlinked=li_uls_obj},
863 li {linkableUnlinked=li_uls_bco}]
864 _ -> [li]
865
866 findModuleLinkable_maybe :: [Linkable] -> Module -> Maybe Linkable
867 findModuleLinkable_maybe lis mod
868 = case [LM time nm us | LM time nm us <- lis, nm == mod] of
869 [] -> Nothing
870 [li] -> Just li
871 _ -> pprPanic "findModuleLinkable" (ppr mod)
872
873 linkableInSet :: Linkable -> [Linkable] -> Bool
874 linkableInSet l objs_loaded =
875 case findModuleLinkable_maybe objs_loaded (linkableModule l) of
876 Nothing -> False
877 Just m -> linkableTime l == linkableTime m
878
879
880 {- **********************************************************************
881
882 The object-code linker
883
884 ********************************************************************* -}
885
886 dynLinkObjs :: HscEnv -> PersistentLinkerState -> [Linkable]
887 -> IO (PersistentLinkerState, SuccessFlag)
888 dynLinkObjs hsc_env pls objs = do
889 -- Load the object files and link them
890 let (objs_loaded', new_objs) = rmDupLinkables (objs_loaded pls) objs
891 pls1 = pls { objs_loaded = objs_loaded' }
892 unlinkeds = concatMap linkableUnlinked new_objs
893 wanted_objs = map nameOfObject unlinkeds
894
895 if interpreterDynamic (hsc_dflags hsc_env)
896 then do pls2 <- dynLoadObjs hsc_env pls1 wanted_objs
897 return (pls2, Succeeded)
898 else do mapM_ (loadObj hsc_env) wanted_objs
899
900 -- Link them all together
901 ok <- resolveObjs hsc_env
902
903 -- If resolving failed, unload all our
904 -- object modules and carry on
905 if succeeded ok then do
906 return (pls1, Succeeded)
907 else do
908 pls2 <- unload_wkr hsc_env [] pls1
909 return (pls2, Failed)
910
911
912 dynLoadObjs :: HscEnv -> PersistentLinkerState -> [FilePath]
913 -> IO PersistentLinkerState
914 dynLoadObjs _ pls [] = return pls
915 dynLoadObjs hsc_env pls objs = do
916 let dflags = hsc_dflags hsc_env
917 let platform = targetPlatform dflags
918 let minus_ls = [ lib | Option ('-':'l':lib) <- ldInputs dflags ]
919 let minus_big_ls = [ lib | Option ('-':'L':lib) <- ldInputs dflags ]
920 (soFile, libPath , libName) <-
921 newTempLibName dflags TFL_CurrentModule (soExt platform)
922 let
923 dflags2 = dflags {
924 -- We don't want the original ldInputs in
925 -- (they're already linked in), but we do want
926 -- to link against previous dynLoadObjs
927 -- libraries if there were any, so that the linker
928 -- can resolve dependencies when it loads this
929 -- library.
930 ldInputs =
931 concatMap (\l -> [ Option ("-l" ++ l) ])
932 (nub $ snd <$> temp_sos pls)
933 ++ concatMap (\lp -> [ Option ("-L" ++ lp)
934 , Option "-Xlinker"
935 , Option "-rpath"
936 , Option "-Xlinker"
937 , Option lp ])
938 (nub $ fst <$> temp_sos pls)
939 ++ concatMap
940 (\lp ->
941 [ Option ("-L" ++ lp)
942 , Option "-Xlinker"
943 , Option "-rpath"
944 , Option "-Xlinker"
945 , Option lp
946 ])
947 minus_big_ls
948 -- See Note [-Xlinker -rpath vs -Wl,-rpath]
949 ++ map (\l -> Option ("-l" ++ l)) minus_ls,
950 -- Add -l options and -L options from dflags.
951 --
952 -- When running TH for a non-dynamic way, we still
953 -- need to make -l flags to link against the dynamic
954 -- libraries, so we need to add WayDyn to ways.
955 --
956 -- Even if we're e.g. profiling, we still want
957 -- the vanilla dynamic libraries, so we set the
958 -- ways / build tag to be just WayDyn.
959 ways = [WayDyn],
960 buildTag = mkBuildTag [WayDyn],
961 outputFile = Just soFile
962 }
963 -- link all "loaded packages" so symbols in those can be resolved
964 -- Note: We are loading packages with local scope, so to see the
965 -- symbols in this link we must link all loaded packages again.
966 linkDynLib dflags2 objs (pkgs_loaded pls)
967
968 -- if we got this far, extend the lifetime of the library file
969 changeTempFilesLifetime dflags TFL_GhcSession [soFile]
970 m <- loadDLL hsc_env soFile
971 case m of
972 Nothing -> return pls { temp_sos = (libPath, libName) : temp_sos pls }
973 Just err -> panic ("Loading temp shared object failed: " ++ err)
974
975 rmDupLinkables :: [Linkable] -- Already loaded
976 -> [Linkable] -- New linkables
977 -> ([Linkable], -- New loaded set (including new ones)
978 [Linkable]) -- New linkables (excluding dups)
979 rmDupLinkables already ls
980 = go already [] ls
981 where
982 go already extras [] = (already, extras)
983 go already extras (l:ls)
984 | linkableInSet l already = go already extras ls
985 | otherwise = go (l:already) (l:extras) ls
986
987 {- **********************************************************************
988
989 The byte-code linker
990
991 ********************************************************************* -}
992
993
994 dynLinkBCOs :: HscEnv -> PersistentLinkerState -> [Linkable]
995 -> IO PersistentLinkerState
996 dynLinkBCOs hsc_env pls bcos = do
997
998 let (bcos_loaded', new_bcos) = rmDupLinkables (bcos_loaded pls) bcos
999 pls1 = pls { bcos_loaded = bcos_loaded' }
1000 unlinkeds :: [Unlinked]
1001 unlinkeds = concatMap linkableUnlinked new_bcos
1002
1003 cbcs :: [CompiledByteCode]
1004 cbcs = map byteCodeOfObject unlinkeds
1005
1006
1007 ies = map bc_itbls cbcs
1008 gce = closure_env pls
1009 final_ie = foldr plusNameEnv (itbl_env pls) ies
1010
1011 names_and_refs <- linkSomeBCOs hsc_env final_ie gce cbcs
1012
1013 -- We only want to add the external ones to the ClosureEnv
1014 let (to_add, to_drop) = partition (isExternalName.fst) names_and_refs
1015
1016 -- Immediately release any HValueRefs we're not going to add
1017 freeHValueRefs hsc_env (map snd to_drop)
1018 -- Wrap finalizers on the ones we want to keep
1019 new_binds <- makeForeignNamedHValueRefs hsc_env to_add
1020
1021 return pls1 { closure_env = extendClosureEnv gce new_binds,
1022 itbl_env = final_ie }
1023
1024 -- Link a bunch of BCOs and return references to their values
1025 linkSomeBCOs :: HscEnv
1026 -> ItblEnv
1027 -> ClosureEnv
1028 -> [CompiledByteCode]
1029 -> IO [(Name,HValueRef)]
1030 -- The returned HValueRefs are associated 1-1 with
1031 -- the incoming unlinked BCOs. Each gives the
1032 -- value of the corresponding unlinked BCO
1033
1034 linkSomeBCOs hsc_env ie ce mods = foldr fun do_link mods []
1035 where
1036 fun CompiledByteCode{..} inner accum =
1037 case bc_breaks of
1038 Nothing -> inner ((panic "linkSomeBCOs: no break array", bc_bcos) : accum)
1039 Just mb -> withForeignRef (modBreaks_flags mb) $ \breakarray ->
1040 inner ((breakarray, bc_bcos) : accum)
1041
1042 do_link [] = return []
1043 do_link mods = do
1044 let flat = [ (breakarray, bco) | (breakarray, bcos) <- mods, bco <- bcos ]
1045 names = map (unlinkedBCOName . snd) flat
1046 bco_ix = mkNameEnv (zip names [0..])
1047 resolved <- sequence [ linkBCO hsc_env ie ce bco_ix breakarray bco
1048 | (breakarray, bco) <- flat ]
1049 hvrefs <- createBCOs hsc_env resolved
1050 return (zip names hvrefs)
1051
1052 -- | Useful to apply to the result of 'linkSomeBCOs'
1053 makeForeignNamedHValueRefs
1054 :: HscEnv -> [(Name,HValueRef)] -> IO [(Name,ForeignHValue)]
1055 makeForeignNamedHValueRefs hsc_env bindings =
1056 mapM (\(n, hvref) -> (n,) <$> mkFinalizedHValue hsc_env hvref) bindings
1057
1058 {- **********************************************************************
1059
1060 Unload some object modules
1061
1062 ********************************************************************* -}
1063
1064 -- ---------------------------------------------------------------------------
1065 -- | Unloading old objects ready for a new compilation sweep.
1066 --
1067 -- The compilation manager provides us with a list of linkables that it
1068 -- considers \"stable\", i.e. won't be recompiled this time around. For
1069 -- each of the modules current linked in memory,
1070 --
1071 -- * if the linkable is stable (and it's the same one -- the user may have
1072 -- recompiled the module on the side), we keep it,
1073 --
1074 -- * otherwise, we unload it.
1075 --
1076 -- * we also implicitly unload all temporary bindings at this point.
1077 --
1078 unload :: HscEnv
1079 -> [Linkable] -- ^ The linkables to *keep*.
1080 -> IO ()
1081 unload hsc_env linkables
1082 = mask_ $ do -- mask, so we're safe from Ctrl-C in here
1083
1084 -- Initialise the linker (if it's not been done already)
1085 initDynLinker hsc_env
1086
1087 new_pls
1088 <- modifyPLS $ \pls -> do
1089 pls1 <- unload_wkr hsc_env linkables pls
1090 return (pls1, pls1)
1091
1092 let dflags = hsc_dflags hsc_env
1093 debugTraceMsg dflags 3 $
1094 text "unload: retaining objs" <+> ppr (objs_loaded new_pls)
1095 debugTraceMsg dflags 3 $
1096 text "unload: retaining bcos" <+> ppr (bcos_loaded new_pls)
1097 return ()
1098
1099 unload_wkr :: HscEnv
1100 -> [Linkable] -- stable linkables
1101 -> PersistentLinkerState
1102 -> IO PersistentLinkerState
1103 -- Does the core unload business
1104 -- (the wrapper blocks exceptions and deals with the PLS get and put)
1105
1106 unload_wkr hsc_env keep_linkables pls@PersistentLinkerState{..} = do
1107 -- NB. careful strictness here to avoid keeping the old PLS when
1108 -- we're unloading some code. -fghci-leak-check with the tests in
1109 -- testsuite/ghci can detect space leaks here.
1110
1111 let (objs_to_keep, bcos_to_keep) = partition isObjectLinkable keep_linkables
1112
1113 discard keep l = not (linkableInSet l keep)
1114
1115 (objs_to_unload, remaining_objs_loaded) =
1116 partition (discard objs_to_keep) objs_loaded
1117 (bcos_to_unload, remaining_bcos_loaded) =
1118 partition (discard bcos_to_keep) bcos_loaded
1119
1120 mapM_ unloadObjs objs_to_unload
1121 mapM_ unloadObjs bcos_to_unload
1122
1123 -- If we unloaded any object files at all, we need to purge the cache
1124 -- of lookupSymbol results.
1125 when (not (null (objs_to_unload ++
1126 filter (not . null . linkableObjs) bcos_to_unload))) $
1127 purgeLookupSymbolCache hsc_env
1128
1129 let !bcos_retained = mkModuleSet $ map linkableModule remaining_bcos_loaded
1130
1131 -- Note that we want to remove all *local*
1132 -- (i.e. non-isExternal) names too (these are the
1133 -- temporary bindings from the command line).
1134 keep_name (n,_) = isExternalName n &&
1135 nameModule n `elemModuleSet` bcos_retained
1136
1137 itbl_env' = filterNameEnv keep_name itbl_env
1138 closure_env' = filterNameEnv keep_name closure_env
1139
1140 !new_pls = pls { itbl_env = itbl_env',
1141 closure_env = closure_env',
1142 bcos_loaded = remaining_bcos_loaded,
1143 objs_loaded = remaining_objs_loaded }
1144
1145 return new_pls
1146 where
1147 unloadObjs :: Linkable -> IO ()
1148 unloadObjs lnk
1149 | dynamicGhc = return ()
1150 -- We don't do any cleanup when linking objects with the
1151 -- dynamic linker. Doing so introduces extra complexity for
1152 -- not much benefit.
1153 | otherwise
1154 = mapM_ (unloadObj hsc_env) [f | DotO f <- linkableUnlinked lnk]
1155 -- The components of a BCO linkable may contain
1156 -- dot-o files. Which is very confusing.
1157 --
1158 -- But the BCO parts can be unlinked just by
1159 -- letting go of them (plus of course depopulating
1160 -- the symbol table which is done in the main body)
1161
1162 {- **********************************************************************
1163
1164 Loading packages
1165
1166 ********************************************************************* -}
1167
1168 data LibrarySpec
1169 = Object FilePath -- Full path name of a .o file, including trailing .o
1170 -- For dynamic objects only, try to find the object
1171 -- file in all the directories specified in
1172 -- v_Library_paths before giving up.
1173
1174 | Archive FilePath -- Full path name of a .a file, including trailing .a
1175
1176 | DLL String -- "Unadorned" name of a .DLL/.so
1177 -- e.g. On unix "qt" denotes "libqt.so"
1178 -- On Windows "burble" denotes "burble.DLL" or "libburble.dll"
1179 -- loadDLL is platform-specific and adds the lib/.so/.DLL
1180 -- suffixes platform-dependently
1181
1182 | DLLPath FilePath -- Absolute or relative pathname to a dynamic library
1183 -- (ends with .dll or .so).
1184
1185 | Framework String -- Only used for darwin, but does no harm
1186
1187 -- If this package is already part of the GHCi binary, we'll already
1188 -- have the right DLLs for this package loaded, so don't try to
1189 -- load them again.
1190 --
1191 -- But on Win32 we must load them 'again'; doing so is a harmless no-op
1192 -- as far as the loader is concerned, but it does initialise the list
1193 -- of DLL handles that rts/Linker.c maintains, and that in turn is
1194 -- used by lookupSymbol. So we must call addDLL for each library
1195 -- just to get the DLL handle into the list.
1196 partOfGHCi :: [PackageName]
1197 partOfGHCi
1198 | isWindowsHost || isDarwinHost = []
1199 | otherwise = map (PackageName . mkFastString)
1200 ["base", "template-haskell", "editline"]
1201
1202 showLS :: LibrarySpec -> String
1203 showLS (Object nm) = "(static) " ++ nm
1204 showLS (Archive nm) = "(static archive) " ++ nm
1205 showLS (DLL nm) = "(dynamic) " ++ nm
1206 showLS (DLLPath nm) = "(dynamic) " ++ nm
1207 showLS (Framework nm) = "(framework) " ++ nm
1208
1209 -- TODO: Make this type more precise
1210 type LinkerUnitId = InstalledUnitId
1211
1212 -- | Link exactly the specified packages, and their dependents (unless of
1213 -- course they are already linked). The dependents are linked
1214 -- automatically, and it doesn't matter what order you specify the input
1215 -- packages.
1216 --
1217 linkPackages :: HscEnv -> [LinkerUnitId] -> IO ()
1218 -- NOTE: in fact, since each module tracks all the packages it depends on,
1219 -- we don't really need to use the package-config dependencies.
1220 --
1221 -- However we do need the package-config stuff (to find aux libs etc),
1222 -- and following them lets us load libraries in the right order, which
1223 -- perhaps makes the error message a bit more localised if we get a link
1224 -- failure. So the dependency walking code is still here.
1225
1226 linkPackages hsc_env new_pkgs = do
1227 -- It's probably not safe to try to load packages concurrently, so we take
1228 -- a lock.
1229 initDynLinker hsc_env
1230 modifyPLS_ $ \pls -> do
1231 linkPackages' hsc_env new_pkgs pls
1232
1233 linkPackages' :: HscEnv -> [LinkerUnitId] -> PersistentLinkerState
1234 -> IO PersistentLinkerState
1235 linkPackages' hsc_env new_pks pls = do
1236 pkgs' <- link (pkgs_loaded pls) new_pks
1237 return $! pls { pkgs_loaded = pkgs' }
1238 where
1239 dflags = hsc_dflags hsc_env
1240
1241 link :: [LinkerUnitId] -> [LinkerUnitId] -> IO [LinkerUnitId]
1242 link pkgs new_pkgs =
1243 foldM link_one pkgs new_pkgs
1244
1245 link_one pkgs new_pkg
1246 | new_pkg `elem` pkgs -- Already linked
1247 = return pkgs
1248
1249 | Just pkg_cfg <- lookupInstalledPackage dflags new_pkg
1250 = do { -- Link dependents first
1251 pkgs' <- link pkgs (depends pkg_cfg)
1252 -- Now link the package itself
1253 ; linkPackage hsc_env pkg_cfg
1254 ; return (new_pkg : pkgs') }
1255
1256 | otherwise
1257 = throwGhcExceptionIO (CmdLineError ("unknown package: " ++ unpackFS (installedUnitIdFS new_pkg)))
1258
1259
1260 linkPackage :: HscEnv -> PackageConfig -> IO ()
1261 linkPackage hsc_env pkg
1262 = do
1263 let dflags = hsc_dflags hsc_env
1264 platform = targetPlatform dflags
1265 dirs | interpreterDynamic dflags = Packages.libraryDynDirs pkg
1266 | otherwise = Packages.libraryDirs pkg
1267
1268 let hs_libs = Packages.hsLibraries pkg
1269 -- The FFI GHCi import lib isn't needed as
1270 -- compiler/ghci/Linker.hs + rts/Linker.c link the
1271 -- interpreted references to FFI to the compiled FFI.
1272 -- We therefore filter it out so that we don't get
1273 -- duplicate symbol errors.
1274 hs_libs' = filter ("HSffi" /=) hs_libs
1275
1276 -- Because of slight differences between the GHC dynamic linker and
1277 -- the native system linker some packages have to link with a
1278 -- different list of libraries when using GHCi. Examples include: libs
1279 -- that are actually gnu ld scripts, and the possibility that the .a
1280 -- libs do not exactly match the .so/.dll equivalents. So if the
1281 -- package file provides an "extra-ghci-libraries" field then we use
1282 -- that instead of the "extra-libraries" field.
1283 extra_libs =
1284 (if null (Packages.extraGHCiLibraries pkg)
1285 then Packages.extraLibraries pkg
1286 else Packages.extraGHCiLibraries pkg)
1287 ++ [ lib | '-':'l':lib <- Packages.ldOptions pkg ]
1288 -- See Note [Fork/Exec Windows]
1289 gcc_paths <- getGCCPaths dflags (platformOS platform)
1290 dirs_env <- addEnvPaths "LIBRARY_PATH" dirs
1291
1292 hs_classifieds
1293 <- mapM (locateLib hsc_env True dirs_env gcc_paths) hs_libs'
1294 extra_classifieds
1295 <- mapM (locateLib hsc_env False dirs_env gcc_paths) extra_libs
1296 let classifieds = hs_classifieds ++ extra_classifieds
1297
1298 -- Complication: all the .so's must be loaded before any of the .o's.
1299 let known_dlls = [ dll | DLLPath dll <- classifieds ]
1300 dlls = [ dll | DLL dll <- classifieds ]
1301 objs = [ obj | Object obj <- classifieds ]
1302 archs = [ arch | Archive arch <- classifieds ]
1303
1304 -- Add directories to library search paths
1305 let dll_paths = map takeDirectory known_dlls
1306 all_paths = nub $ map normalise $ dll_paths ++ dirs
1307 all_paths_env <- addEnvPaths "LD_LIBRARY_PATH" all_paths
1308 pathCache <- mapM (addLibrarySearchPath hsc_env) all_paths_env
1309
1310 maybePutStr dflags
1311 ("Loading package " ++ sourcePackageIdString pkg ++ " ... ")
1312
1313 -- See comments with partOfGHCi
1314 when (packageName pkg `notElem` partOfGHCi) $ do
1315 loadFrameworks hsc_env platform pkg
1316 mapM_ (load_dyn hsc_env)
1317 (known_dlls ++ map (mkSOName platform) dlls)
1318
1319 -- After loading all the DLLs, we can load the static objects.
1320 -- Ordering isn't important here, because we do one final link
1321 -- step to resolve everything.
1322 mapM_ (loadObj hsc_env) objs
1323 mapM_ (loadArchive hsc_env) archs
1324
1325 maybePutStr dflags "linking ... "
1326 ok <- resolveObjs hsc_env
1327
1328 -- DLLs are loaded, reset the search paths
1329 -- Import libraries will be loaded via loadArchive so only
1330 -- reset the DLL search path after all archives are loaded
1331 -- as well.
1332 mapM_ (removeLibrarySearchPath hsc_env) $ reverse pathCache
1333
1334 if succeeded ok
1335 then maybePutStrLn dflags "done."
1336 else let errmsg = "unable to load package `"
1337 ++ sourcePackageIdString pkg ++ "'"
1338 in throwGhcExceptionIO (InstallationError errmsg)
1339
1340 -- we have already searched the filesystem; the strings passed to load_dyn
1341 -- can be passed directly to loadDLL. They are either fully-qualified
1342 -- ("/usr/lib/libfoo.so"), or unqualified ("libfoo.so"). In the latter case,
1343 -- loadDLL is going to search the system paths to find the library.
1344 --
1345 load_dyn :: HscEnv -> FilePath -> IO ()
1346 load_dyn hsc_env dll = do
1347 r <- loadDLL hsc_env dll
1348 case r of
1349 Nothing -> return ()
1350 Just err -> cmdLineErrorIO ("can't load .so/.DLL for: "
1351 ++ dll ++ " (" ++ err ++ ")")
1352
1353 loadFrameworks :: HscEnv -> Platform -> PackageConfig -> IO ()
1354 loadFrameworks hsc_env platform pkg
1355 = when (platformUsesFrameworks platform) $ mapM_ load frameworks
1356 where
1357 fw_dirs = Packages.frameworkDirs pkg
1358 frameworks = Packages.frameworks pkg
1359
1360 load fw = do r <- loadFramework hsc_env fw_dirs fw
1361 case r of
1362 Nothing -> return ()
1363 Just err -> cmdLineErrorIO ("can't load framework: "
1364 ++ fw ++ " (" ++ err ++ ")" )
1365
1366 -- Try to find an object file for a given library in the given paths.
1367 -- If it isn't present, we assume that addDLL in the RTS can find it,
1368 -- which generally means that it should be a dynamic library in the
1369 -- standard system search path.
1370 -- For GHCi we tend to prefer dynamic libraries over static ones as
1371 -- they are easier to load and manage, have less overhead.
1372 locateLib :: HscEnv -> Bool -> [FilePath] -> [FilePath] -> String
1373 -> IO LibrarySpec
1374 locateLib hsc_env is_hs lib_dirs gcc_dirs lib
1375 | not is_hs
1376 -- For non-Haskell libraries (e.g. gmp, iconv):
1377 -- first look in library-dirs for a dynamic library (on User paths only)
1378 -- (libfoo.so)
1379 -- then try looking for import libraries on Windows (on User paths only)
1380 -- (.dll.a, .lib)
1381 -- first look in library-dirs for a dynamic library (on GCC paths only)
1382 -- (libfoo.so)
1383 -- then check for system dynamic libraries (e.g. kernel32.dll on windows)
1384 -- then try looking for import libraries on Windows (on GCC paths only)
1385 -- (.dll.a, .lib)
1386 -- then look in library-dirs for a static library (libfoo.a)
1387 -- then look in library-dirs and inplace GCC for a dynamic library (libfoo.so)
1388 -- then try looking for import libraries on Windows (.dll.a, .lib)
1389 -- then look in library-dirs and inplace GCC for a static library (libfoo.a)
1390 -- then try "gcc --print-file-name" to search gcc's search path
1391 -- for a dynamic library (#5289)
1392 -- otherwise, assume loadDLL can find it
1393 --
1394 -- The logic is a bit complicated, but the rationale behind it is that
1395 -- loading a shared library for us is O(1) while loading an archive is
1396 -- O(n). Loading an import library is also O(n) so in general we prefer
1397 -- shared libraries because they are simpler and faster.
1398 --
1399 = findDll user `orElse`
1400 tryImpLib user `orElse`
1401 findDll gcc `orElse`
1402 findSysDll `orElse`
1403 tryImpLib gcc `orElse`
1404 findArchive `orElse`
1405 tryGcc `orElse`
1406 assumeDll
1407
1408 | loading_dynamic_hs_libs -- search for .so libraries first.
1409 = findHSDll `orElse`
1410 findDynObject `orElse`
1411 assumeDll
1412
1413 | loading_profiled_hs_libs -- only a libHSfoo_p.a archive will do.
1414 = findArchive `orElse`
1415 assumeDll
1416
1417 | otherwise
1418 -- HSfoo.o is the best, but only works for the normal way
1419 -- libHSfoo.a is the backup option.
1420 = findObject `orElse`
1421 findArchive `orElse`
1422 assumeDll
1423
1424 where
1425 dflags = hsc_dflags hsc_env
1426 dirs = lib_dirs ++ gcc_dirs
1427 gcc = False
1428 user = True
1429
1430 obj_file = lib <.> "o"
1431 dyn_obj_file = lib <.> "dyn_o"
1432 arch_files = [ "lib" ++ lib ++ lib_tag <.> "a"
1433 , lib <.> "a" -- native code has no lib_tag
1434 , "lib" ++ lib, lib
1435 ]
1436 lib_tag = if is_hs && loading_profiled_hs_libs then "_p" else ""
1437
1438 loading_profiled_hs_libs = interpreterProfiled dflags
1439 loading_dynamic_hs_libs = interpreterDynamic dflags
1440
1441 import_libs = [ lib <.> "lib" , "lib" ++ lib <.> "lib"
1442 , "lib" ++ lib <.> "dll.a", lib <.> "dll.a"
1443 ]
1444
1445 hs_dyn_lib_name = lib ++ '-':programName dflags ++ projectVersion dflags
1446 hs_dyn_lib_file = mkHsSOName platform hs_dyn_lib_name
1447
1448 so_name = mkSOName platform lib
1449 lib_so_name = "lib" ++ so_name
1450 dyn_lib_file = case (arch, os) of
1451 (ArchX86_64, OSSolaris2) -> "64" </> so_name
1452 _ -> so_name
1453
1454 findObject = liftM (fmap Object) $ findFile dirs obj_file
1455 findDynObject = liftM (fmap Object) $ findFile dirs dyn_obj_file
1456 findArchive = let local name = liftM (fmap Archive) $ findFile dirs name
1457 in apply (map local arch_files)
1458 findHSDll = liftM (fmap DLLPath) $ findFile dirs hs_dyn_lib_file
1459 findDll re = let dirs' = if re == user then lib_dirs else gcc_dirs
1460 in liftM (fmap DLLPath) $ findFile dirs' dyn_lib_file
1461 findSysDll = fmap (fmap $ DLL . dropExtension . takeFileName) $
1462 findSystemLibrary hsc_env so_name
1463 tryGcc = let search = searchForLibUsingGcc dflags
1464 dllpath = liftM (fmap DLLPath)
1465 short = dllpath $ search so_name lib_dirs
1466 full = dllpath $ search lib_so_name lib_dirs
1467 gcc name = liftM (fmap Archive) $ search name lib_dirs
1468 files = import_libs ++ arch_files
1469 in apply $ short : full : map gcc files
1470 tryImpLib re = case os of
1471 OSMinGW32 ->
1472 let dirs' = if re == user then lib_dirs else gcc_dirs
1473 implib name = liftM (fmap Archive) $
1474 findFile dirs' name
1475 in apply (map implib import_libs)
1476 _ -> return Nothing
1477
1478 assumeDll = return (DLL lib)
1479 infixr `orElse`
1480 f `orElse` g = f >>= maybe g return
1481
1482 apply [] = return Nothing
1483 apply (x:xs) = do x' <- x
1484 if isJust x'
1485 then return x'
1486 else apply xs
1487
1488 platform = targetPlatform dflags
1489 arch = platformArch platform
1490 os = platformOS platform
1491
1492 searchForLibUsingGcc :: DynFlags -> String -> [FilePath] -> IO (Maybe FilePath)
1493 searchForLibUsingGcc dflags so dirs = do
1494 -- GCC does not seem to extend the library search path (using -L) when using
1495 -- --print-file-name. So instead pass it a new base location.
1496 str <- askLd dflags (map (FileOption "-B") dirs
1497 ++ [Option "--print-file-name", Option so])
1498 let file = case lines str of
1499 [] -> ""
1500 l:_ -> l
1501 if (file == so)
1502 then return Nothing
1503 else return (Just file)
1504
1505 -- | Retrieve the list of search directory GCC and the System use to find
1506 -- libraries and components. See Note [Fork/Exec Windows].
1507 getGCCPaths :: DynFlags -> OS -> IO [FilePath]
1508 getGCCPaths dflags os
1509 = case os of
1510 OSMinGW32 ->
1511 do gcc_dirs <- getGccSearchDirectory dflags "libraries"
1512 sys_dirs <- getSystemDirectories
1513 return $ nub $ gcc_dirs ++ sys_dirs
1514 _ -> return []
1515
1516 -- | Cache for the GCC search directories as this can't easily change
1517 -- during an invocation of GHC. (Maybe with some env. variable but we'll)
1518 -- deal with that highly unlikely scenario then.
1519 {-# NOINLINE gccSearchDirCache #-}
1520 gccSearchDirCache :: IORef [(String, [String])]
1521 gccSearchDirCache = unsafePerformIO $ newIORef []
1522
1523 -- Note [Fork/Exec Windows]
1524 -- ~~~~~~~~~~~~~~~~~~~~~~~~
1525 -- fork/exec is expensive on Windows, for each time we ask GCC for a library we
1526 -- have to eat the cost of af least 3 of these: gcc -> real_gcc -> cc1.
1527 -- So instead get a list of location that GCC would search and use findDirs
1528 -- which hopefully is written in an optimized mannor to take advantage of
1529 -- caching. At the very least we remove the overhead of the fork/exec and waits
1530 -- which dominate a large percentage of startup time on Windows.
1531 getGccSearchDirectory :: DynFlags -> String -> IO [FilePath]
1532 getGccSearchDirectory dflags key = do
1533 cache <- readIORef gccSearchDirCache
1534 case lookup key cache of
1535 Just x -> return x
1536 Nothing -> do
1537 str <- askLd dflags [Option "--print-search-dirs"]
1538 let line = dropWhile isSpace str
1539 name = key ++ ": ="
1540 if null line
1541 then return []
1542 else do let val = split $ find name line
1543 dirs <- filterM doesDirectoryExist val
1544 modifyIORef' gccSearchDirCache ((key, dirs):)
1545 return val
1546 where split :: FilePath -> [FilePath]
1547 split r = case break (==';') r of
1548 (s, [] ) -> [s]
1549 (s, (_:xs)) -> s : split xs
1550
1551 find :: String -> String -> String
1552 find r x = let lst = lines x
1553 val = filter (r `isPrefixOf`) lst
1554 in if null val
1555 then []
1556 else case break (=='=') (head val) of
1557 (_ , []) -> []
1558 (_, (_:xs)) -> xs
1559
1560 -- | Get a list of system search directories, this to alleviate pressure on
1561 -- the findSysDll function.
1562 getSystemDirectories :: IO [FilePath]
1563 #if defined(mingw32_HOST_OS)
1564 getSystemDirectories = fmap (:[]) getSystemDirectory
1565 #else
1566 getSystemDirectories = return []
1567 #endif
1568
1569 -- | Merge the given list of paths with those in the environment variable
1570 -- given. If the variable does not exist then just return the identity.
1571 addEnvPaths :: String -> [String] -> IO [String]
1572 addEnvPaths name list
1573 = do -- According to POSIX (chapter 8.3) a zero-length prefix means current
1574 -- working directory. Replace empty strings in the env variable with
1575 -- `working_dir` (see also #14695).
1576 working_dir <- getCurrentDirectory
1577 values <- lookupEnv name
1578 case values of
1579 Nothing -> return list
1580 Just arr -> return $ list ++ splitEnv working_dir arr
1581 where
1582 splitEnv :: FilePath -> String -> [String]
1583 splitEnv working_dir value =
1584 case break (== envListSep) value of
1585 (x, [] ) ->
1586 [if null x then working_dir else x]
1587 (x, (_:xs)) ->
1588 (if null x then working_dir else x) : splitEnv working_dir xs
1589 #if defined(mingw32_HOST_OS)
1590 envListSep = ';'
1591 #else
1592 envListSep = ':'
1593 #endif
1594
1595 -- ----------------------------------------------------------------------------
1596 -- Loading a dynamic library (dlopen()-ish on Unix, LoadLibrary-ish on Win32)
1597
1598 -- Darwin / MacOS X only: load a framework
1599 -- a framework is a dynamic library packaged inside a directory of the same
1600 -- name. They are searched for in different paths than normal libraries.
1601 loadFramework :: HscEnv -> [FilePath] -> FilePath -> IO (Maybe String)
1602 loadFramework hsc_env extraPaths rootname
1603 = do { either_dir <- tryIO getHomeDirectory
1604 ; let homeFrameworkPath = case either_dir of
1605 Left _ -> []
1606 Right dir -> [dir </> "Library/Frameworks"]
1607 ps = extraPaths ++ homeFrameworkPath ++ defaultFrameworkPaths
1608 ; mb_fwk <- findFile ps fwk_file
1609 ; case mb_fwk of
1610 Just fwk_path -> loadDLL hsc_env fwk_path
1611 Nothing -> return (Just "not found") }
1612 -- Tried all our known library paths, but dlopen()
1613 -- has no built-in paths for frameworks: give up
1614 where
1615 fwk_file = rootname <.> "framework" </> rootname
1616 -- sorry for the hardcoded paths, I hope they won't change anytime soon:
1617 defaultFrameworkPaths = ["/Library/Frameworks", "/System/Library/Frameworks"]
1618
1619 {- **********************************************************************
1620
1621 Helper functions
1622
1623 ********************************************************************* -}
1624
1625 maybePutStr :: DynFlags -> String -> IO ()
1626 maybePutStr dflags s
1627 = when (verbosity dflags > 1) $
1628 putLogMsg dflags
1629 NoReason
1630 SevInteractive
1631 noSrcSpan
1632 (defaultUserStyle dflags)
1633 (text s)
1634
1635 maybePutStrLn :: DynFlags -> String -> IO ()
1636 maybePutStrLn dflags s = maybePutStr dflags (s ++ "\n")