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,
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,
200 c) Loading any packages specified on the command line,
201 now held in the -l options in v_Opt_l
203 d) Loading any .o/.dll files specified on the command line,
204 now held in v_Ld_inputs
206 e) Loading any MacOS frameworks
209 initDynLinker :: DynFlags -> IO ()
210 -- This function is idempotent; if called more than once, it does nothing
211 -- This is useful in Template Haskell, where we call it before trying to link
213 = do { done <- readIORef v_InitLinkerDone
214 ; if done then return ()
215 else do { writeIORef v_InitLinkerDone True
216 ; reallyInitDynLinker dflags }
219 reallyInitDynLinker dflags
220 = do { -- Initialise the linker state
221 ; writeIORef v_PersistentLinkerState (emptyPLS dflags)
223 -- (a) initialise the C dynamic linker
226 -- (b) Load packages from the command-line
227 ; linkPackages dflags (preloadPackages (pkgState dflags))
229 -- (c) Link libraries from the command-line
230 ; let optl = getOpts dflags opt_l
231 ; let minus_ls = [ lib | '-':'l':lib <- optl ]
233 -- (d) Link .o files from the command-line
234 ; let lib_paths = libraryPaths dflags
235 ; cmdline_ld_inputs <- readIORef v_Ld_inputs
237 ; classified_ld_inputs <- mapM classifyLdInput cmdline_ld_inputs
239 -- (e) Link any MacOS frameworks
240 #ifdef darwin_TARGET_OS
241 ; let framework_paths = frameworkPaths dflags
242 ; let frameworks = cmdlineFrameworks dflags
244 ; let frameworks = []
245 ; let framework_paths = []
247 -- Finally do (c),(d),(e)
248 ; let cmdline_lib_specs = [ l | Just l <- classified_ld_inputs ]
250 ++ map Framework frameworks
251 ; if null cmdline_lib_specs then return ()
254 { mapM_ (preloadLib dflags lib_paths framework_paths) cmdline_lib_specs
255 ; maybePutStr dflags "final link ... "
258 ; if succeeded ok then maybePutStrLn dflags "done"
259 else throwDyn (InstallationError "linking extra libraries/objects failed")
262 classifyLdInput :: FilePath -> IO (Maybe LibrarySpec)
264 | isObjectFilename f = return (Just (Object f))
265 | isDynLibFilename f = return (Just (DLLPath f))
267 hPutStrLn stderr ("Warning: ignoring unrecognised input `" ++ f ++ "'")
270 preloadLib :: DynFlags -> [String] -> [String] -> LibrarySpec -> IO ()
271 preloadLib dflags lib_paths framework_paths lib_spec
272 = do maybePutStr dflags ("Loading object " ++ showLS lib_spec ++ " ... ")
275 -> do b <- preload_static lib_paths static_ish
276 maybePutStrLn dflags (if b then "done"
280 -> do maybe_errstr <- loadDynamic lib_paths dll_unadorned
282 Nothing -> maybePutStrLn dflags "done"
283 Just mm -> preloadFailed mm lib_paths lib_spec
286 -> do maybe_errstr <- loadDLL dll_path
288 Nothing -> maybePutStrLn dflags "done"
289 Just mm -> preloadFailed mm lib_paths lib_spec
291 #ifdef darwin_TARGET_OS
293 -> do maybe_errstr <- loadFramework framework_paths framework
295 Nothing -> maybePutStrLn dflags "done"
296 Just mm -> preloadFailed mm framework_paths lib_spec
299 preloadFailed :: String -> [String] -> LibrarySpec -> IO ()
300 preloadFailed sys_errmsg paths spec
301 = do maybePutStr dflags
302 ("failed.\nDynamic linker error message was:\n "
303 ++ sys_errmsg ++ "\nWhilst trying to load: "
304 ++ showLS spec ++ "\nDirectories to search are:\n"
305 ++ unlines (map (" "++) paths) )
308 -- Not interested in the paths in the static case.
309 preload_static paths name
310 = do b <- doesFileExist name
311 if not b then return False
312 else loadObj name >> return True
315 CmdLineError "user specified .o/.so/.DLL could not be loaded."
319 %************************************************************************
321 Link a byte-code expression
323 %************************************************************************
326 linkExpr :: HscEnv -> SrcSpan -> UnlinkedBCO -> IO HValue
328 -- Link a single expression, *including* first linking packages and
329 -- modules that this expression depends on.
331 -- Raises an IO exception if it can't find a compiled version of the
332 -- dependents to link.
334 linkExpr hsc_env span root_ul_bco
336 -- Initialise the linker (if it's not been done already)
337 let dflags = hsc_dflags hsc_env
338 ; initDynLinker dflags
340 -- The interpreter and dynamic linker can only handle object code built
341 -- the "normal" way, i.e. no non-std ways like profiling or ticky-ticky.
342 -- So here we check the build tag: if we're building a non-standard way
343 -- then we need to find & link object files built the "normal" way.
344 ; maybe_normal_osuf <- checkNonStdWay dflags span
346 -- Find what packages and linkables are required
347 ; eps <- readIORef (hsc_EPS hsc_env)
348 ; (lnks, pkgs) <- getLinkDeps hsc_env hpt (eps_PIT eps)
349 maybe_normal_osuf span needed_mods
351 -- Link the packages and modules required
352 ; linkPackages dflags pkgs
353 ; ok <- linkModules dflags lnks
355 throwDyn (ProgramError "")
358 -- Link the expression itself
359 pls <- readIORef v_PersistentLinkerState
360 ; let ie = itbl_env pls
363 -- Link the necessary packages and linkables
364 ; (_, (root_hval:_)) <- linkSomeBCOs False ie ce [root_ul_bco]
368 hpt = hsc_HPT hsc_env
369 free_names = nameSetToList (bcoFreeNames root_ul_bco)
371 needed_mods :: [Module]
372 needed_mods = [ nameModule n | n <- free_names,
373 isExternalName n, -- Names from other modules
374 not (isWiredInName n) -- Exclude wired-in names
375 ] -- (see note below)
376 -- Exclude wired-in names because we may not have read
377 -- their interface files, so getLinkDeps will fail
378 -- All wired-in names are in the base package, which we link
379 -- by default, so we can safely ignore them here.
381 dieWith span msg = throwDyn (ProgramError (showSDoc (mkLocMessage span msg)))
384 checkNonStdWay :: DynFlags -> SrcSpan -> IO (Maybe String)
385 checkNonStdWay dflags srcspan = do
386 tag <- readIORef v_Build_tag
387 if null tag then return Nothing else do
388 let default_osuf = phaseInputExt StopLn
389 if objectSuf dflags == default_osuf
390 then failNonStd srcspan
391 else return (Just default_osuf)
393 failNonStd srcspan = dieWith srcspan $
394 ptext SLIT("Dynamic linking required, but this is a non-standard build (eg. prof).") $$
395 ptext SLIT("You need to build the program twice: once the normal way, and then") $$
396 ptext SLIT("in the desired way using -osuf to set the object file suffix.")
399 getLinkDeps :: HscEnv -> HomePackageTable -> PackageIfaceTable
400 -> Maybe String -- the "normal" object suffix
401 -> SrcSpan -- for error messages
402 -> [Module] -- If you need these
403 -> IO ([Linkable], [PackageId]) -- ... then link these first
404 -- Fails with an IO exception if it can't find enough files
406 getLinkDeps hsc_env hpt pit maybe_normal_osuf span mods
407 -- Find all the packages and linkables that a set of modules depends on
408 = do { pls <- readIORef v_PersistentLinkerState ;
410 -- 1. Find the dependent home-pkg-modules/packages from each iface
411 (mods_s, pkgs_s) = unzip (map get_deps mods) ;
413 -- 2. Exclude ones already linked
414 -- Main reason: avoid findModule calls in get_linkable
415 mods_needed = nub (concat mods_s) `minusList` linked_mods ;
416 pkgs_needed = nub (concat pkgs_s) `minusList` pkgs_loaded pls ;
418 linked_mods = map (moduleName.linkableModule)
419 (objs_loaded pls ++ bcos_loaded pls)
422 -- 3. For each dependent module, find its linkable
423 -- This will either be in the HPT or (in the case of one-shot
424 -- compilation) we may need to use maybe_getFileLinkable
425 lnks_needed <- mapM (get_linkable maybe_normal_osuf) mods_needed ;
427 return (lnks_needed, pkgs_needed) }
429 dflags = hsc_dflags hsc_env
430 this_pkg = thisPackage dflags
432 get_deps :: Module -> ([ModuleName],[PackageId])
433 -- Get the things needed for the specified module
434 -- This is rather similar to the code in RnNames.importsFromImportDecl
437 = ([], pkg : dep_pkgs deps)
439 = (moduleName mod : [m | (m,_) <- dep_mods deps], dep_pkgs deps)
441 pkg = modulePackageId mod
442 deps = mi_deps (get_iface mod)
444 get_iface mod = case lookupIfaceByModule dflags hpt pit mod of
446 Nothing -> pprPanic "getLinkDeps" (no_iface mod)
447 no_iface mod = ptext SLIT("No iface for") <+> ppr mod
448 -- This one is a GHC bug
450 no_obj mod = dieWith span $
451 ptext SLIT("cannot find object file for module ") <>
455 while_linking_expr = ptext SLIT("while linking an interpreted expression")
457 -- This one is a build-system bug
459 get_linkable maybe_normal_osuf mod_name -- A home-package module
460 | Just mod_info <- lookupUFM hpt mod_name
461 = ASSERT(isJust (hm_linkable mod_info))
462 adjust_linkable (fromJust (hm_linkable mod_info))
464 = do -- It's not in the HPT because we are in one shot mode,
465 -- so use the Finder to get a ModLocation...
466 mb_stuff <- findHomeModule hsc_env mod_name
468 Found loc mod -> found loc mod
472 -- ...and then find the linkable for it
473 mb_lnk <- findObjectLinkableMaybe mod loc ;
475 Nothing -> no_obj mod ;
476 Just lnk -> adjust_linkable lnk
480 | Just osuf <- maybe_normal_osuf = do
481 new_uls <- mapM (adjust_ul osuf) (linkableUnlinked lnk)
482 return lnk{ linkableUnlinked=new_uls }
486 adjust_ul osuf (DotO file) = do
487 let new_file = replaceFilenameSuffix file osuf
488 ok <- doesFileExist new_file
491 ptext SLIT("cannot find normal object file ")
492 <> quotes (text new_file) $$ while_linking_expr
493 else return (DotO new_file)
497 %************************************************************************
500 The linkables may consist of a mixture of
501 byte-code modules and object modules
503 %************************************************************************
506 linkModules :: DynFlags -> [Linkable] -> IO SuccessFlag
507 linkModules dflags linkables
508 = block $ do -- don't want to be interrupted by ^C in here
510 let (objs, bcos) = partition isObjectLinkable
511 (concatMap partitionLinkable linkables)
513 -- Load objects first; they can't depend on BCOs
514 ok_flag <- dynLinkObjs dflags objs
516 if failed ok_flag then
523 -- HACK to support f-x-dynamic in the interpreter; no other purpose
524 partitionLinkable :: Linkable -> [Linkable]
526 = let li_uls = linkableUnlinked li
527 li_uls_obj = filter isObject li_uls
528 li_uls_bco = filter isInterpretable li_uls
530 case (li_uls_obj, li_uls_bco) of
531 (objs@(_:_), bcos@(_:_))
532 -> [li{linkableUnlinked=li_uls_obj}, li{linkableUnlinked=li_uls_bco}]
536 findModuleLinkable_maybe :: [Linkable] -> Module -> Maybe Linkable
537 findModuleLinkable_maybe lis mod
538 = case [LM time nm us | LM time nm us <- lis, nm == mod] of
541 many -> pprPanic "findModuleLinkable" (ppr mod)
543 linkableInSet :: Linkable -> [Linkable] -> Bool
544 linkableInSet l objs_loaded =
545 case findModuleLinkable_maybe objs_loaded (linkableModule l) of
547 Just m -> linkableTime l == linkableTime m
551 %************************************************************************
553 \subsection{The object-code linker}
555 %************************************************************************
558 dynLinkObjs :: DynFlags -> [Linkable] -> IO SuccessFlag
559 -- Side-effects the PersistentLinkerState
561 dynLinkObjs dflags objs
562 = do pls <- readIORef v_PersistentLinkerState
564 -- Load the object files and link them
565 let (objs_loaded', new_objs) = rmDupLinkables (objs_loaded pls) objs
566 pls1 = pls { objs_loaded = objs_loaded' }
567 unlinkeds = concatMap linkableUnlinked new_objs
569 mapM loadObj (map nameOfObject unlinkeds)
571 -- Link the all together
574 -- If resolving failed, unload all our
575 -- object modules and carry on
576 if succeeded ok then do
577 writeIORef v_PersistentLinkerState pls1
580 pls2 <- unload_wkr dflags [] pls1
581 writeIORef v_PersistentLinkerState pls2
585 rmDupLinkables :: [Linkable] -- Already loaded
586 -> [Linkable] -- New linkables
587 -> ([Linkable], -- New loaded set (including new ones)
588 [Linkable]) -- New linkables (excluding dups)
589 rmDupLinkables already ls
592 go already extras [] = (already, extras)
593 go already extras (l:ls)
594 | linkableInSet l already = go already extras ls
595 | otherwise = go (l:already) (l:extras) ls
598 %************************************************************************
600 \subsection{The byte-code linker}
602 %************************************************************************
605 dynLinkBCOs :: [Linkable] -> IO ()
606 -- Side-effects the persistent linker state
608 = do pls <- readIORef v_PersistentLinkerState
610 let (bcos_loaded', new_bcos) = rmDupLinkables (bcos_loaded pls) bcos
611 pls1 = pls { bcos_loaded = bcos_loaded' }
612 unlinkeds :: [Unlinked]
613 unlinkeds = concatMap linkableUnlinked new_bcos
615 cbcs :: [CompiledByteCode]
616 cbcs = map byteCodeOfObject unlinkeds
619 ul_bcos = [b | ByteCode bs _ <- cbcs, b <- bs]
620 ies = [ie | ByteCode _ ie <- cbcs]
621 gce = closure_env pls
622 final_ie = foldr plusNameEnv (itbl_env pls) ies
624 (final_gce, linked_bcos) <- linkSomeBCOs True final_ie gce ul_bcos
625 -- What happens to these linked_bcos?
627 let pls2 = pls1 { closure_env = final_gce,
628 itbl_env = final_ie }
630 writeIORef v_PersistentLinkerState pls2
633 -- Link a bunch of BCOs and return them + updated closure env.
634 linkSomeBCOs :: Bool -- False <=> add _all_ BCOs to returned closure env
635 -- True <=> add only toplevel BCOs to closure env
639 -> IO (ClosureEnv, [HValue])
640 -- The returned HValues are associated 1-1 with
641 -- the incoming unlinked BCOs. Each gives the
642 -- value of the corresponding unlinked BCO
645 linkSomeBCOs toplevs_only ie ce_in ul_bcos
646 = do let nms = map unlinkedBCOName ul_bcos
648 ( \ hvs -> let ce_out = extendClosureEnv ce_in (zipLazy nms hvs)
649 in mapM (linkBCO ie ce_out) ul_bcos )
651 let ce_all_additions = zip nms hvals
652 ce_top_additions = filter (isExternalName.fst) ce_all_additions
653 ce_additions = if toplevs_only then ce_top_additions
654 else ce_all_additions
655 ce_out = -- make sure we're not inserting duplicate names into the
656 -- closure environment, which leads to trouble.
657 ASSERT (all (not . (`elemNameEnv` ce_in)) (map fst ce_additions))
658 extendClosureEnv ce_in ce_additions
659 return (ce_out, hvals)
664 %************************************************************************
666 Unload some object modules
668 %************************************************************************
671 -- ---------------------------------------------------------------------------
672 -- Unloading old objects ready for a new compilation sweep.
674 -- The compilation manager provides us with a list of linkables that it
675 -- considers "stable", i.e. won't be recompiled this time around. For
676 -- each of the modules current linked in memory,
678 -- * if the linkable is stable (and it's the same one - the
679 -- user may have recompiled the module on the side), we keep it,
681 -- * otherwise, we unload it.
683 -- * we also implicitly unload all temporary bindings at this point.
685 unload :: DynFlags -> [Linkable] -> IO ()
686 -- The 'linkables' are the ones to *keep*
688 unload dflags linkables
689 = block $ do -- block, so we're safe from Ctrl-C in here
691 -- Initialise the linker (if it's not been done already)
694 pls <- readIORef v_PersistentLinkerState
695 new_pls <- unload_wkr dflags linkables pls
696 writeIORef v_PersistentLinkerState new_pls
698 debugTraceMsg dflags 3 (text "unload: retaining objs" <+> ppr (objs_loaded new_pls))
699 debugTraceMsg dflags 3 (text "unload: retaining bcos" <+> ppr (bcos_loaded new_pls))
702 unload_wkr :: DynFlags
703 -> [Linkable] -- stable linkables
704 -> PersistentLinkerState
705 -> IO PersistentLinkerState
706 -- Does the core unload business
707 -- (the wrapper blocks exceptions and deals with the PLS get and put)
709 unload_wkr dflags linkables pls
710 = do let (objs_to_keep, bcos_to_keep) = partition isObjectLinkable linkables
712 objs_loaded' <- filterM (maybeUnload objs_to_keep) (objs_loaded pls)
713 bcos_loaded' <- filterM (maybeUnload bcos_to_keep) (bcos_loaded pls)
715 let bcos_retained = map linkableModule bcos_loaded'
716 itbl_env' = filterNameMap bcos_retained (itbl_env pls)
717 closure_env' = filterNameMap bcos_retained (closure_env pls)
718 new_pls = pls { itbl_env = itbl_env',
719 closure_env = closure_env',
720 bcos_loaded = bcos_loaded',
721 objs_loaded = objs_loaded' }
725 maybeUnload :: [Linkable] -> Linkable -> IO Bool
726 maybeUnload keep_linkables lnk
727 | linkableInSet lnk linkables = return True
729 = do mapM_ unloadObj [f | DotO f <- linkableUnlinked lnk]
730 -- The components of a BCO linkable may contain
731 -- dot-o files. Which is very confusing.
733 -- But the BCO parts can be unlinked just by
734 -- letting go of them (plus of course depopulating
735 -- the symbol table which is done in the main body)
740 %************************************************************************
744 %************************************************************************
749 = Object FilePath -- Full path name of a .o file, including trailing .o
750 -- For dynamic objects only, try to find the object
751 -- file in all the directories specified in
752 -- v_Library_paths before giving up.
754 | DLL String -- "Unadorned" name of a .DLL/.so
755 -- e.g. On unix "qt" denotes "libqt.so"
756 -- On WinDoze "burble" denotes "burble.DLL"
757 -- loadDLL is platform-specific and adds the lib/.so/.DLL
758 -- suffixes platform-dependently
760 | DLLPath FilePath -- Absolute or relative pathname to a dynamic library
761 -- (ends with .dll or .so).
763 | Framework String -- Only used for darwin, but does no harm
765 -- If this package is already part of the GHCi binary, we'll already
766 -- have the right DLLs for this package loaded, so don't try to
769 -- But on Win32 we must load them 'again'; doing so is a harmless no-op
770 -- as far as the loader is concerned, but it does initialise the list
771 -- of DLL handles that rts/Linker.c maintains, and that in turn is
772 -- used by lookupSymbol. So we must call addDLL for each library
773 -- just to get the DLL handle into the list.
775 # if defined(mingw32_TARGET_OS) || defined(darwin_TARGET_OS)
778 = [ "base", "haskell98", "template-haskell", "readline" ]
781 showLS (Object nm) = "(static) " ++ nm
782 showLS (DLL nm) = "(dynamic) " ++ nm
783 showLS (DLLPath nm) = "(dynamic) " ++ nm
784 showLS (Framework nm) = "(framework) " ++ nm
786 linkPackages :: DynFlags -> [PackageId] -> IO ()
787 -- Link exactly the specified packages, and their dependents
788 -- (unless of course they are already linked)
789 -- The dependents are linked automatically, and it doesn't matter
790 -- what order you specify the input packages.
792 -- NOTE: in fact, since each module tracks all the packages it depends on,
793 -- we don't really need to use the package-config dependencies.
794 -- However we do need the package-config stuff (to find aux libs etc),
795 -- and following them lets us load libraries in the right order, which
796 -- perhaps makes the error message a bit more localised if we get a link
797 -- failure. So the dependency walking code is still here.
799 linkPackages dflags new_pkgs
800 = do { pls <- readIORef v_PersistentLinkerState
801 ; let pkg_map = pkgIdMap (pkgState dflags)
803 ; pkgs' <- link pkg_map (pkgs_loaded pls) new_pkgs
805 ; writeIORef v_PersistentLinkerState (pls { pkgs_loaded = pkgs' })
808 link :: PackageConfigMap -> [PackageId] -> [PackageId] -> IO [PackageId]
809 link pkg_map pkgs new_pkgs
810 = foldM (link_one pkg_map) pkgs new_pkgs
812 link_one pkg_map pkgs new_pkg
813 | new_pkg `elem` pkgs -- Already linked
816 | Just pkg_cfg <- lookupPackage pkg_map new_pkg
817 = do { -- Link dependents first
818 pkgs' <- link pkg_map pkgs (map mkPackageId (depends pkg_cfg))
819 -- Now link the package itself
820 ; linkPackage dflags pkg_cfg
821 ; return (new_pkg : pkgs') }
824 = throwDyn (CmdLineError ("unknown package: " ++ packageIdString new_pkg))
827 linkPackage :: DynFlags -> PackageConfig -> IO ()
828 linkPackage dflags pkg
830 let dirs = Packages.libraryDirs pkg
832 let libs = Packages.hsLibraries pkg
833 -- Because of slight differences between the GHC dynamic linker and
834 -- the native system linker some packages have to link with a
835 -- different list of libraries when using GHCi. Examples include: libs
836 -- that are actually gnu ld scripts, and the possability that the .a
837 -- libs do not exactly match the .so/.dll equivalents. So if the
838 -- package file provides an "extra-ghci-libraries" field then we use
839 -- that instead of the "extra-libraries" field.
840 ++ (if null (Packages.extraGHCiLibraries pkg)
841 then Packages.extraLibraries pkg
842 else Packages.extraGHCiLibraries pkg)
843 ++ [ lib | '-':'l':lib <- Packages.ldOptions pkg ]
844 classifieds <- mapM (locateOneObj dirs) libs
846 -- Complication: all the .so's must be loaded before any of the .o's.
847 let dlls = [ dll | DLL dll <- classifieds ]
848 objs = [ obj | Object obj <- classifieds ]
850 maybePutStr dflags ("Loading package " ++ showPackageId (package pkg) ++ " ... ")
852 -- See comments with partOfGHCi
853 when (pkgName (package pkg) `notElem` partOfGHCi) $ do
855 -- When a library A needs symbols from a library B, the order in
856 -- extra_libraries/extra_ld_opts is "-lA -lB", because that's the
857 -- way ld expects it for static linking. Dynamic linking is a
858 -- different story: When A has no dependency information for B,
859 -- dlopen-ing A with RTLD_NOW (see addDLL in Linker.c) will fail
860 -- when B has not been loaded before. In a nutshell: Reverse the
861 -- order of DLLs for dynamic linking.
862 -- This fixes a problem with the HOpenGL package (see "Compiling
863 -- HOpenGL under recent versions of GHC" on the HOpenGL list).
864 mapM_ (load_dyn dirs) (reverse dlls)
866 -- After loading all the DLLs, we can load the static objects.
867 -- Ordering isn't important here, because we do one final link
868 -- step to resolve everything.
871 maybePutStr dflags "linking ... "
873 if succeeded ok then maybePutStrLn dflags "done."
874 else throwDyn (InstallationError ("unable to load package `" ++ showPackageId (package pkg) ++ "'"))
876 load_dyn dirs dll = do r <- loadDynamic dirs dll
879 Just err -> throwDyn (CmdLineError ("can't load .so/.DLL for: "
880 ++ dll ++ " (" ++ err ++ ")" ))
881 #ifndef darwin_TARGET_OS
882 loadFrameworks pkg = return ()
884 loadFrameworks pkg = mapM_ load frameworks
886 fw_dirs = Packages.frameworkDirs pkg
887 frameworks = Packages.frameworks pkg
889 load fw = do r <- loadFramework fw_dirs fw
892 Just err -> throwDyn (CmdLineError ("can't load framework: "
893 ++ fw ++ " (" ++ err ++ ")" ))
896 -- Try to find an object file for a given library in the given paths.
897 -- If it isn't present, we assume it's a dynamic library.
898 locateOneObj :: [FilePath] -> String -> IO LibrarySpec
899 locateOneObj dirs lib
900 = do { mb_obj_path <- findFile mk_obj_path dirs
901 ; case mb_obj_path of
902 Just obj_path -> return (Object obj_path)
904 do { mb_lib_path <- findFile mk_dyn_lib_path dirs
905 ; case mb_lib_path of
906 Just lib_path -> return (DLL (lib ++ "_dyn"))
907 Nothing -> return (DLL lib) }} -- We assume
909 mk_obj_path dir = dir `joinFileName` (lib `joinFileExt` "o")
910 mk_dyn_lib_path dir = dir `joinFileName` mkSOName (lib ++ "_dyn")
913 -- ----------------------------------------------------------------------------
914 -- Loading a dyanmic library (dlopen()-ish on Unix, LoadLibrary-ish on Win32)
916 -- return Nothing == success, else Just error message from dlopen
917 loadDynamic paths rootname
918 = do { mb_dll <- findFile mk_dll_path paths
920 Just dll -> loadDLL dll
921 Nothing -> loadDLL (mkSOName rootname) }
922 -- Tried all our known library paths, so let
923 -- dlopen() search its own builtin paths now.
925 mk_dll_path dir = dir `joinFileName` mkSOName rootname
927 #if defined(darwin_TARGET_OS)
928 mkSOName root = ("lib" ++ root) `joinFileExt` "dylib"
929 #elif defined(mingw32_TARGET_OS)
930 -- Win32 DLLs have no .dll extension here, because addDLL tries
931 -- both foo.dll and foo.drv
934 mkSOName root = ("lib" ++ root) `joinFileExt` "so"
937 -- Darwin / MacOS X only: load a framework
938 -- a framework is a dynamic library packaged inside a directory of the same
939 -- name. They are searched for in different paths than normal libraries.
940 #ifdef darwin_TARGET_OS
941 loadFramework extraPaths rootname
942 = do { mb_fwk <- findFile mk_fwk (extraPaths ++ defaultFrameworkPaths)
944 Just fwk_path -> loadDLL fwk_path
945 Nothing -> return (Just "not found") }
946 -- Tried all our known library paths, but dlopen()
947 -- has no built-in paths for frameworks: give up
949 mk_fwk dir = dir `joinFileName` (rootname ++ ".framework/" ++ rootname)
950 -- sorry for the hardcoded paths, I hope they won't change anytime soon:
951 defaultFrameworkPaths = ["/Library/Frameworks", "/System/Library/Frameworks"]
955 %************************************************************************
959 %************************************************************************
962 findFile :: (FilePath -> FilePath) -- Maps a directory path to a file path
963 -> [FilePath] -- Directories to look in
964 -> IO (Maybe FilePath) -- The first file path to match
965 findFile mk_file_path []
967 findFile mk_file_path (dir:dirs)
968 = do { let file_path = mk_file_path dir
969 ; b <- doesFileExist file_path
971 return (Just file_path)
973 findFile mk_file_path dirs }
977 maybePutStr dflags s | verbosity dflags > 0 = putStr s
978 | otherwise = return ()
980 maybePutStrLn dflags s | verbosity dflags > 0 = putStrLn s
981 | otherwise = return ()