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,
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 ( findModule, findObjectLinkableMaybe, FindResult(..) )
35 import Name ( Name, nameModule, isExternalName, isWiredInName )
37 import NameSet ( nameSetToList )
39 import ListSetOps ( minusList )
40 import DynFlags ( DynFlags(..), getOpts )
41 import BasicTypes ( SuccessFlag(..), succeeded, failed )
43 import Panic ( GhcException(..) )
44 import Util ( zipLazy, global, joinFileExt, joinFileName, suffixOf )
45 import StaticFlags ( v_Ld_inputs )
46 import ErrUtils ( debugTraceMsg )
49 import Control.Monad ( when, filterM, foldM )
51 import Data.IORef ( IORef, readIORef, writeIORef, modifyIORef )
52 import Data.List ( partition, nub )
54 import System.IO ( putStr, putStrLn, hPutStrLn, stderr, fixIO )
55 import System.Directory ( doesFileExist )
57 import Control.Exception ( block, throwDyn )
58 import Maybe ( isJust, fromJust )
60 #if __GLASGOW_HASKELL__ >= 503
61 import GHC.IOBase ( IO(..) )
63 import PrelIOBase ( IO(..) )
68 %************************************************************************
72 %************************************************************************
74 The persistent linker state *must* match the actual state of the
75 C dynamic linker at all times, so we keep it in a private global variable.
78 The PersistentLinkerState maps Names to actual closures (for
79 interpreted code only), for use during linking.
82 GLOBAL_VAR(v_PersistentLinkerState, panic "Dynamic linker not initialised", PersistentLinkerState)
83 GLOBAL_VAR(v_InitLinkerDone, False, Bool) -- Set True when dynamic linker is initialised
85 data PersistentLinkerState
86 = PersistentLinkerState {
88 -- Current global mapping from Names to their true values
89 closure_env :: ClosureEnv,
91 -- The current global mapping from RdrNames of DataCons to
92 -- info table addresses.
93 -- When a new Unlinked is linked into the running image, or an existing
94 -- module in the image is replaced, the itbl_env must be updated
98 -- The currently loaded interpreted modules (home package)
99 bcos_loaded :: [Linkable],
101 -- And the currently-loaded compiled modules (home package)
102 objs_loaded :: [Linkable],
104 -- The currently-loaded packages; always object code
105 -- Held, as usual, in dependency order; though I am not sure if
106 -- that is really important
107 pkgs_loaded :: [PackageId]
110 emptyPLS :: DynFlags -> PersistentLinkerState
111 emptyPLS dflags = PersistentLinkerState {
112 closure_env = emptyNameEnv,
113 itbl_env = emptyNameEnv,
114 pkgs_loaded = init_pkgs,
117 -- Packages that don't need loading, because the compiler
118 -- shares them with the interpreted program.
120 -- The linker's symbol table is populated with RTS symbols using an
121 -- explicit list. See rts/Linker.c for details.
123 | ExtPackage rts_id <- rtsPackageId (pkgState dflags) = [rts_id]
128 extendLoadedPkgs :: [PackageId] -> IO ()
129 extendLoadedPkgs pkgs
130 = modifyIORef v_PersistentLinkerState (\s -> s{pkgs_loaded = pkgs ++ pkgs_loaded s})
132 extendLinkEnv :: [(Name,HValue)] -> IO ()
133 -- Automatically discards shadowed bindings
134 extendLinkEnv new_bindings
135 = do pls <- readIORef v_PersistentLinkerState
136 let new_closure_env = extendClosureEnv (closure_env pls) new_bindings
137 new_pls = pls { closure_env = new_closure_env }
138 writeIORef v_PersistentLinkerState new_pls
140 -- filterNameMap removes from the environment all entries except
141 -- those for a given set of modules;
142 -- Note that this removes all *local* (i.e. non-isExternal) names too
143 -- (these are the temporary bindings from the command line).
144 -- Used to filter both the ClosureEnv and ItblEnv
146 filterNameMap :: [Module] -> NameEnv (Name, a) -> NameEnv (Name, a)
147 filterNameMap mods env
148 = filterNameEnv keep_elt env
150 keep_elt (n,_) = isExternalName n
151 && (nameModule n `elem` mods)
156 showLinkerState :: IO ()
157 -- Display the persistent linker state
159 = do pls <- readIORef v_PersistentLinkerState
160 printDump (vcat [text "----- Linker state -----",
161 text "Pkgs:" <+> ppr (pkgs_loaded pls),
162 text "Objs:" <+> ppr (objs_loaded pls),
163 text "BCOs:" <+> ppr (bcos_loaded pls)])
169 %************************************************************************
171 \subsection{Initialisation}
173 %************************************************************************
175 We initialise the dynamic linker by
177 a) calling the C initialisation procedure
179 b) Loading any packages specified on the command line,
180 now held in v_ExplicitPackages
182 c) Loading any packages specified on the command line,
183 now held in the -l options in v_Opt_l
185 d) Loading any .o/.dll files specified on the command line,
186 now held in v_Ld_inputs
188 e) Loading any MacOS frameworks
191 initDynLinker :: DynFlags -> IO ()
192 -- This function is idempotent; if called more than once, it does nothing
193 -- This is useful in Template Haskell, where we call it before trying to link
195 = do { done <- readIORef v_InitLinkerDone
196 ; if done then return ()
197 else do { writeIORef v_InitLinkerDone True
198 ; reallyInitDynLinker dflags }
201 reallyInitDynLinker dflags
202 = do { -- Initialise the linker state
203 ; writeIORef v_PersistentLinkerState (emptyPLS dflags)
205 -- (a) initialise the C dynamic linker
208 -- (b) Load packages from the command-line
209 ; linkPackages dflags (explicitPackages (pkgState dflags))
211 -- (c) Link libraries from the command-line
212 ; let optl = getOpts dflags opt_l
213 ; let minus_ls = [ lib | '-':'l':lib <- optl ]
215 -- (d) Link .o files from the command-line
216 ; let lib_paths = libraryPaths dflags
217 ; cmdline_ld_inputs <- readIORef v_Ld_inputs
219 ; classified_ld_inputs <- mapM classifyLdInput cmdline_ld_inputs
221 -- (e) Link any MacOS frameworks
222 #ifdef darwin_TARGET_OS
223 ; let framework_paths = frameworkPaths dflags
224 ; let frameworks = cmdlineFrameworks dflags
226 ; let frameworks = []
227 ; let framework_paths = []
229 -- Finally do (c),(d),(e)
230 ; let cmdline_lib_specs = [ l | Just l <- classified_ld_inputs ]
232 ++ map Framework frameworks
233 ; if null cmdline_lib_specs then return ()
236 { mapM_ (preloadLib dflags lib_paths framework_paths) cmdline_lib_specs
237 ; maybePutStr dflags "final link ... "
240 ; if succeeded ok then maybePutStrLn dflags "done"
241 else throwDyn (InstallationError "linking extra libraries/objects failed")
244 classifyLdInput :: FilePath -> IO (Maybe LibrarySpec)
246 | isObjectFilename f = return (Just (Object f))
247 | isDynLibFilename f = return (Just (DLLPath f))
249 hPutStrLn stderr ("Warning: ignoring unrecognised input `" ++ f ++ "'")
252 preloadLib :: DynFlags -> [String] -> [String] -> LibrarySpec -> IO ()
253 preloadLib dflags lib_paths framework_paths lib_spec
254 = do maybePutStr dflags ("Loading object " ++ showLS lib_spec ++ " ... ")
257 -> do b <- preload_static lib_paths static_ish
258 maybePutStrLn dflags (if b then "done"
262 -> do maybe_errstr <- loadDynamic lib_paths dll_unadorned
264 Nothing -> maybePutStrLn dflags "done"
265 Just mm -> preloadFailed mm lib_paths lib_spec
268 -> do maybe_errstr <- loadDLL dll_path
270 Nothing -> maybePutStrLn dflags "done"
271 Just mm -> preloadFailed mm lib_paths lib_spec
273 #ifdef darwin_TARGET_OS
275 -> do maybe_errstr <- loadFramework framework_paths framework
277 Nothing -> maybePutStrLn dflags "done"
278 Just mm -> preloadFailed mm framework_paths lib_spec
281 preloadFailed :: String -> [String] -> LibrarySpec -> IO ()
282 preloadFailed sys_errmsg paths spec
283 = do maybePutStr dflags
284 ("failed.\nDynamic linker error message was:\n "
285 ++ sys_errmsg ++ "\nWhilst trying to load: "
286 ++ showLS spec ++ "\nDirectories to search are:\n"
287 ++ unlines (map (" "++) paths) )
290 -- Not interested in the paths in the static case.
291 preload_static paths name
292 = do b <- doesFileExist name
293 if not b then return False
294 else loadObj name >> return True
297 CmdLineError "user specified .o/.so/.DLL could not be loaded."
301 %************************************************************************
303 Link a byte-code expression
305 %************************************************************************
308 linkExpr :: HscEnv -> UnlinkedBCO -> IO HValue
310 -- Link a single expression, *including* first linking packages and
311 -- modules that this expression depends on.
313 -- Raises an IO exception if it can't find a compiled version of the
314 -- dependents to link.
316 linkExpr hsc_env root_ul_bco
318 -- Initialise the linker (if it's not been done already)
319 let dflags = hsc_dflags hsc_env
320 ; initDynLinker dflags
322 -- Find what packages and linkables are required
323 ; eps <- readIORef (hsc_EPS hsc_env)
324 ; (lnks, pkgs) <- getLinkDeps hsc_env hpt (eps_PIT eps) needed_mods
326 -- Link the packages and modules required
327 ; linkPackages dflags pkgs
328 ; ok <- linkModules dflags lnks
333 -- Link the expression itself
334 pls <- readIORef v_PersistentLinkerState
335 ; let ie = itbl_env pls
338 -- Link the necessary packages and linkables
339 ; (_, (root_hval:_)) <- linkSomeBCOs False ie ce [root_ul_bco]
343 hpt = hsc_HPT hsc_env
344 dflags = hsc_dflags hsc_env
345 free_names = nameSetToList (bcoFreeNames root_ul_bco)
347 needed_mods :: [Module]
348 needed_mods = [ nameModule n | n <- free_names,
349 isExternalName n, -- Names from other modules
350 not (isWiredInName n) -- Exclude wired-in names
351 ] -- (see note below)
352 -- Exclude wired-in names because we may not have read
353 -- their interface files, so getLinkDeps will fail
354 -- All wired-in names are in the base package, which we link
355 -- by default, so we can safely ignore them here.
357 dieWith msg = throwDyn (ProgramError (showSDoc msg))
359 getLinkDeps :: HscEnv -> HomePackageTable -> PackageIfaceTable
360 -> [Module] -- If you need these
361 -> IO ([Linkable], [PackageId]) -- ... then link these first
362 -- Fails with an IO exception if it can't find enough files
364 getLinkDeps hsc_env hpt pit mods
365 -- Find all the packages and linkables that a set of modules depends on
366 = do { pls <- readIORef v_PersistentLinkerState ;
368 -- 1. Find the dependent home-pkg-modules/packages from each iface
369 (mods_s, pkgs_s) = unzip (map get_deps mods) ;
371 -- 2. Exclude ones already linked
372 -- Main reason: avoid findModule calls in get_linkable
373 mods_needed = nub (concat mods_s) `minusList` linked_mods ;
374 pkgs_needed = nub (concat pkgs_s) `minusList` pkgs_loaded pls ;
376 linked_mods = map linkableModule (objs_loaded pls ++ bcos_loaded pls)
379 -- 3. For each dependent module, find its linkable
380 -- This will either be in the HPT or (in the case of one-shot
381 -- compilation) we may need to use maybe_getFileLinkable
382 lnks_needed <- mapM get_linkable mods_needed ;
384 return (lnks_needed, pkgs_needed) }
386 get_deps :: Module -> ([Module],[PackageId])
387 -- Get the things needed for the specified module
388 -- This is rather similar to the code in RnNames.importsFromImportDecl
390 | ExtPackage p <- mi_package iface
391 = ([], p : dep_pkgs deps)
393 = (mod : [m | (m,_) <- dep_mods deps], dep_pkgs deps)
395 iface = get_iface mod
398 get_iface mod = case lookupIface hpt pit mod of
400 Nothing -> pprPanic "getLinkDeps" (no_iface mod)
401 no_iface mod = ptext SLIT("No iface for") <+> ppr mod
402 -- This one is a GHC bug
404 no_obj mod = dieWith (ptext SLIT("No compiled code for") <+> ppr mod)
405 -- This one is a build-system bug
407 get_linkable mod_name -- A home-package module
408 | Just mod_info <- lookupModuleEnv hpt mod_name
409 = ASSERT(isJust (hm_linkable mod_info))
410 return (fromJust (hm_linkable mod_info))
412 = -- It's not in the HPT because we are in one shot mode,
413 -- so use the Finder to get a ModLocation...
414 do { mb_stuff <- findModule hsc_env mod_name False ;
416 Found loc _ -> found loc mod_name ;
420 found loc mod_name = do {
421 -- ...and then find the linkable for it
422 mb_lnk <- findObjectLinkableMaybe mod_name loc ;
424 Nothing -> no_obj mod_name ;
425 Just lnk -> return lnk
430 %************************************************************************
433 The linkables may consist of a mixture of
434 byte-code modules and object modules
436 %************************************************************************
439 linkModules :: DynFlags -> [Linkable] -> IO SuccessFlag
440 linkModules dflags linkables
441 = block $ do -- don't want to be interrupted by ^C in here
443 let (objs, bcos) = partition isObjectLinkable
444 (concatMap partitionLinkable linkables)
446 -- Load objects first; they can't depend on BCOs
447 ok_flag <- dynLinkObjs dflags objs
449 if failed ok_flag then
456 -- HACK to support f-x-dynamic in the interpreter; no other purpose
457 partitionLinkable :: Linkable -> [Linkable]
459 = let li_uls = linkableUnlinked li
460 li_uls_obj = filter isObject li_uls
461 li_uls_bco = filter isInterpretable li_uls
463 case (li_uls_obj, li_uls_bco) of
464 (objs@(_:_), bcos@(_:_))
465 -> [li{linkableUnlinked=li_uls_obj}, li{linkableUnlinked=li_uls_bco}]
469 findModuleLinkable_maybe :: [Linkable] -> Module -> Maybe Linkable
470 findModuleLinkable_maybe lis mod
471 = case [LM time nm us | LM time nm us <- lis, nm == mod] of
474 many -> pprPanic "findModuleLinkable" (ppr mod)
476 linkableInSet :: Linkable -> [Linkable] -> Bool
477 linkableInSet l objs_loaded =
478 case findModuleLinkable_maybe objs_loaded (linkableModule l) of
480 Just m -> linkableTime l == linkableTime m
484 %************************************************************************
486 \subsection{The object-code linker}
488 %************************************************************************
491 dynLinkObjs :: DynFlags -> [Linkable] -> IO SuccessFlag
492 -- Side-effects the PersistentLinkerState
494 dynLinkObjs dflags objs
495 = do pls <- readIORef v_PersistentLinkerState
497 -- Load the object files and link them
498 let (objs_loaded', new_objs) = rmDupLinkables (objs_loaded pls) objs
499 pls1 = pls { objs_loaded = objs_loaded' }
500 unlinkeds = concatMap linkableUnlinked new_objs
502 mapM loadObj (map nameOfObject unlinkeds)
504 -- Link the all together
507 -- If resolving failed, unload all our
508 -- object modules and carry on
509 if succeeded ok then do
510 writeIORef v_PersistentLinkerState pls1
513 pls2 <- unload_wkr dflags [] pls1
514 writeIORef v_PersistentLinkerState pls2
518 rmDupLinkables :: [Linkable] -- Already loaded
519 -> [Linkable] -- New linkables
520 -> ([Linkable], -- New loaded set (including new ones)
521 [Linkable]) -- New linkables (excluding dups)
522 rmDupLinkables already ls
525 go already extras [] = (already, extras)
526 go already extras (l:ls)
527 | linkableInSet l already = go already extras ls
528 | otherwise = go (l:already) (l:extras) ls
531 %************************************************************************
533 \subsection{The byte-code linker}
535 %************************************************************************
538 dynLinkBCOs :: [Linkable] -> IO ()
539 -- Side-effects the persistent linker state
541 = do pls <- readIORef v_PersistentLinkerState
543 let (bcos_loaded', new_bcos) = rmDupLinkables (bcos_loaded pls) bcos
544 pls1 = pls { bcos_loaded = bcos_loaded' }
545 unlinkeds :: [Unlinked]
546 unlinkeds = concatMap linkableUnlinked new_bcos
548 cbcs :: [CompiledByteCode]
549 cbcs = map byteCodeOfObject unlinkeds
552 ul_bcos = [b | ByteCode bs _ <- cbcs, b <- bs]
553 ies = [ie | ByteCode _ ie <- cbcs]
554 gce = closure_env pls
555 final_ie = foldr plusNameEnv (itbl_env pls) ies
557 (final_gce, linked_bcos) <- linkSomeBCOs True final_ie gce ul_bcos
558 -- What happens to these linked_bcos?
560 let pls2 = pls1 { closure_env = final_gce,
561 itbl_env = final_ie }
563 writeIORef v_PersistentLinkerState pls2
566 -- Link a bunch of BCOs and return them + updated closure env.
567 linkSomeBCOs :: Bool -- False <=> add _all_ BCOs to returned closure env
568 -- True <=> add only toplevel BCOs to closure env
572 -> IO (ClosureEnv, [HValue])
573 -- The returned HValues are associated 1-1 with
574 -- the incoming unlinked BCOs. Each gives the
575 -- value of the corresponding unlinked BCO
578 linkSomeBCOs toplevs_only ie ce_in ul_bcos
579 = do let nms = map unlinkedBCOName ul_bcos
581 ( \ hvs -> let ce_out = extendClosureEnv ce_in (zipLazy nms hvs)
582 in mapM (linkBCO ie ce_out) ul_bcos )
584 let ce_all_additions = zip nms hvals
585 ce_top_additions = filter (isExternalName.fst) ce_all_additions
586 ce_additions = if toplevs_only then ce_top_additions
587 else ce_all_additions
588 ce_out = -- make sure we're not inserting duplicate names into the
589 -- closure environment, which leads to trouble.
590 ASSERT (all (not . (`elemNameEnv` ce_in)) (map fst ce_additions))
591 extendClosureEnv ce_in ce_additions
592 return (ce_out, hvals)
597 %************************************************************************
599 Unload some object modules
601 %************************************************************************
604 -- ---------------------------------------------------------------------------
605 -- Unloading old objects ready for a new compilation sweep.
607 -- The compilation manager provides us with a list of linkables that it
608 -- considers "stable", i.e. won't be recompiled this time around. For
609 -- each of the modules current linked in memory,
611 -- * if the linkable is stable (and it's the same one - the
612 -- user may have recompiled the module on the side), we keep it,
614 -- * otherwise, we unload it.
616 -- * we also implicitly unload all temporary bindings at this point.
618 unload :: DynFlags -> [Linkable] -> IO ()
619 -- The 'linkables' are the ones to *keep*
621 unload dflags linkables
622 = block $ do -- block, so we're safe from Ctrl-C in here
624 -- Initialise the linker (if it's not been done already)
627 pls <- readIORef v_PersistentLinkerState
628 new_pls <- unload_wkr dflags linkables pls
629 writeIORef v_PersistentLinkerState new_pls
631 debugTraceMsg dflags 3 (text "unload: retaining objs" <+> ppr (objs_loaded new_pls))
632 debugTraceMsg dflags 3 (text "unload: retaining bcos" <+> ppr (bcos_loaded new_pls))
635 unload_wkr :: DynFlags
636 -> [Linkable] -- stable linkables
637 -> PersistentLinkerState
638 -> IO PersistentLinkerState
639 -- Does the core unload business
640 -- (the wrapper blocks exceptions and deals with the PLS get and put)
642 unload_wkr dflags linkables pls
643 = do let (objs_to_keep, bcos_to_keep) = partition isObjectLinkable linkables
645 objs_loaded' <- filterM (maybeUnload objs_to_keep) (objs_loaded pls)
646 bcos_loaded' <- filterM (maybeUnload bcos_to_keep) (bcos_loaded pls)
648 let bcos_retained = map linkableModule bcos_loaded'
649 itbl_env' = filterNameMap bcos_retained (itbl_env pls)
650 closure_env' = filterNameMap bcos_retained (closure_env pls)
651 new_pls = pls { itbl_env = itbl_env',
652 closure_env = closure_env',
653 bcos_loaded = bcos_loaded',
654 objs_loaded = objs_loaded' }
658 maybeUnload :: [Linkable] -> Linkable -> IO Bool
659 maybeUnload keep_linkables lnk
660 | linkableInSet lnk linkables = return True
662 = do mapM_ unloadObj [f | DotO f <- linkableUnlinked lnk]
663 -- The components of a BCO linkable may contain
664 -- dot-o files. Which is very confusing.
666 -- But the BCO parts can be unlinked just by
667 -- letting go of them (plus of course depopulating
668 -- the symbol table which is done in the main body)
673 %************************************************************************
677 %************************************************************************
682 = Object FilePath -- Full path name of a .o file, including trailing .o
683 -- For dynamic objects only, try to find the object
684 -- file in all the directories specified in
685 -- v_Library_paths before giving up.
687 | DLL String -- "Unadorned" name of a .DLL/.so
688 -- e.g. On unix "qt" denotes "libqt.so"
689 -- On WinDoze "burble" denotes "burble.DLL"
690 -- loadDLL is platform-specific and adds the lib/.so/.DLL
691 -- suffixes platform-dependently
693 | DLLPath FilePath -- Absolute or relative pathname to a dynamic library
694 -- (ends with .dll or .so).
696 | Framework String -- Only used for darwin, but does no harm
698 -- If this package is already part of the GHCi binary, we'll already
699 -- have the right DLLs for this package loaded, so don't try to
702 -- But on Win32 we must load them 'again'; doing so is a harmless no-op
703 -- as far as the loader is concerned, but it does initialise the list
704 -- of DLL handles that rts/Linker.c maintains, and that in turn is
705 -- used by lookupSymbol. So we must call addDLL for each library
706 -- just to get the DLL handle into the list.
708 # if defined(mingw32_TARGET_OS) || defined(darwin_TARGET_OS)
711 = [ "base", "haskell98", "template-haskell", "readline" ]
714 showLS (Object nm) = "(static) " ++ nm
715 showLS (DLL nm) = "(dynamic) " ++ nm
716 showLS (DLLPath nm) = "(dynamic) " ++ nm
717 showLS (Framework nm) = "(framework) " ++ nm
719 linkPackages :: DynFlags -> [PackageId] -> IO ()
720 -- Link exactly the specified packages, and their dependents
721 -- (unless of course they are already linked)
722 -- The dependents are linked automatically, and it doesn't matter
723 -- what order you specify the input packages.
725 -- NOTE: in fact, since each module tracks all the packages it depends on,
726 -- we don't really need to use the package-config dependencies.
727 -- However we do need the package-config stuff (to find aux libs etc),
728 -- and following them lets us load libraries in the right order, which
729 -- perhaps makes the error message a bit more localised if we get a link
730 -- failure. So the dependency walking code is still here.
732 linkPackages dflags new_pkgs
733 = do { pls <- readIORef v_PersistentLinkerState
734 ; let pkg_map = pkgIdMap (pkgState dflags)
736 ; pkgs' <- link pkg_map (pkgs_loaded pls) new_pkgs
738 ; writeIORef v_PersistentLinkerState (pls { pkgs_loaded = pkgs' })
741 link :: PackageConfigMap -> [PackageId] -> [PackageId] -> IO [PackageId]
742 link pkg_map pkgs new_pkgs
743 = foldM (link_one pkg_map) pkgs new_pkgs
745 link_one pkg_map pkgs new_pkg
746 | new_pkg `elem` pkgs -- Already linked
749 | Just pkg_cfg <- lookupPackage pkg_map new_pkg
750 = do { -- Link dependents first
751 pkgs' <- link pkg_map pkgs (map mkPackageId (depends pkg_cfg))
752 -- Now link the package itself
753 ; linkPackage dflags pkg_cfg
754 ; return (new_pkg : pkgs') }
757 = throwDyn (CmdLineError ("unknown package: " ++ packageIdString new_pkg))
760 linkPackage :: DynFlags -> PackageConfig -> IO ()
761 linkPackage dflags pkg
763 let dirs = Packages.libraryDirs pkg
765 let libs = Packages.hsLibraries pkg
766 -- Because of slight differences between the GHC dynamic linker and
767 -- the native system linker some packages have to link with a
768 -- different list of libraries when using GHCi. Examples include: libs
769 -- that are actually gnu ld scripts, and the possability that the .a
770 -- libs do not exactly match the .so/.dll equivalents. So if the
771 -- package file provides an "extra-ghci-libraries" field then we use
772 -- that instead of the "extra-libraries" field.
773 ++ (if null (Packages.extraGHCiLibraries pkg)
774 then Packages.extraLibraries pkg
775 else Packages.extraGHCiLibraries pkg)
776 ++ [ lib | '-':'l':lib <- Packages.ldOptions pkg ]
777 classifieds <- mapM (locateOneObj dirs) libs
779 -- Complication: all the .so's must be loaded before any of the .o's.
780 let dlls = [ dll | DLL dll <- classifieds ]
781 objs = [ obj | Object obj <- classifieds ]
783 maybePutStr dflags ("Loading package " ++ showPackageId (package pkg) ++ " ... ")
785 -- See comments with partOfGHCi
786 when (pkgName (package pkg) `notElem` partOfGHCi) $ do
788 -- When a library A needs symbols from a library B, the order in
789 -- extra_libraries/extra_ld_opts is "-lA -lB", because that's the
790 -- way ld expects it for static linking. Dynamic linking is a
791 -- different story: When A has no dependency information for B,
792 -- dlopen-ing A with RTLD_NOW (see addDLL in Linker.c) will fail
793 -- when B has not been loaded before. In a nutshell: Reverse the
794 -- order of DLLs for dynamic linking.
795 -- This fixes a problem with the HOpenGL package (see "Compiling
796 -- HOpenGL under recent versions of GHC" on the HOpenGL list).
797 mapM_ (load_dyn dirs) (reverse dlls)
799 -- After loading all the DLLs, we can load the static objects.
800 -- Ordering isn't important here, because we do one final link
801 -- step to resolve everything.
804 maybePutStr dflags "linking ... "
806 if succeeded ok then maybePutStrLn dflags "done."
807 else throwDyn (InstallationError ("unable to load package `" ++ showPackageId (package pkg) ++ "'"))
809 load_dyn dirs dll = do r <- loadDynamic dirs dll
812 Just err -> throwDyn (CmdLineError ("can't load .so/.DLL for: "
813 ++ dll ++ " (" ++ err ++ ")" ))
814 #ifndef darwin_TARGET_OS
815 loadFrameworks pkg = return ()
817 loadFrameworks pkg = mapM_ load frameworks
819 fw_dirs = Packages.frameworkDirs pkg
820 frameworks = Packages.frameworks pkg
822 load fw = do r <- loadFramework fw_dirs fw
825 Just err -> throwDyn (CmdLineError ("can't load framework: "
826 ++ fw ++ " (" ++ err ++ ")" ))
829 -- Try to find an object file for a given library in the given paths.
830 -- If it isn't present, we assume it's a dynamic library.
831 locateOneObj :: [FilePath] -> String -> IO LibrarySpec
832 locateOneObj dirs lib
833 = do { mb_obj_path <- findFile mk_obj_path dirs
834 ; case mb_obj_path of
835 Just obj_path -> return (Object obj_path)
837 do { mb_lib_path <- findFile mk_dyn_lib_path dirs
838 ; case mb_lib_path of
839 Just lib_path -> return (DLL (lib ++ "_dyn"))
840 Nothing -> return (DLL lib) }} -- We assume
842 mk_obj_path dir = dir `joinFileName` (lib `joinFileExt` "o")
843 mk_dyn_lib_path dir = dir `joinFileName` mkSOName (lib ++ "_dyn")
846 -- ----------------------------------------------------------------------------
847 -- Loading a dyanmic library (dlopen()-ish on Unix, LoadLibrary-ish on Win32)
849 -- return Nothing == success, else Just error message from dlopen
850 loadDynamic paths rootname
851 = do { mb_dll <- findFile mk_dll_path paths
853 Just dll -> loadDLL dll
854 Nothing -> loadDLL (mkSOName rootname) }
855 -- Tried all our known library paths, so let
856 -- dlopen() search its own builtin paths now.
858 mk_dll_path dir = dir `joinFileName` mkSOName rootname
860 #if defined(darwin_TARGET_OS)
861 mkSOName root = ("lib" ++ root) `joinFileExt` "dylib"
862 #elif defined(mingw32_TARGET_OS)
863 -- Win32 DLLs have no .dll extension here, because addDLL tries
864 -- both foo.dll and foo.drv
867 mkSOName root = ("lib" ++ root) `joinFileExt` "so"
870 -- Darwin / MacOS X only: load a framework
871 -- a framework is a dynamic library packaged inside a directory of the same
872 -- name. They are searched for in different paths than normal libraries.
873 #ifdef darwin_TARGET_OS
874 loadFramework extraPaths rootname
875 = do { mb_fwk <- findFile mk_fwk (extraPaths ++ defaultFrameworkPaths)
877 Just fwk_path -> loadDLL fwk_path
878 Nothing -> return (Just "not found") }
879 -- Tried all our known library paths, but dlopen()
880 -- has no built-in paths for frameworks: give up
882 mk_fwk dir = dir `joinFileName` (rootname ++ ".framework/" ++ rootname)
883 -- sorry for the hardcoded paths, I hope they won't change anytime soon:
884 defaultFrameworkPaths = ["/Library/Frameworks", "/System/Library/Frameworks"]
888 %************************************************************************
892 %************************************************************************
895 findFile :: (FilePath -> FilePath) -- Maps a directory path to a file path
896 -> [FilePath] -- Directories to look in
897 -> IO (Maybe FilePath) -- The first file path to match
898 findFile mk_file_path []
900 findFile mk_file_path (dir:dirs)
901 = do { let file_path = mk_file_path dir
902 ; b <- doesFileExist file_path
904 return (Just file_path)
906 findFile mk_file_path dirs }
910 maybePutStr dflags s | verbosity dflags > 0 = putStr s
911 | otherwise = return ()
913 maybePutStrLn dflags s | verbosity dflags > 0 = putStrLn s
914 | otherwise = return ()