2 % (c) The University of Glasgow 2005
5 -- --------------------------------------
6 -- The dynamic linker for GHCi
7 -- --------------------------------------
9 This module deals with the top-level issues of dynamic linking,
10 calling the object-code linker and the byte-code linker where
16 {-# OPTIONS -optc-DNON_POSIX_SOURCE -#include "Linker.h" #-}
18 module Linker ( HValue, showLinkerState,
19 linkExpr, unload, extendLinkEnv, withExtendedLinkEnv,
21 linkPackages,initDynLinker
24 #include "HsVersions.h"
26 import ObjLink ( loadDLL, loadObj, unloadObj, resolveObjs, initObjLinker )
27 import ByteCodeLink ( HValue, ClosureEnv, extendClosureEnv, linkBCO )
28 import ByteCodeItbls ( ItblEnv )
29 import ByteCodeAsm ( CompiledByteCode(..), bcoFreeNames, UnlinkedBCO(..))
32 import DriverPhases ( isObjectFilename, isDynLibFilename )
33 import Finder ( findHomeModule, findObjectLinkableMaybe,
36 import Name ( Name, nameModule, isExternalName, isWiredInName )
38 import NameSet ( nameSetToList )
39 import UniqFM ( lookupUFM )
41 import ListSetOps ( minusList )
42 import DynFlags ( DynFlags(..), getOpts )
43 import BasicTypes ( SuccessFlag(..), succeeded, failed )
45 import PackageConfig ( rtsPackageId )
46 import Panic ( GhcException(..) )
47 import Util ( zipLazy, global, joinFileExt, joinFileName, suffixOf,
48 replaceFilenameSuffix )
49 import StaticFlags ( v_Ld_inputs, v_Build_tag )
50 import ErrUtils ( debugTraceMsg, mkLocMessage )
51 import DriverPhases ( phaseInputExt, Phase(..) )
52 import SrcLoc ( SrcSpan )
55 import Control.Monad ( when, filterM, foldM )
57 import Data.IORef ( IORef, readIORef, writeIORef, modifyIORef )
58 import Data.List ( partition, nub )
60 import System.IO ( putStr, putStrLn, hPutStrLn, stderr, fixIO )
61 import System.Directory ( doesFileExist )
63 import Control.Exception ( block, throwDyn, bracket )
64 import Maybe ( fromJust )
66 import Maybe ( isJust )
69 #if __GLASGOW_HASKELL__ >= 503
70 import GHC.IOBase ( IO(..) )
72 import PrelIOBase ( IO(..) )
77 %************************************************************************
81 %************************************************************************
83 The persistent linker state *must* match the actual state of the
84 C dynamic linker at all times, so we keep it in a private global variable.
87 The PersistentLinkerState maps Names to actual closures (for
88 interpreted code only), for use during linking.
91 GLOBAL_VAR(v_PersistentLinkerState, panic "Dynamic linker not initialised", PersistentLinkerState)
92 GLOBAL_VAR(v_InitLinkerDone, False, Bool) -- Set True when dynamic linker is initialised
94 data PersistentLinkerState
95 = PersistentLinkerState {
97 -- Current global mapping from Names to their true values
98 closure_env :: ClosureEnv,
100 -- The current global mapping from RdrNames of DataCons to
101 -- info table addresses.
102 -- When a new Unlinked is linked into the running image, or an existing
103 -- module in the image is replaced, the itbl_env must be updated
107 -- The currently loaded interpreted modules (home package)
108 bcos_loaded :: [Linkable],
110 -- And the currently-loaded compiled modules (home package)
111 objs_loaded :: [Linkable],
113 -- The currently-loaded packages; always object code
114 -- Held, as usual, in dependency order; though I am not sure if
115 -- that is really important
116 pkgs_loaded :: [PackageId]
119 emptyPLS :: DynFlags -> PersistentLinkerState
120 emptyPLS dflags = PersistentLinkerState {
121 closure_env = emptyNameEnv,
122 itbl_env = emptyNameEnv,
123 pkgs_loaded = init_pkgs,
126 -- Packages that don't need loading, because the compiler
127 -- shares them with the interpreted program.
129 -- The linker's symbol table is populated with RTS symbols using an
130 -- explicit list. See rts/Linker.c for details.
131 where init_pkgs = [rtsPackageId]
135 extendLoadedPkgs :: [PackageId] -> IO ()
136 extendLoadedPkgs pkgs
137 = modifyIORef v_PersistentLinkerState (\s -> s{pkgs_loaded = pkgs ++ pkgs_loaded s})
139 extendLinkEnv :: [(Name,HValue)] -> IO ()
140 -- Automatically discards shadowed bindings
141 extendLinkEnv new_bindings
142 = do pls <- readIORef v_PersistentLinkerState
143 let new_closure_env = extendClosureEnv (closure_env pls) new_bindings
144 new_pls = pls { closure_env = new_closure_env }
145 writeIORef v_PersistentLinkerState new_pls
147 withExtendedLinkEnv :: [(Name,HValue)] -> IO a -> IO a
148 withExtendedLinkEnv new_env action
149 = bracket set_new_env
152 where set_new_env = do pls <- readIORef v_PersistentLinkerState
153 let new_closure_env = extendClosureEnv (closure_env pls) new_env
154 new_pls = pls { closure_env = new_closure_env }
155 writeIORef v_PersistentLinkerState new_pls
156 return (closure_env pls)
157 reset_old_env env = modifyIORef v_PersistentLinkerState (\pls -> pls{ closure_env = env })
159 -- filterNameMap removes from the environment all entries except
160 -- those for a given set of modules;
161 -- Note that this removes all *local* (i.e. non-isExternal) names too
162 -- (these are the temporary bindings from the command line).
163 -- Used to filter both the ClosureEnv and ItblEnv
165 filterNameMap :: [Module] -> NameEnv (Name, a) -> NameEnv (Name, a)
166 filterNameMap mods env
167 = filterNameEnv keep_elt env
169 keep_elt (n,_) = isExternalName n
170 && (nameModule n `elem` mods)
175 showLinkerState :: IO ()
176 -- Display the persistent linker state
178 = do pls <- readIORef v_PersistentLinkerState
179 printDump (vcat [text "----- Linker state -----",
180 text "Pkgs:" <+> ppr (pkgs_loaded pls),
181 text "Objs:" <+> ppr (objs_loaded pls),
182 text "BCOs:" <+> ppr (bcos_loaded pls)])
188 %************************************************************************
190 \subsection{Initialisation}
192 %************************************************************************
194 We initialise the dynamic linker by
196 a) calling the C initialisation procedure
198 b) Loading any packages specified on the command line,
199 now held in v_ExplicitPackages
201 c) Loading any packages specified on the command line,
202 now held in the -l options in v_Opt_l
204 d) Loading any .o/.dll files specified on the command line,
205 now held in v_Ld_inputs
207 e) Loading any MacOS frameworks
210 initDynLinker :: DynFlags -> IO ()
211 -- This function is idempotent; if called more than once, it does nothing
212 -- This is useful in Template Haskell, where we call it before trying to link
214 = do { done <- readIORef v_InitLinkerDone
215 ; if done then return ()
216 else do { writeIORef v_InitLinkerDone True
217 ; reallyInitDynLinker dflags }
220 reallyInitDynLinker dflags
221 = do { -- Initialise the linker state
222 ; writeIORef v_PersistentLinkerState (emptyPLS dflags)
224 -- (a) initialise the C dynamic linker
227 -- (b) Load packages from the command-line
228 ; linkPackages dflags (explicitPackages (pkgState dflags))
230 -- (c) Link libraries from the command-line
231 ; let optl = getOpts dflags opt_l
232 ; let minus_ls = [ lib | '-':'l':lib <- optl ]
234 -- (d) Link .o files from the command-line
235 ; let lib_paths = libraryPaths dflags
236 ; cmdline_ld_inputs <- readIORef v_Ld_inputs
238 ; classified_ld_inputs <- mapM classifyLdInput cmdline_ld_inputs
240 -- (e) Link any MacOS frameworks
241 #ifdef darwin_TARGET_OS
242 ; let framework_paths = frameworkPaths dflags
243 ; let frameworks = cmdlineFrameworks dflags
245 ; let frameworks = []
246 ; let framework_paths = []
248 -- Finally do (c),(d),(e)
249 ; let cmdline_lib_specs = [ l | Just l <- classified_ld_inputs ]
251 ++ map Framework frameworks
252 ; if null cmdline_lib_specs then return ()
255 { mapM_ (preloadLib dflags lib_paths framework_paths) cmdline_lib_specs
256 ; maybePutStr dflags "final link ... "
259 ; if succeeded ok then maybePutStrLn dflags "done"
260 else throwDyn (InstallationError "linking extra libraries/objects failed")
263 classifyLdInput :: FilePath -> IO (Maybe LibrarySpec)
265 | isObjectFilename f = return (Just (Object f))
266 | isDynLibFilename f = return (Just (DLLPath f))
268 hPutStrLn stderr ("Warning: ignoring unrecognised input `" ++ f ++ "'")
271 preloadLib :: DynFlags -> [String] -> [String] -> LibrarySpec -> IO ()
272 preloadLib dflags lib_paths framework_paths lib_spec
273 = do maybePutStr dflags ("Loading object " ++ showLS lib_spec ++ " ... ")
276 -> do b <- preload_static lib_paths static_ish
277 maybePutStrLn dflags (if b then "done"
281 -> do maybe_errstr <- loadDynamic lib_paths dll_unadorned
283 Nothing -> maybePutStrLn dflags "done"
284 Just mm -> preloadFailed mm lib_paths lib_spec
287 -> do maybe_errstr <- loadDLL dll_path
289 Nothing -> maybePutStrLn dflags "done"
290 Just mm -> preloadFailed mm lib_paths lib_spec
292 #ifdef darwin_TARGET_OS
294 -> do maybe_errstr <- loadFramework framework_paths framework
296 Nothing -> maybePutStrLn dflags "done"
297 Just mm -> preloadFailed mm framework_paths lib_spec
300 preloadFailed :: String -> [String] -> LibrarySpec -> IO ()
301 preloadFailed sys_errmsg paths spec
302 = do maybePutStr dflags
303 ("failed.\nDynamic linker error message was:\n "
304 ++ sys_errmsg ++ "\nWhilst trying to load: "
305 ++ showLS spec ++ "\nDirectories to search are:\n"
306 ++ unlines (map (" "++) paths) )
309 -- Not interested in the paths in the static case.
310 preload_static paths name
311 = do b <- doesFileExist name
312 if not b then return False
313 else loadObj name >> return True
316 CmdLineError "user specified .o/.so/.DLL could not be loaded."
320 %************************************************************************
322 Link a byte-code expression
324 %************************************************************************
327 linkExpr :: HscEnv -> SrcSpan -> UnlinkedBCO -> IO HValue
329 -- Link a single expression, *including* first linking packages and
330 -- modules that this expression depends on.
332 -- Raises an IO exception if it can't find a compiled version of the
333 -- dependents to link.
335 linkExpr hsc_env span root_ul_bco
337 -- Initialise the linker (if it's not been done already)
338 let dflags = hsc_dflags hsc_env
339 ; initDynLinker dflags
341 -- The interpreter and dynamic linker can only handle object code built
342 -- the "normal" way, i.e. no non-std ways like profiling or ticky-ticky.
343 -- So here we check the build tag: if we're building a non-standard way
344 -- then we need to find & link object files built the "normal" way.
345 ; maybe_normal_osuf <- checkNonStdWay dflags span
347 -- Find what packages and linkables are required
348 ; eps <- readIORef (hsc_EPS hsc_env)
349 ; (lnks, pkgs) <- getLinkDeps hsc_env hpt (eps_PIT eps)
350 maybe_normal_osuf span needed_mods
352 -- Link the packages and modules required
353 ; linkPackages dflags pkgs
354 ; ok <- linkModules dflags lnks
356 throwDyn (ProgramError "")
359 -- Link the expression itself
360 pls <- readIORef v_PersistentLinkerState
361 ; let ie = itbl_env pls
364 -- Link the necessary packages and linkables
365 ; (_, (root_hval:_)) <- linkSomeBCOs False ie ce [root_ul_bco]
369 hpt = hsc_HPT hsc_env
370 free_names = nameSetToList (bcoFreeNames root_ul_bco)
372 needed_mods :: [Module]
373 needed_mods = [ nameModule n | n <- free_names,
374 isExternalName n, -- Names from other modules
375 not (isWiredInName n) -- Exclude wired-in names
376 ] -- (see note below)
377 -- Exclude wired-in names because we may not have read
378 -- their interface files, so getLinkDeps will fail
379 -- All wired-in names are in the base package, which we link
380 -- by default, so we can safely ignore them here.
382 dieWith span msg = throwDyn (ProgramError (showSDoc (mkLocMessage span msg)))
385 checkNonStdWay :: DynFlags -> SrcSpan -> IO (Maybe String)
386 checkNonStdWay dflags srcspan = do
387 tag <- readIORef v_Build_tag
388 if null tag then return Nothing else do
389 let default_osuf = phaseInputExt StopLn
390 if objectSuf dflags == default_osuf
391 then failNonStd srcspan
392 else return (Just default_osuf)
394 failNonStd srcspan = dieWith srcspan $
395 ptext SLIT("Dynamic linking required, but this is a non-standard build (eg. prof).") $$
396 ptext SLIT("You need to build the program twice: once the normal way, and then") $$
397 ptext SLIT("in the desired way using -osuf to set the object file suffix.")
400 getLinkDeps :: HscEnv -> HomePackageTable -> PackageIfaceTable
401 -> Maybe String -- the "normal" object suffix
402 -> SrcSpan -- for error messages
403 -> [Module] -- If you need these
404 -> IO ([Linkable], [PackageId]) -- ... then link these first
405 -- Fails with an IO exception if it can't find enough files
407 getLinkDeps hsc_env hpt pit maybe_normal_osuf span mods
408 -- Find all the packages and linkables that a set of modules depends on
409 = do { pls <- readIORef v_PersistentLinkerState ;
411 -- 1. Find the dependent home-pkg-modules/packages from each iface
412 (mods_s, pkgs_s) = unzip (map get_deps mods) ;
414 -- 2. Exclude ones already linked
415 -- Main reason: avoid findModule calls in get_linkable
416 mods_needed = nub (concat mods_s) `minusList` linked_mods ;
417 pkgs_needed = nub (concat pkgs_s) `minusList` pkgs_loaded pls ;
419 linked_mods = map (moduleName.linkableModule)
420 (objs_loaded pls ++ bcos_loaded pls)
423 -- 3. For each dependent module, find its linkable
424 -- This will either be in the HPT or (in the case of one-shot
425 -- compilation) we may need to use maybe_getFileLinkable
426 lnks_needed <- mapM (get_linkable maybe_normal_osuf) mods_needed ;
428 return (lnks_needed, pkgs_needed) }
430 dflags = hsc_dflags hsc_env
431 this_pkg = thisPackage dflags
433 get_deps :: Module -> ([ModuleName],[PackageId])
434 -- Get the things needed for the specified module
435 -- This is rather similar to the code in RnNames.importsFromImportDecl
438 = ([], pkg : dep_pkgs deps)
440 = (moduleName mod : [m | (m,_) <- dep_mods deps], dep_pkgs deps)
442 pkg = modulePackageId mod
443 deps = mi_deps (get_iface mod)
445 get_iface mod = case lookupIfaceByModule dflags hpt pit mod of
447 Nothing -> pprPanic "getLinkDeps" (no_iface mod)
448 no_iface mod = ptext SLIT("No iface for") <+> ppr mod
449 -- This one is a GHC bug
451 no_obj mod = dieWith span $
452 ptext SLIT("cannot find object file for module ") <>
456 while_linking_expr = ptext SLIT("while linking an interpreted expression")
458 -- This one is a build-system bug
460 get_linkable maybe_normal_osuf mod_name -- A home-package module
461 | Just mod_info <- lookupUFM hpt mod_name
462 = ASSERT(isJust (hm_linkable mod_info))
463 adjust_linkable (fromJust (hm_linkable mod_info))
465 = do -- It's not in the HPT because we are in one shot mode,
466 -- so use the Finder to get a ModLocation...
467 mb_stuff <- findHomeModule hsc_env mod_name
469 Found loc mod -> found loc mod
473 -- ...and then find the linkable for it
474 mb_lnk <- findObjectLinkableMaybe mod loc ;
476 Nothing -> no_obj mod ;
477 Just lnk -> adjust_linkable lnk
481 | Just osuf <- maybe_normal_osuf = do
482 new_uls <- mapM (adjust_ul osuf) (linkableUnlinked lnk)
483 return lnk{ linkableUnlinked=new_uls }
487 adjust_ul osuf (DotO file) = do
488 let new_file = replaceFilenameSuffix file osuf
489 ok <- doesFileExist new_file
492 ptext SLIT("cannot find normal object file ")
493 <> quotes (text new_file) $$ while_linking_expr
494 else return (DotO new_file)
498 %************************************************************************
501 The linkables may consist of a mixture of
502 byte-code modules and object modules
504 %************************************************************************
507 linkModules :: DynFlags -> [Linkable] -> IO SuccessFlag
508 linkModules dflags linkables
509 = block $ do -- don't want to be interrupted by ^C in here
511 let (objs, bcos) = partition isObjectLinkable
512 (concatMap partitionLinkable linkables)
514 -- Load objects first; they can't depend on BCOs
515 ok_flag <- dynLinkObjs dflags objs
517 if failed ok_flag then
524 -- HACK to support f-x-dynamic in the interpreter; no other purpose
525 partitionLinkable :: Linkable -> [Linkable]
527 = let li_uls = linkableUnlinked li
528 li_uls_obj = filter isObject li_uls
529 li_uls_bco = filter isInterpretable li_uls
531 case (li_uls_obj, li_uls_bco) of
532 (objs@(_:_), bcos@(_:_))
533 -> [li{linkableUnlinked=li_uls_obj}, li{linkableUnlinked=li_uls_bco}]
537 findModuleLinkable_maybe :: [Linkable] -> Module -> Maybe Linkable
538 findModuleLinkable_maybe lis mod
539 = case [LM time nm us | LM time nm us <- lis, nm == mod] of
542 many -> pprPanic "findModuleLinkable" (ppr mod)
544 linkableInSet :: Linkable -> [Linkable] -> Bool
545 linkableInSet l objs_loaded =
546 case findModuleLinkable_maybe objs_loaded (linkableModule l) of
548 Just m -> linkableTime l == linkableTime m
552 %************************************************************************
554 \subsection{The object-code linker}
556 %************************************************************************
559 dynLinkObjs :: DynFlags -> [Linkable] -> IO SuccessFlag
560 -- Side-effects the PersistentLinkerState
562 dynLinkObjs dflags objs
563 = do pls <- readIORef v_PersistentLinkerState
565 -- Load the object files and link them
566 let (objs_loaded', new_objs) = rmDupLinkables (objs_loaded pls) objs
567 pls1 = pls { objs_loaded = objs_loaded' }
568 unlinkeds = concatMap linkableUnlinked new_objs
570 mapM loadObj (map nameOfObject unlinkeds)
572 -- Link the all together
575 -- If resolving failed, unload all our
576 -- object modules and carry on
577 if succeeded ok then do
578 writeIORef v_PersistentLinkerState pls1
581 pls2 <- unload_wkr dflags [] pls1
582 writeIORef v_PersistentLinkerState pls2
586 rmDupLinkables :: [Linkable] -- Already loaded
587 -> [Linkable] -- New linkables
588 -> ([Linkable], -- New loaded set (including new ones)
589 [Linkable]) -- New linkables (excluding dups)
590 rmDupLinkables already ls
593 go already extras [] = (already, extras)
594 go already extras (l:ls)
595 | linkableInSet l already = go already extras ls
596 | otherwise = go (l:already) (l:extras) ls
599 %************************************************************************
601 \subsection{The byte-code linker}
603 %************************************************************************
606 dynLinkBCOs :: [Linkable] -> IO ()
607 -- Side-effects the persistent linker state
609 = do pls <- readIORef v_PersistentLinkerState
611 let (bcos_loaded', new_bcos) = rmDupLinkables (bcos_loaded pls) bcos
612 pls1 = pls { bcos_loaded = bcos_loaded' }
613 unlinkeds :: [Unlinked]
614 unlinkeds = concatMap linkableUnlinked new_bcos
616 cbcs :: [CompiledByteCode]
617 cbcs = map byteCodeOfObject unlinkeds
620 ul_bcos = [b | ByteCode bs _ <- cbcs, b <- bs]
621 ies = [ie | ByteCode _ ie <- cbcs]
622 gce = closure_env pls
623 final_ie = foldr plusNameEnv (itbl_env pls) ies
625 (final_gce, linked_bcos) <- linkSomeBCOs True final_ie gce ul_bcos
626 -- What happens to these linked_bcos?
628 let pls2 = pls1 { closure_env = final_gce,
629 itbl_env = final_ie }
631 writeIORef v_PersistentLinkerState pls2
634 -- Link a bunch of BCOs and return them + updated closure env.
635 linkSomeBCOs :: Bool -- False <=> add _all_ BCOs to returned closure env
636 -- True <=> add only toplevel BCOs to closure env
640 -> IO (ClosureEnv, [HValue])
641 -- The returned HValues are associated 1-1 with
642 -- the incoming unlinked BCOs. Each gives the
643 -- value of the corresponding unlinked BCO
646 linkSomeBCOs toplevs_only ie ce_in ul_bcos
647 = do let nms = map unlinkedBCOName ul_bcos
649 ( \ hvs -> let ce_out = extendClosureEnv ce_in (zipLazy nms hvs)
650 in mapM (linkBCO ie ce_out) ul_bcos )
652 let ce_all_additions = zip nms hvals
653 ce_top_additions = filter (isExternalName.fst) ce_all_additions
654 ce_additions = if toplevs_only then ce_top_additions
655 else ce_all_additions
656 ce_out = -- make sure we're not inserting duplicate names into the
657 -- closure environment, which leads to trouble.
658 ASSERT (all (not . (`elemNameEnv` ce_in)) (map fst ce_additions))
659 extendClosureEnv ce_in ce_additions
660 return (ce_out, hvals)
665 %************************************************************************
667 Unload some object modules
669 %************************************************************************
672 -- ---------------------------------------------------------------------------
673 -- Unloading old objects ready for a new compilation sweep.
675 -- The compilation manager provides us with a list of linkables that it
676 -- considers "stable", i.e. won't be recompiled this time around. For
677 -- each of the modules current linked in memory,
679 -- * if the linkable is stable (and it's the same one - the
680 -- user may have recompiled the module on the side), we keep it,
682 -- * otherwise, we unload it.
684 -- * we also implicitly unload all temporary bindings at this point.
686 unload :: DynFlags -> [Linkable] -> IO ()
687 -- The 'linkables' are the ones to *keep*
689 unload dflags linkables
690 = block $ do -- block, so we're safe from Ctrl-C in here
692 -- Initialise the linker (if it's not been done already)
695 pls <- readIORef v_PersistentLinkerState
696 new_pls <- unload_wkr dflags linkables pls
697 writeIORef v_PersistentLinkerState new_pls
699 debugTraceMsg dflags 3 (text "unload: retaining objs" <+> ppr (objs_loaded new_pls))
700 debugTraceMsg dflags 3 (text "unload: retaining bcos" <+> ppr (bcos_loaded new_pls))
703 unload_wkr :: DynFlags
704 -> [Linkable] -- stable linkables
705 -> PersistentLinkerState
706 -> IO PersistentLinkerState
707 -- Does the core unload business
708 -- (the wrapper blocks exceptions and deals with the PLS get and put)
710 unload_wkr dflags linkables pls
711 = do let (objs_to_keep, bcos_to_keep) = partition isObjectLinkable linkables
713 objs_loaded' <- filterM (maybeUnload objs_to_keep) (objs_loaded pls)
714 bcos_loaded' <- filterM (maybeUnload bcos_to_keep) (bcos_loaded pls)
716 let bcos_retained = map linkableModule bcos_loaded'
717 itbl_env' = filterNameMap bcos_retained (itbl_env pls)
718 closure_env' = filterNameMap bcos_retained (closure_env pls)
719 new_pls = pls { itbl_env = itbl_env',
720 closure_env = closure_env',
721 bcos_loaded = bcos_loaded',
722 objs_loaded = objs_loaded' }
726 maybeUnload :: [Linkable] -> Linkable -> IO Bool
727 maybeUnload keep_linkables lnk
728 | linkableInSet lnk linkables = return True
730 = do mapM_ unloadObj [f | DotO f <- linkableUnlinked lnk]
731 -- The components of a BCO linkable may contain
732 -- dot-o files. Which is very confusing.
734 -- But the BCO parts can be unlinked just by
735 -- letting go of them (plus of course depopulating
736 -- the symbol table which is done in the main body)
741 %************************************************************************
745 %************************************************************************
750 = Object FilePath -- Full path name of a .o file, including trailing .o
751 -- For dynamic objects only, try to find the object
752 -- file in all the directories specified in
753 -- v_Library_paths before giving up.
755 | DLL String -- "Unadorned" name of a .DLL/.so
756 -- e.g. On unix "qt" denotes "libqt.so"
757 -- On WinDoze "burble" denotes "burble.DLL"
758 -- loadDLL is platform-specific and adds the lib/.so/.DLL
759 -- suffixes platform-dependently
761 | DLLPath FilePath -- Absolute or relative pathname to a dynamic library
762 -- (ends with .dll or .so).
764 | Framework String -- Only used for darwin, but does no harm
766 -- If this package is already part of the GHCi binary, we'll already
767 -- have the right DLLs for this package loaded, so don't try to
770 -- But on Win32 we must load them 'again'; doing so is a harmless no-op
771 -- as far as the loader is concerned, but it does initialise the list
772 -- of DLL handles that rts/Linker.c maintains, and that in turn is
773 -- used by lookupSymbol. So we must call addDLL for each library
774 -- just to get the DLL handle into the list.
776 # if defined(mingw32_TARGET_OS) || defined(darwin_TARGET_OS)
779 = [ "base", "haskell98", "template-haskell", "readline" ]
782 showLS (Object nm) = "(static) " ++ nm
783 showLS (DLL nm) = "(dynamic) " ++ nm
784 showLS (DLLPath nm) = "(dynamic) " ++ nm
785 showLS (Framework nm) = "(framework) " ++ nm
787 linkPackages :: DynFlags -> [PackageId] -> IO ()
788 -- Link exactly the specified packages, and their dependents
789 -- (unless of course they are already linked)
790 -- The dependents are linked automatically, and it doesn't matter
791 -- what order you specify the input packages.
793 -- NOTE: in fact, since each module tracks all the packages it depends on,
794 -- we don't really need to use the package-config dependencies.
795 -- However we do need the package-config stuff (to find aux libs etc),
796 -- and following them lets us load libraries in the right order, which
797 -- perhaps makes the error message a bit more localised if we get a link
798 -- failure. So the dependency walking code is still here.
800 linkPackages dflags new_pkgs
801 = do { pls <- readIORef v_PersistentLinkerState
802 ; let pkg_map = pkgIdMap (pkgState dflags)
804 ; pkgs' <- link pkg_map (pkgs_loaded pls) new_pkgs
806 ; writeIORef v_PersistentLinkerState (pls { pkgs_loaded = pkgs' })
809 link :: PackageConfigMap -> [PackageId] -> [PackageId] -> IO [PackageId]
810 link pkg_map pkgs new_pkgs
811 = foldM (link_one pkg_map) pkgs new_pkgs
813 link_one pkg_map pkgs new_pkg
814 | new_pkg `elem` pkgs -- Already linked
817 | Just pkg_cfg <- lookupPackage pkg_map new_pkg
818 = do { -- Link dependents first
819 pkgs' <- link pkg_map pkgs (map mkPackageId (depends pkg_cfg))
820 -- Now link the package itself
821 ; linkPackage dflags pkg_cfg
822 ; return (new_pkg : pkgs') }
825 = throwDyn (CmdLineError ("unknown package: " ++ packageIdString new_pkg))
828 linkPackage :: DynFlags -> PackageConfig -> IO ()
829 linkPackage dflags pkg
831 let dirs = Packages.libraryDirs pkg
833 let libs = Packages.hsLibraries pkg
834 -- Because of slight differences between the GHC dynamic linker and
835 -- the native system linker some packages have to link with a
836 -- different list of libraries when using GHCi. Examples include: libs
837 -- that are actually gnu ld scripts, and the possability that the .a
838 -- libs do not exactly match the .so/.dll equivalents. So if the
839 -- package file provides an "extra-ghci-libraries" field then we use
840 -- that instead of the "extra-libraries" field.
841 ++ (if null (Packages.extraGHCiLibraries pkg)
842 then Packages.extraLibraries pkg
843 else Packages.extraGHCiLibraries pkg)
844 ++ [ lib | '-':'l':lib <- Packages.ldOptions pkg ]
845 classifieds <- mapM (locateOneObj dirs) libs
847 -- Complication: all the .so's must be loaded before any of the .o's.
848 let dlls = [ dll | DLL dll <- classifieds ]
849 objs = [ obj | Object obj <- classifieds ]
851 maybePutStr dflags ("Loading package " ++ showPackageId (package pkg) ++ " ... ")
853 -- See comments with partOfGHCi
854 when (pkgName (package pkg) `notElem` partOfGHCi) $ do
856 -- When a library A needs symbols from a library B, the order in
857 -- extra_libraries/extra_ld_opts is "-lA -lB", because that's the
858 -- way ld expects it for static linking. Dynamic linking is a
859 -- different story: When A has no dependency information for B,
860 -- dlopen-ing A with RTLD_NOW (see addDLL in Linker.c) will fail
861 -- when B has not been loaded before. In a nutshell: Reverse the
862 -- order of DLLs for dynamic linking.
863 -- This fixes a problem with the HOpenGL package (see "Compiling
864 -- HOpenGL under recent versions of GHC" on the HOpenGL list).
865 mapM_ (load_dyn dirs) (reverse dlls)
867 -- After loading all the DLLs, we can load the static objects.
868 -- Ordering isn't important here, because we do one final link
869 -- step to resolve everything.
872 maybePutStr dflags "linking ... "
874 if succeeded ok then maybePutStrLn dflags "done."
875 else throwDyn (InstallationError ("unable to load package `" ++ showPackageId (package pkg) ++ "'"))
877 load_dyn dirs dll = do r <- loadDynamic dirs dll
880 Just err -> throwDyn (CmdLineError ("can't load .so/.DLL for: "
881 ++ dll ++ " (" ++ err ++ ")" ))
882 #ifndef darwin_TARGET_OS
883 loadFrameworks pkg = return ()
885 loadFrameworks pkg = mapM_ load frameworks
887 fw_dirs = Packages.frameworkDirs pkg
888 frameworks = Packages.frameworks pkg
890 load fw = do r <- loadFramework fw_dirs fw
893 Just err -> throwDyn (CmdLineError ("can't load framework: "
894 ++ fw ++ " (" ++ err ++ ")" ))
897 -- Try to find an object file for a given library in the given paths.
898 -- If it isn't present, we assume it's a dynamic library.
899 locateOneObj :: [FilePath] -> String -> IO LibrarySpec
900 locateOneObj dirs lib
901 = do { mb_obj_path <- findFile mk_obj_path dirs
902 ; case mb_obj_path of
903 Just obj_path -> return (Object obj_path)
905 do { mb_lib_path <- findFile mk_dyn_lib_path dirs
906 ; case mb_lib_path of
907 Just lib_path -> return (DLL (lib ++ "_dyn"))
908 Nothing -> return (DLL lib) }} -- We assume
910 mk_obj_path dir = dir `joinFileName` (lib `joinFileExt` "o")
911 mk_dyn_lib_path dir = dir `joinFileName` mkSOName (lib ++ "_dyn")
914 -- ----------------------------------------------------------------------------
915 -- Loading a dyanmic library (dlopen()-ish on Unix, LoadLibrary-ish on Win32)
917 -- return Nothing == success, else Just error message from dlopen
918 loadDynamic paths rootname
919 = do { mb_dll <- findFile mk_dll_path paths
921 Just dll -> loadDLL dll
922 Nothing -> loadDLL (mkSOName rootname) }
923 -- Tried all our known library paths, so let
924 -- dlopen() search its own builtin paths now.
926 mk_dll_path dir = dir `joinFileName` mkSOName rootname
928 #if defined(darwin_TARGET_OS)
929 mkSOName root = ("lib" ++ root) `joinFileExt` "dylib"
930 #elif defined(mingw32_TARGET_OS)
931 -- Win32 DLLs have no .dll extension here, because addDLL tries
932 -- both foo.dll and foo.drv
935 mkSOName root = ("lib" ++ root) `joinFileExt` "so"
938 -- Darwin / MacOS X only: load a framework
939 -- a framework is a dynamic library packaged inside a directory of the same
940 -- name. They are searched for in different paths than normal libraries.
941 #ifdef darwin_TARGET_OS
942 loadFramework extraPaths rootname
943 = do { mb_fwk <- findFile mk_fwk (extraPaths ++ defaultFrameworkPaths)
945 Just fwk_path -> loadDLL fwk_path
946 Nothing -> return (Just "not found") }
947 -- Tried all our known library paths, but dlopen()
948 -- has no built-in paths for frameworks: give up
950 mk_fwk dir = dir `joinFileName` (rootname ++ ".framework/" ++ rootname)
951 -- sorry for the hardcoded paths, I hope they won't change anytime soon:
952 defaultFrameworkPaths = ["/Library/Frameworks", "/System/Library/Frameworks"]
956 %************************************************************************
960 %************************************************************************
963 findFile :: (FilePath -> FilePath) -- Maps a directory path to a file path
964 -> [FilePath] -- Directories to look in
965 -> IO (Maybe FilePath) -- The first file path to match
966 findFile mk_file_path []
968 findFile mk_file_path (dir:dirs)
969 = do { let file_path = mk_file_path dir
970 ; b <- doesFileExist file_path
972 return (Just file_path)
974 findFile mk_file_path dirs }
978 maybePutStr dflags s | verbosity dflags > 0 = putStr s
979 | otherwise = return ()
981 maybePutStrLn dflags s | verbosity dflags > 0 = putStrLn s
982 | otherwise = return ()