2 % (c) The University of Glasgow 2005-2006
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
15 {-# OPTIONS -optc-DNON_POSIX_SOURCE -#include "Linker.h" #-}
17 module Linker ( HValue, getHValue, showLinkerState,
18 linkExpr, unload, extendLinkEnv, withExtendedLinkEnv,
20 linkPackages,initDynLinker,
24 #include "HsVersions.h"
30 import RtClosureInspect
61 import Control.Arrow ( second )
68 import System.Directory
70 import Control.Exception
73 #if __GLASGOW_HASKELL__ >= 503
74 import GHC.IOBase ( IO(..) )
76 import PrelIOBase ( IO(..) )
81 %************************************************************************
85 %************************************************************************
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.
91 The PersistentLinkerState maps Names to actual closures (for
92 interpreted code only), for use during linking.
95 GLOBAL_VAR(v_PersistentLinkerState, panic "Dynamic linker not initialised", PersistentLinkerState)
96 GLOBAL_VAR(v_InitLinkerDone, False, Bool) -- Set True when dynamic linker is initialised
98 data PersistentLinkerState
99 = PersistentLinkerState {
101 -- Current global mapping from Names to their true values
102 closure_env :: ClosureEnv,
104 -- The current global mapping from RdrNames of DataCons to
105 -- info table addresses.
106 -- When a new Unlinked is linked into the running image, or an existing
107 -- module in the image is replaced, the itbl_env must be updated
111 -- The currently loaded interpreted modules (home package)
112 bcos_loaded :: [Linkable],
114 -- And the currently-loaded compiled modules (home package)
115 objs_loaded :: [Linkable],
117 -- The currently-loaded packages; always object code
118 -- Held, as usual, in dependency order; though I am not sure if
119 -- that is really important
120 pkgs_loaded :: [PackageId]
121 ,dtacons_env :: DataConEnv
124 emptyPLS :: DynFlags -> PersistentLinkerState
125 emptyPLS dflags = PersistentLinkerState {
126 closure_env = emptyNameEnv,
127 itbl_env = emptyNameEnv,
128 pkgs_loaded = init_pkgs,
131 , dtacons_env = emptyAddressEnv
133 -- Packages that don't need loading, because the compiler
134 -- shares them with the interpreted program.
136 -- The linker's symbol table is populated with RTS symbols using an
137 -- explicit list. See rts/Linker.c for details.
138 where init_pkgs = [rtsPackageId]
142 extendLoadedPkgs :: [PackageId] -> IO ()
143 extendLoadedPkgs pkgs
144 = modifyIORef v_PersistentLinkerState (\s -> s{pkgs_loaded = pkgs ++ pkgs_loaded s})
146 extendLinkEnv :: [(Name,HValue)] -> IO ()
147 -- Automatically discards shadowed bindings
148 extendLinkEnv new_bindings
149 = do pls <- readIORef v_PersistentLinkerState
150 let new_closure_env = extendClosureEnv (closure_env pls) new_bindings
151 new_pls = pls { closure_env = new_closure_env }
152 writeIORef v_PersistentLinkerState new_pls
155 recoverDataCon :: a -> TcM Name
156 recoverDataCon a = recoverDCInRTS a `recoverM` ioToTcRn (do
157 mb_name <- recoverDCInDynEnv a
158 maybe (fail "Linker.recoverDatacon: Name not found in Dyn Env")
162 -- | If a is a Constr closure, lookupDC returns either the Name of the DataCon or the
163 -- symbol if it is a nullary constructor
164 -- For instance, for a closure containing 'Just x' it would return the Name for Data.Maybe.Just
165 -- For a closure containing 'Nothing' it would return the String "DataziMaybe_Nothing_static_info"
166 recoverDCInDynEnv :: a -> IO (Maybe Name)
167 recoverDCInDynEnv a = do
168 pls <- readIORef v_PersistentLinkerState
169 let de = dtacons_env pls
170 ctype <- getClosureType a
171 if not (isConstr ctype)
172 then putStrLn ("Not a Constr (" ++ show ctype ++ ")") >>
174 else do let infot = getInfoTablePtr a
175 name = lookupAddressEnv de (castPtr$ infot `plusPtr` (wORD_SIZE*2))
179 recoverDCInRTS :: a -> TcM Name
180 recoverDCInRTS a = do
181 ctype <- ioToTcRn$ getClosureType a
182 if (not$ isConstr ctype)
183 then fail "not Constr"
185 Just symbol <- ioToTcRn$ lookupDataCon (getInfoTablePtr a)
186 let (occ,mod) = (parse . lex) symbol
188 where lex x = map zDecodeString . init . init . split '_' . removeLeadingUnderscore $ x
189 parse [pkg, modName, occ] = (mkOccName OccName.dataName occ,
190 mkModule (stringToPackageId pkg) (mkModuleName modName))
191 parse [modName, occ] = (mkOccName OccName.dataName occ,
192 mkModule mainPackageId (mkModuleName modName))
195 helper x = Just . second (drop 1) . break (==delim) $ x
197 removeLeadingUnderscore = if cLeadingUnderscore=="YES"
201 getHValue :: Name -> IO (Maybe HValue)
203 pls <- readIORef v_PersistentLinkerState
204 case lookupNameEnv (closure_env pls) name of
205 Just (_,x) -> return$ Just x
208 withExtendedLinkEnv :: [(Name,HValue)] -> IO a -> IO a
209 withExtendedLinkEnv new_env action
210 = bracket set_new_env
213 where set_new_env = do pls <- readIORef v_PersistentLinkerState
214 let new_closure_env = extendClosureEnv (closure_env pls) new_env
215 new_pls = pls { closure_env = new_closure_env }
216 writeIORef v_PersistentLinkerState new_pls
217 return (closure_env pls)
218 reset_old_env env = modifyIORef v_PersistentLinkerState (\pls -> pls{ closure_env = env })
220 -- filterNameMap removes from the environment all entries except
221 -- those for a given set of modules;
222 -- Note that this removes all *local* (i.e. non-isExternal) names too
223 -- (these are the temporary bindings from the command line).
224 -- Used to filter both the ClosureEnv and ItblEnv
226 filterNameMap :: [Module] -> NameEnv (Name, a) -> NameEnv (Name, a)
227 filterNameMap mods env
228 = filterNameEnv keep_elt env
230 keep_elt (n,_) = isExternalName n
231 && (nameModule n `elem` mods)
236 showLinkerState :: IO ()
237 -- Display the persistent linker state
239 = do pls <- readIORef v_PersistentLinkerState
240 printDump (vcat [text "----- Linker state -----",
241 text "Pkgs:" <+> ppr (pkgs_loaded pls),
242 text "Objs:" <+> ppr (objs_loaded pls),
243 text "BCOs:" <+> ppr (bcos_loaded pls),
244 text "DataCons:" <+> ppr (dtacons_env pls)
251 %************************************************************************
253 \subsection{Initialisation}
255 %************************************************************************
257 We initialise the dynamic linker by
259 a) calling the C initialisation procedure
261 b) Loading any packages specified on the command line,
263 c) Loading any packages specified on the command line,
264 now held in the -l options in v_Opt_l
266 d) Loading any .o/.dll files specified on the command line,
267 now held in v_Ld_inputs
269 e) Loading any MacOS frameworks
272 initDynLinker :: DynFlags -> IO ()
273 -- This function is idempotent; if called more than once, it does nothing
274 -- This is useful in Template Haskell, where we call it before trying to link
276 = do { done <- readIORef v_InitLinkerDone
277 ; if done then return ()
278 else do { writeIORef v_InitLinkerDone True
279 ; reallyInitDynLinker dflags }
282 reallyInitDynLinker dflags
283 = do { -- Initialise the linker state
284 ; writeIORef v_PersistentLinkerState (emptyPLS dflags)
286 -- (a) initialise the C dynamic linker
289 -- (b) Load packages from the command-line
290 ; linkPackages dflags (preloadPackages (pkgState dflags))
292 -- (c) Link libraries from the command-line
293 ; let optl = getOpts dflags opt_l
294 ; let minus_ls = [ lib | '-':'l':lib <- optl ]
296 -- (d) Link .o files from the command-line
297 ; let lib_paths = libraryPaths dflags
298 ; cmdline_ld_inputs <- readIORef v_Ld_inputs
300 ; classified_ld_inputs <- mapM classifyLdInput cmdline_ld_inputs
302 -- (e) Link any MacOS frameworks
303 #ifdef darwin_TARGET_OS
304 ; let framework_paths = frameworkPaths dflags
305 ; let frameworks = cmdlineFrameworks dflags
307 ; let frameworks = []
308 ; let framework_paths = []
310 -- Finally do (c),(d),(e)
311 ; let cmdline_lib_specs = [ l | Just l <- classified_ld_inputs ]
313 ++ map Framework frameworks
314 ; if null cmdline_lib_specs then return ()
317 { mapM_ (preloadLib dflags lib_paths framework_paths) cmdline_lib_specs
318 ; maybePutStr dflags "final link ... "
321 ; if succeeded ok then maybePutStrLn dflags "done"
322 else throwDyn (InstallationError "linking extra libraries/objects failed")
325 classifyLdInput :: FilePath -> IO (Maybe LibrarySpec)
327 | isObjectFilename f = return (Just (Object f))
328 | isDynLibFilename f = return (Just (DLLPath f))
330 hPutStrLn stderr ("Warning: ignoring unrecognised input `" ++ f ++ "'")
333 preloadLib :: DynFlags -> [String] -> [String] -> LibrarySpec -> IO ()
334 preloadLib dflags lib_paths framework_paths lib_spec
335 = do maybePutStr dflags ("Loading object " ++ showLS lib_spec ++ " ... ")
338 -> do b <- preload_static lib_paths static_ish
339 maybePutStrLn dflags (if b then "done"
343 -> do maybe_errstr <- loadDynamic lib_paths dll_unadorned
345 Nothing -> maybePutStrLn dflags "done"
346 Just mm -> preloadFailed mm lib_paths lib_spec
349 -> do maybe_errstr <- loadDLL dll_path
351 Nothing -> maybePutStrLn dflags "done"
352 Just mm -> preloadFailed mm lib_paths lib_spec
354 #ifdef darwin_TARGET_OS
356 -> do maybe_errstr <- loadFramework framework_paths framework
358 Nothing -> maybePutStrLn dflags "done"
359 Just mm -> preloadFailed mm framework_paths lib_spec
362 preloadFailed :: String -> [String] -> LibrarySpec -> IO ()
363 preloadFailed sys_errmsg paths spec
364 = do maybePutStr dflags
365 ("failed.\nDynamic linker error message was:\n "
366 ++ sys_errmsg ++ "\nWhilst trying to load: "
367 ++ showLS spec ++ "\nDirectories to search are:\n"
368 ++ unlines (map (" "++) paths) )
371 -- Not interested in the paths in the static case.
372 preload_static paths name
373 = do b <- doesFileExist name
374 if not b then return False
375 else loadObj name >> return True
378 CmdLineError "user specified .o/.so/.DLL could not be loaded."
382 %************************************************************************
384 Link a byte-code expression
386 %************************************************************************
389 linkExpr :: HscEnv -> SrcSpan -> UnlinkedBCO -> IO HValue
391 -- Link a single expression, *including* first linking packages and
392 -- modules that this expression depends on.
394 -- Raises an IO exception if it can't find a compiled version of the
395 -- dependents to link.
397 -- Note: This function side-effects the linker state (Pepe)
399 linkExpr hsc_env span root_ul_bco
401 -- Initialise the linker (if it's not been done already)
402 let dflags = hsc_dflags hsc_env
403 ; initDynLinker dflags
405 -- The interpreter and dynamic linker can only handle object code built
406 -- the "normal" way, i.e. no non-std ways like profiling or ticky-ticky.
407 -- So here we check the build tag: if we're building a non-standard way
408 -- then we need to find & link object files built the "normal" way.
409 ; maybe_normal_osuf <- checkNonStdWay dflags span
411 -- Find what packages and linkables are required
412 ; eps <- readIORef (hsc_EPS hsc_env)
413 ; (lnks, pkgs) <- getLinkDeps hsc_env hpt (eps_PIT eps)
414 maybe_normal_osuf span needed_mods
416 -- Link the packages and modules required
417 ; linkPackages dflags pkgs
418 ; ok <- linkModules dflags lnks
420 throwDyn (ProgramError "")
423 -- Link the expression itself
424 pls <- readIORef v_PersistentLinkerState
425 ; let ie = itbl_env pls
429 -- Link the necessary packages and linkables
430 ; (_,de_out, (root_hval:_)) <- linkSomeBCOs False ie ce de [root_ul_bco]
431 ; writeIORef v_PersistentLinkerState (pls{dtacons_env=de_out})
435 hpt = hsc_HPT hsc_env
436 free_names = nameSetToList (bcoFreeNames root_ul_bco)
438 needed_mods :: [Module]
439 needed_mods = [ nameModule n | n <- free_names,
440 isExternalName n, -- Names from other modules
441 not (isWiredInName n) -- Exclude wired-in names
442 ] -- (see note below)
443 -- Exclude wired-in names because we may not have read
444 -- their interface files, so getLinkDeps will fail
445 -- All wired-in names are in the base package, which we link
446 -- by default, so we can safely ignore them here.
448 dieWith span msg = throwDyn (ProgramError (showSDoc (mkLocMessage span msg)))
451 checkNonStdWay :: DynFlags -> SrcSpan -> IO (Maybe String)
452 checkNonStdWay dflags srcspan = do
453 tag <- readIORef v_Build_tag
454 if null tag then return Nothing else do
455 let default_osuf = phaseInputExt StopLn
456 if objectSuf dflags == default_osuf
457 then failNonStd srcspan
458 else return (Just default_osuf)
460 failNonStd srcspan = dieWith srcspan $
461 ptext SLIT("Dynamic linking required, but this is a non-standard build (eg. prof).") $$
462 ptext SLIT("You need to build the program twice: once the normal way, and then") $$
463 ptext SLIT("in the desired way using -osuf to set the object file suffix.")
466 getLinkDeps :: HscEnv -> HomePackageTable -> PackageIfaceTable
467 -> Maybe String -- the "normal" object suffix
468 -> SrcSpan -- for error messages
469 -> [Module] -- If you need these
470 -> IO ([Linkable], [PackageId]) -- ... then link these first
471 -- Fails with an IO exception if it can't find enough files
473 getLinkDeps hsc_env hpt pit maybe_normal_osuf span mods
474 -- Find all the packages and linkables that a set of modules depends on
475 = do { pls <- readIORef v_PersistentLinkerState ;
477 -- 1. Find the dependent home-pkg-modules/packages from each iface
478 (mods_s, pkgs_s) = follow_deps mods emptyUniqSet emptyUniqSet;
480 -- 2. Exclude ones already linked
481 -- Main reason: avoid findModule calls in get_linkable
482 mods_needed = mods_s `minusList` linked_mods ;
483 pkgs_needed = pkgs_s `minusList` pkgs_loaded pls ;
485 linked_mods = map (moduleName.linkableModule)
486 (objs_loaded pls ++ bcos_loaded pls)
489 -- putStrLn (showSDoc (ppr mods_s)) ;
490 -- 3. For each dependent module, find its linkable
491 -- This will either be in the HPT or (in the case of one-shot
492 -- compilation) we may need to use maybe_getFileLinkable
493 lnks_needed <- mapM (get_linkable maybe_normal_osuf) mods_needed ;
495 return (lnks_needed, pkgs_needed) }
497 dflags = hsc_dflags hsc_env
498 this_pkg = thisPackage dflags
500 -- The ModIface contains the transitive closure of the module dependencies
501 -- within the current package, *except* for boot modules: if we encounter
502 -- a boot module, we have to find its real interface and discover the
503 -- dependencies of that. Hence we need to traverse the dependency
504 -- tree recursively. See bug #936, testcase ghci/prog007.
505 follow_deps :: [Module] -- modules to follow
506 -> UniqSet ModuleName -- accum. module dependencies
507 -> UniqSet PackageId -- accum. package dependencies
508 -> ([ModuleName], [PackageId]) -- result
509 follow_deps [] acc_mods acc_pkgs
510 = (uniqSetToList acc_mods, uniqSetToList acc_pkgs)
511 follow_deps (mod:mods) acc_mods acc_pkgs
513 = follow_deps mods acc_mods (addOneToUniqSet acc_pkgs' pkg)
515 = link_boot_mod_error mod
517 = follow_deps (map (mkModule this_pkg) boot_deps ++ mods) acc_mods' acc_pkgs'
519 pkg = modulePackageId mod
520 iface = get_iface mod
523 pkg_deps = dep_pkgs deps
524 (boot_deps, mod_deps) = partitionWith is_boot (dep_mods deps)
525 where is_boot (m,True) = Left m
526 is_boot (m,False) = Right m
528 boot_deps' = filter (not . (`elementOfUniqSet` acc_mods)) boot_deps
529 acc_mods' = addListToUniqSet acc_mods (moduleName mod : mod_deps)
530 acc_pkgs' = addListToUniqSet acc_pkgs pkg_deps
533 link_boot_mod_error mod =
534 throwDyn (ProgramError (showSDoc (
535 text "module" <+> ppr mod <+>
536 text "cannot be linked; it is only available as a boot module")))
538 get_iface mod = case lookupIfaceByModule dflags hpt pit mod of
540 Nothing -> pprPanic "getLinkDeps" (no_iface mod)
541 no_iface mod = ptext SLIT("No iface for") <+> ppr mod
542 -- This one is a GHC bug
544 no_obj mod = dieWith span $
545 ptext SLIT("cannot find object file for module ") <>
549 while_linking_expr = ptext SLIT("while linking an interpreted expression")
551 -- This one is a build-system bug
553 get_linkable maybe_normal_osuf mod_name -- A home-package module
554 | Just mod_info <- lookupUFM hpt mod_name
555 = ASSERT(isJust (hm_linkable mod_info))
556 adjust_linkable (fromJust (hm_linkable mod_info))
558 = do -- It's not in the HPT because we are in one shot mode,
559 -- so use the Finder to get a ModLocation...
560 mb_stuff <- findHomeModule hsc_env mod_name
562 Found loc mod -> found loc mod
566 -- ...and then find the linkable for it
567 mb_lnk <- findObjectLinkableMaybe mod loc ;
569 Nothing -> no_obj mod ;
570 Just lnk -> adjust_linkable lnk
574 | Just osuf <- maybe_normal_osuf = do
575 new_uls <- mapM (adjust_ul osuf) (linkableUnlinked lnk)
576 return lnk{ linkableUnlinked=new_uls }
580 adjust_ul osuf (DotO file) = do
581 let new_file = replaceFilenameSuffix file osuf
582 ok <- doesFileExist new_file
585 ptext SLIT("cannot find normal object file ")
586 <> quotes (text new_file) $$ while_linking_expr
587 else return (DotO new_file)
591 %************************************************************************
594 The linkables may consist of a mixture of
595 byte-code modules and object modules
597 %************************************************************************
600 linkModules :: DynFlags -> [Linkable] -> IO SuccessFlag
601 linkModules dflags linkables
602 = block $ do -- don't want to be interrupted by ^C in here
604 let (objs, bcos) = partition isObjectLinkable
605 (concatMap partitionLinkable linkables)
607 -- Load objects first; they can't depend on BCOs
608 ok_flag <- dynLinkObjs dflags objs
610 if failed ok_flag then
617 -- HACK to support f-x-dynamic in the interpreter; no other purpose
618 partitionLinkable :: Linkable -> [Linkable]
620 = let li_uls = linkableUnlinked li
621 li_uls_obj = filter isObject li_uls
622 li_uls_bco = filter isInterpretable li_uls
624 case (li_uls_obj, li_uls_bco) of
625 (objs@(_:_), bcos@(_:_))
626 -> [li{linkableUnlinked=li_uls_obj}, li{linkableUnlinked=li_uls_bco}]
630 findModuleLinkable_maybe :: [Linkable] -> Module -> Maybe Linkable
631 findModuleLinkable_maybe lis mod
632 = case [LM time nm us | LM time nm us <- lis, nm == mod] of
635 many -> pprPanic "findModuleLinkable" (ppr mod)
637 linkableInSet :: Linkable -> [Linkable] -> Bool
638 linkableInSet l objs_loaded =
639 case findModuleLinkable_maybe objs_loaded (linkableModule l) of
641 Just m -> linkableTime l == linkableTime m
645 %************************************************************************
647 \subsection{The object-code linker}
649 %************************************************************************
652 dynLinkObjs :: DynFlags -> [Linkable] -> IO SuccessFlag
653 -- Side-effects the PersistentLinkerState
655 dynLinkObjs dflags objs
656 = do pls <- readIORef v_PersistentLinkerState
658 -- Load the object files and link them
659 let (objs_loaded', new_objs) = rmDupLinkables (objs_loaded pls) objs
660 pls1 = pls { objs_loaded = objs_loaded' }
661 unlinkeds = concatMap linkableUnlinked new_objs
663 mapM loadObj (map nameOfObject unlinkeds)
665 -- Link the all together
668 -- If resolving failed, unload all our
669 -- object modules and carry on
670 if succeeded ok then do
671 writeIORef v_PersistentLinkerState pls1
674 pls2 <- unload_wkr dflags [] pls1
675 writeIORef v_PersistentLinkerState pls2
679 rmDupLinkables :: [Linkable] -- Already loaded
680 -> [Linkable] -- New linkables
681 -> ([Linkable], -- New loaded set (including new ones)
682 [Linkable]) -- New linkables (excluding dups)
683 rmDupLinkables already ls
686 go already extras [] = (already, extras)
687 go already extras (l:ls)
688 | linkableInSet l already = go already extras ls
689 | otherwise = go (l:already) (l:extras) ls
692 %************************************************************************
694 \subsection{The byte-code linker}
696 %************************************************************************
699 dynLinkBCOs :: [Linkable] -> IO ()
700 -- Side-effects the persistent linker state
702 = do pls <- readIORef v_PersistentLinkerState
704 let (bcos_loaded', new_bcos) = rmDupLinkables (bcos_loaded pls) bcos
705 pls1 = pls { bcos_loaded = bcos_loaded' }
706 unlinkeds :: [Unlinked]
707 unlinkeds = concatMap linkableUnlinked new_bcos
709 cbcs :: [CompiledByteCode]
710 cbcs = map byteCodeOfObject unlinkeds
713 ul_bcos = [b | ByteCode bs _ <- cbcs, b <- bs]
714 ies = [ie | ByteCode _ ie <- cbcs]
715 gce = closure_env pls
716 final_ie = foldr plusNameEnv (itbl_env pls) ies
718 (final_gce, final_de, linked_bcos) <- linkSomeBCOs True final_ie gce (dtacons_env pls) ul_bcos
719 -- What happens to these linked_bcos?
721 let pls2 = pls1 { closure_env = final_gce,
722 dtacons_env = final_de,
723 itbl_env = final_ie }
725 writeIORef v_PersistentLinkerState pls2
728 -- Link a bunch of BCOs and return them + updated closure env.
729 linkSomeBCOs :: Bool -- False <=> add _all_ BCOs to returned closure env
730 -- True <=> add only toplevel BCOs to closure env
735 -> IO (ClosureEnv, DataConEnv, [HValue])
736 -- The returned HValues are associated 1-1 with
737 -- the incoming unlinked BCOs. Each gives the
738 -- value of the corresponding unlinked BCO
740 linkSomeBCOs toplevs_only ie ce_in de_in ul_bcos
741 = do let nms = map unlinkedBCOName ul_bcos
743 ( \ hvs -> let ce_out = extendClosureEnv ce_in (zipLazy nms hvs)
744 in mapM (linkBCO ie ce_out) ul_bcos )
745 let ce_all_additions = zip nms hvals
746 ce_top_additions = filter (isExternalName.fst) ce_all_additions
747 ce_additions = if toplevs_only then ce_top_additions
748 else ce_all_additions
749 ce_out = -- make sure we're not inserting duplicate names into the
750 -- closure environment, which leads to trouble.
751 ASSERT (all (not . (`elemNameEnv` ce_in)) (map fst ce_additions))
752 extendClosureEnv ce_in ce_additions
753 names = concatMap (ssElts . unlinkedBCOItbls) ul_bcos
754 addresses <- mapM (lookupIE ie) names
755 let de_additions = [(address, name) | (address, name) <- zip addresses names
756 , not(address `elemAddressEnv` de_in)
758 de_out = extendAddressEnvList de_in de_additions
759 return ( ce_out, de_out, hvals)
764 %************************************************************************
766 Unload some object modules
768 %************************************************************************
771 -- ---------------------------------------------------------------------------
772 -- Unloading old objects ready for a new compilation sweep.
774 -- The compilation manager provides us with a list of linkables that it
775 -- considers "stable", i.e. won't be recompiled this time around. For
776 -- each of the modules current linked in memory,
778 -- * if the linkable is stable (and it's the same one - the
779 -- user may have recompiled the module on the side), we keep it,
781 -- * otherwise, we unload it.
783 -- * we also implicitly unload all temporary bindings at this point.
785 unload :: DynFlags -> [Linkable] -> IO ()
786 -- The 'linkables' are the ones to *keep*
788 unload dflags linkables
789 = block $ do -- block, so we're safe from Ctrl-C in here
791 -- Initialise the linker (if it's not been done already)
794 pls <- readIORef v_PersistentLinkerState
795 new_pls <- unload_wkr dflags linkables pls
796 writeIORef v_PersistentLinkerState new_pls
798 debugTraceMsg dflags 3 (text "unload: retaining objs" <+> ppr (objs_loaded new_pls))
799 debugTraceMsg dflags 3 (text "unload: retaining bcos" <+> ppr (bcos_loaded new_pls))
802 unload_wkr :: DynFlags
803 -> [Linkable] -- stable linkables
804 -> PersistentLinkerState
805 -> IO PersistentLinkerState
806 -- Does the core unload business
807 -- (the wrapper blocks exceptions and deals with the PLS get and put)
809 unload_wkr dflags linkables pls
810 = do let (objs_to_keep, bcos_to_keep) = partition isObjectLinkable linkables
812 objs_loaded' <- filterM (maybeUnload objs_to_keep) (objs_loaded pls)
813 bcos_loaded' <- filterM (maybeUnload bcos_to_keep) (bcos_loaded pls)
815 let bcos_retained = map linkableModule bcos_loaded'
816 itbl_env' = filterNameMap bcos_retained (itbl_env pls)
817 closure_env' = filterNameMap bcos_retained (closure_env pls)
818 new_pls = pls { itbl_env = itbl_env',
819 closure_env = closure_env',
820 bcos_loaded = bcos_loaded',
821 objs_loaded = objs_loaded' }
825 maybeUnload :: [Linkable] -> Linkable -> IO Bool
826 maybeUnload keep_linkables lnk
827 | linkableInSet lnk linkables = return True
829 = do mapM_ unloadObj [f | DotO f <- linkableUnlinked lnk]
830 -- The components of a BCO linkable may contain
831 -- dot-o files. Which is very confusing.
833 -- But the BCO parts can be unlinked just by
834 -- letting go of them (plus of course depopulating
835 -- the symbol table which is done in the main body)
840 %************************************************************************
844 %************************************************************************
849 = Object FilePath -- Full path name of a .o file, including trailing .o
850 -- For dynamic objects only, try to find the object
851 -- file in all the directories specified in
852 -- v_Library_paths before giving up.
854 | DLL String -- "Unadorned" name of a .DLL/.so
855 -- e.g. On unix "qt" denotes "libqt.so"
856 -- On WinDoze "burble" denotes "burble.DLL"
857 -- loadDLL is platform-specific and adds the lib/.so/.DLL
858 -- suffixes platform-dependently
860 | DLLPath FilePath -- Absolute or relative pathname to a dynamic library
861 -- (ends with .dll or .so).
863 | Framework String -- Only used for darwin, but does no harm
865 -- If this package is already part of the GHCi binary, we'll already
866 -- have the right DLLs for this package loaded, so don't try to
869 -- But on Win32 we must load them 'again'; doing so is a harmless no-op
870 -- as far as the loader is concerned, but it does initialise the list
871 -- of DLL handles that rts/Linker.c maintains, and that in turn is
872 -- used by lookupSymbol. So we must call addDLL for each library
873 -- just to get the DLL handle into the list.
875 # if defined(mingw32_TARGET_OS) || defined(darwin_TARGET_OS)
878 = [ "base", "haskell98", "template-haskell", "readline" ]
881 showLS (Object nm) = "(static) " ++ nm
882 showLS (DLL nm) = "(dynamic) " ++ nm
883 showLS (DLLPath nm) = "(dynamic) " ++ nm
884 showLS (Framework nm) = "(framework) " ++ nm
886 linkPackages :: DynFlags -> [PackageId] -> IO ()
887 -- Link exactly the specified packages, and their dependents
888 -- (unless of course they are already linked)
889 -- The dependents are linked automatically, and it doesn't matter
890 -- what order you specify the input packages.
892 -- NOTE: in fact, since each module tracks all the packages it depends on,
893 -- we don't really need to use the package-config dependencies.
894 -- However we do need the package-config stuff (to find aux libs etc),
895 -- and following them lets us load libraries in the right order, which
896 -- perhaps makes the error message a bit more localised if we get a link
897 -- failure. So the dependency walking code is still here.
899 linkPackages dflags new_pkgs
900 = do { pls <- readIORef v_PersistentLinkerState
901 ; let pkg_map = pkgIdMap (pkgState dflags)
903 ; pkgs' <- link pkg_map (pkgs_loaded pls) new_pkgs
905 ; writeIORef v_PersistentLinkerState (pls { pkgs_loaded = pkgs' })
908 link :: PackageConfigMap -> [PackageId] -> [PackageId] -> IO [PackageId]
909 link pkg_map pkgs new_pkgs
910 = foldM (link_one pkg_map) pkgs new_pkgs
912 link_one pkg_map pkgs new_pkg
913 | new_pkg `elem` pkgs -- Already linked
916 | Just pkg_cfg <- lookupPackage pkg_map new_pkg
917 = do { -- Link dependents first
918 pkgs' <- link pkg_map pkgs (map mkPackageId (depends pkg_cfg))
919 -- Now link the package itself
920 ; linkPackage dflags pkg_cfg
921 ; return (new_pkg : pkgs') }
924 = throwDyn (CmdLineError ("unknown package: " ++ packageIdString new_pkg))
927 linkPackage :: DynFlags -> PackageConfig -> IO ()
928 linkPackage dflags pkg
930 let dirs = Packages.libraryDirs pkg
932 let libs = Packages.hsLibraries pkg
933 -- Because of slight differences between the GHC dynamic linker and
934 -- the native system linker some packages have to link with a
935 -- different list of libraries when using GHCi. Examples include: libs
936 -- that are actually gnu ld scripts, and the possability that the .a
937 -- libs do not exactly match the .so/.dll equivalents. So if the
938 -- package file provides an "extra-ghci-libraries" field then we use
939 -- that instead of the "extra-libraries" field.
940 ++ (if null (Packages.extraGHCiLibraries pkg)
941 then Packages.extraLibraries pkg
942 else Packages.extraGHCiLibraries pkg)
943 ++ [ lib | '-':'l':lib <- Packages.ldOptions pkg ]
944 classifieds <- mapM (locateOneObj dirs) libs
946 -- Complication: all the .so's must be loaded before any of the .o's.
947 let dlls = [ dll | DLL dll <- classifieds ]
948 objs = [ obj | Object obj <- classifieds ]
950 maybePutStr dflags ("Loading package " ++ showPackageId (package pkg) ++ " ... ")
952 -- See comments with partOfGHCi
953 when (pkgName (package pkg) `notElem` partOfGHCi) $ do
955 -- When a library A needs symbols from a library B, the order in
956 -- extra_libraries/extra_ld_opts is "-lA -lB", because that's the
957 -- way ld expects it for static linking. Dynamic linking is a
958 -- different story: When A has no dependency information for B,
959 -- dlopen-ing A with RTLD_NOW (see addDLL in Linker.c) will fail
960 -- when B has not been loaded before. In a nutshell: Reverse the
961 -- order of DLLs for dynamic linking.
962 -- This fixes a problem with the HOpenGL package (see "Compiling
963 -- HOpenGL under recent versions of GHC" on the HOpenGL list).
964 mapM_ (load_dyn dirs) (reverse dlls)
966 -- After loading all the DLLs, we can load the static objects.
967 -- Ordering isn't important here, because we do one final link
968 -- step to resolve everything.
971 maybePutStr dflags "linking ... "
973 if succeeded ok then maybePutStrLn dflags "done."
974 else throwDyn (InstallationError ("unable to load package `" ++ showPackageId (package pkg) ++ "'"))
976 load_dyn dirs dll = do r <- loadDynamic dirs dll
979 Just err -> throwDyn (CmdLineError ("can't load .so/.DLL for: "
980 ++ dll ++ " (" ++ err ++ ")" ))
981 #ifndef darwin_TARGET_OS
982 loadFrameworks pkg = return ()
984 loadFrameworks pkg = mapM_ load frameworks
986 fw_dirs = Packages.frameworkDirs pkg
987 frameworks = Packages.frameworks pkg
989 load fw = do r <- loadFramework fw_dirs fw
992 Just err -> throwDyn (CmdLineError ("can't load framework: "
993 ++ fw ++ " (" ++ err ++ ")" ))
996 -- Try to find an object file for a given library in the given paths.
997 -- If it isn't present, we assume it's a dynamic library.
998 locateOneObj :: [FilePath] -> String -> IO LibrarySpec
999 locateOneObj dirs lib
1000 = do { mb_obj_path <- findFile mk_obj_path dirs
1001 ; case mb_obj_path of
1002 Just obj_path -> return (Object obj_path)
1004 do { mb_lib_path <- findFile mk_dyn_lib_path dirs
1005 ; case mb_lib_path of
1006 Just lib_path -> return (DLL (lib ++ "_dyn"))
1007 Nothing -> return (DLL lib) }} -- We assume
1009 mk_obj_path dir = dir `joinFileName` (lib `joinFileExt` "o")
1010 mk_dyn_lib_path dir = dir `joinFileName` mkSOName (lib ++ "_dyn")
1013 -- ----------------------------------------------------------------------------
1014 -- Loading a dyanmic library (dlopen()-ish on Unix, LoadLibrary-ish on Win32)
1016 -- return Nothing == success, else Just error message from dlopen
1017 loadDynamic paths rootname
1018 = do { mb_dll <- findFile mk_dll_path paths
1020 Just dll -> loadDLL dll
1021 Nothing -> loadDLL (mkSOName rootname) }
1022 -- Tried all our known library paths, so let
1023 -- dlopen() search its own builtin paths now.
1025 mk_dll_path dir = dir `joinFileName` mkSOName rootname
1027 #if defined(darwin_TARGET_OS)
1028 mkSOName root = ("lib" ++ root) `joinFileExt` "dylib"
1029 #elif defined(mingw32_TARGET_OS)
1030 -- Win32 DLLs have no .dll extension here, because addDLL tries
1031 -- both foo.dll and foo.drv
1032 mkSOName root = root
1034 mkSOName root = ("lib" ++ root) `joinFileExt` "so"
1037 -- Darwin / MacOS X only: load a framework
1038 -- a framework is a dynamic library packaged inside a directory of the same
1039 -- name. They are searched for in different paths than normal libraries.
1040 #ifdef darwin_TARGET_OS
1041 loadFramework extraPaths rootname
1042 = do { mb_fwk <- findFile mk_fwk (extraPaths ++ defaultFrameworkPaths)
1044 Just fwk_path -> loadDLL fwk_path
1045 Nothing -> return (Just "not found") }
1046 -- Tried all our known library paths, but dlopen()
1047 -- has no built-in paths for frameworks: give up
1049 mk_fwk dir = dir `joinFileName` (rootname ++ ".framework/" ++ rootname)
1050 -- sorry for the hardcoded paths, I hope they won't change anytime soon:
1051 defaultFrameworkPaths = ["/Library/Frameworks", "/System/Library/Frameworks"]
1055 %************************************************************************
1059 %************************************************************************
1062 findFile :: (FilePath -> FilePath) -- Maps a directory path to a file path
1063 -> [FilePath] -- Directories to look in
1064 -> IO (Maybe FilePath) -- The first file path to match
1065 findFile mk_file_path []
1067 findFile mk_file_path (dir:dirs)
1068 = do { let file_path = mk_file_path dir
1069 ; b <- doesFileExist file_path
1071 return (Just file_path)
1073 findFile mk_file_path dirs }
1077 maybePutStr dflags s | verbosity dflags > 0 = putStr s
1078 | otherwise = return ()
1080 maybePutStrLn dflags s | verbosity dflags > 0 = putStrLn s
1081 | otherwise = return ()