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,
23 #include "HsVersions.h"
25 import ObjLink ( loadDLL, loadObj, unloadObj, resolveObjs, initObjLinker )
26 import ByteCodeLink ( HValue, ClosureEnv, extendClosureEnv, linkBCO )
27 import ByteCodeItbls ( ItblEnv )
28 import ByteCodeAsm ( CompiledByteCode(..), bcoFreeNames, UnlinkedBCO(..))
31 import DriverPhases ( isObjectFilename, isDynLibFilename )
32 import Util ( getFileSuffix )
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 )
45 import StaticFlags ( v_Ld_inputs )
46 import ErrUtils ( debugTraceMsg )
49 import Control.Monad ( when, filterM, foldM )
51 import Data.IORef ( IORef, readIORef, writeIORef )
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 extendLinkEnv :: [(Name,HValue)] -> IO ()
129 -- Automatically discards shadowed bindings
130 extendLinkEnv new_bindings
131 = do pls <- readIORef v_PersistentLinkerState
132 let new_closure_env = extendClosureEnv (closure_env pls) new_bindings
133 new_pls = pls { closure_env = new_closure_env }
134 writeIORef v_PersistentLinkerState new_pls
136 -- filterNameMap removes from the environment all entries except
137 -- those for a given set of modules;
138 -- Note that this removes all *local* (i.e. non-isExternal) names too
139 -- (these are the temporary bindings from the command line).
140 -- Used to filter both the ClosureEnv and ItblEnv
142 filterNameMap :: [Module] -> NameEnv (Name, a) -> NameEnv (Name, a)
143 filterNameMap mods env
144 = filterNameEnv keep_elt env
146 keep_elt (n,_) = isExternalName n
147 && (nameModule n `elem` mods)
152 showLinkerState :: IO ()
153 -- Display the persistent linker state
155 = do pls <- readIORef v_PersistentLinkerState
156 printDump (vcat [text "----- Linker state -----",
157 text "Pkgs:" <+> ppr (pkgs_loaded pls),
158 text "Objs:" <+> ppr (objs_loaded pls),
159 text "BCOs:" <+> ppr (bcos_loaded pls)])
165 %************************************************************************
167 \subsection{Initialisation}
169 %************************************************************************
171 We initialise the dynamic linker by
173 a) calling the C initialisation procedure
175 b) Loading any packages specified on the command line,
176 now held in v_ExplicitPackages
178 c) Loading any packages specified on the command line,
179 now held in the -l options in v_Opt_l
181 d) Loading any .o/.dll files specified on the command line,
182 now held in v_Ld_inputs
184 e) Loading any MacOS frameworks
187 initDynLinker :: DynFlags -> IO ()
188 -- This function is idempotent; if called more than once, it does nothing
189 -- This is useful in Template Haskell, where we call it before trying to link
191 = do { done <- readIORef v_InitLinkerDone
192 ; if done then return ()
193 else do { writeIORef v_InitLinkerDone True
194 ; reallyInitDynLinker dflags }
197 reallyInitDynLinker dflags
198 = do { -- Initialise the linker state
199 ; writeIORef v_PersistentLinkerState (emptyPLS dflags)
201 -- (a) initialise the C dynamic linker
204 -- (b) Load packages from the command-line
205 ; linkPackages dflags (explicitPackages (pkgState dflags))
207 -- (c) Link libraries from the command-line
208 ; let optl = getOpts dflags opt_l
209 ; let minus_ls = [ lib | '-':'l':lib <- optl ]
211 -- (d) Link .o files from the command-line
212 ; let lib_paths = libraryPaths dflags
213 ; cmdline_ld_inputs <- readIORef v_Ld_inputs
215 ; classified_ld_inputs <- mapM classifyLdInput cmdline_ld_inputs
217 -- (e) Link any MacOS frameworks
218 #ifdef darwin_TARGET_OS
219 ; let framework_paths = frameworkPaths dflags
220 ; let frameworks = cmdlineFrameworks dflags
222 ; let frameworks = []
223 ; let framework_paths = []
225 -- Finally do (c),(d),(e)
226 ; let cmdline_lib_specs = [ l | Just l <- classified_ld_inputs ]
228 ++ map Framework frameworks
229 ; if null cmdline_lib_specs then return ()
232 { mapM_ (preloadLib dflags lib_paths framework_paths) cmdline_lib_specs
233 ; maybePutStr dflags "final link ... "
236 ; if succeeded ok then maybePutStrLn dflags "done"
237 else throwDyn (InstallationError "linking extra libraries/objects failed")
240 classifyLdInput :: FilePath -> IO (Maybe LibrarySpec)
242 | isObjectFilename f = return (Just (Object f))
243 | isDynLibFilename f = return (Just (DLLPath f))
245 hPutStrLn stderr ("Warning: ignoring unrecognised input `" ++ f ++ "'")
248 preloadLib :: DynFlags -> [String] -> [String] -> LibrarySpec -> IO ()
249 preloadLib dflags lib_paths framework_paths lib_spec
250 = do maybePutStr dflags ("Loading object " ++ showLS lib_spec ++ " ... ")
253 -> do b <- preload_static lib_paths static_ish
254 maybePutStrLn dflags (if b then "done"
258 -> do maybe_errstr <- loadDynamic lib_paths dll_unadorned
260 Nothing -> maybePutStrLn dflags "done"
261 Just mm -> preloadFailed mm lib_paths lib_spec
264 -> do maybe_errstr <- loadDLL dll_path
266 Nothing -> maybePutStrLn dflags "done"
267 Just mm -> preloadFailed mm lib_paths lib_spec
269 #ifdef darwin_TARGET_OS
271 -> do maybe_errstr <- loadFramework framework_paths framework
273 Nothing -> maybePutStrLn dflags "done"
274 Just mm -> preloadFailed mm framework_paths lib_spec
277 preloadFailed :: String -> [String] -> LibrarySpec -> IO ()
278 preloadFailed sys_errmsg paths spec
279 = do maybePutStr dflags
280 ("failed.\nDynamic linker error message was:\n "
281 ++ sys_errmsg ++ "\nWhilst trying to load: "
282 ++ showLS spec ++ "\nDirectories to search are:\n"
283 ++ unlines (map (" "++) paths) )
286 -- Not interested in the paths in the static case.
287 preload_static paths name
288 = do b <- doesFileExist name
289 if not b then return False
290 else loadObj name >> return True
293 CmdLineError "user specified .o/.so/.DLL could not be loaded."
297 %************************************************************************
299 Link a byte-code expression
301 %************************************************************************
304 linkExpr :: HscEnv -> UnlinkedBCO -> IO HValue
306 -- Link a single expression, *including* first linking packages and
307 -- modules that this expression depends on.
309 -- Raises an IO exception if it can't find a compiled version of the
310 -- dependents to link.
312 linkExpr hsc_env root_ul_bco
314 -- Initialise the linker (if it's not been done already)
315 let dflags = hsc_dflags hsc_env
316 ; initDynLinker dflags
318 -- Find what packages and linkables are required
319 ; eps <- readIORef (hsc_EPS hsc_env)
320 ; (lnks, pkgs) <- getLinkDeps hsc_env hpt (eps_PIT eps) needed_mods
322 -- Link the packages and modules required
323 ; linkPackages dflags pkgs
324 ; ok <- linkModules dflags lnks
329 -- Link the expression itself
330 pls <- readIORef v_PersistentLinkerState
331 ; let ie = itbl_env pls
334 -- Link the necessary packages and linkables
335 ; (_, (root_hval:_)) <- linkSomeBCOs False ie ce [root_ul_bco]
339 hpt = hsc_HPT hsc_env
340 dflags = hsc_dflags hsc_env
341 free_names = nameSetToList (bcoFreeNames root_ul_bco)
343 needed_mods :: [Module]
344 needed_mods = [ nameModule n | n <- free_names,
345 isExternalName n, -- Names from other modules
346 not (isWiredInName n) -- Exclude wired-in names
347 ] -- (see note below)
348 -- Exclude wired-in names because we may not have read
349 -- their interface files, so getLinkDeps will fail
350 -- All wired-in names are in the base package, which we link
351 -- by default, so we can safely ignore them here.
353 dieWith msg = throwDyn (ProgramError (showSDoc msg))
355 getLinkDeps :: HscEnv -> HomePackageTable -> PackageIfaceTable
356 -> [Module] -- If you need these
357 -> IO ([Linkable], [PackageId]) -- ... then link these first
358 -- Fails with an IO exception if it can't find enough files
360 getLinkDeps hsc_env hpt pit mods
361 -- Find all the packages and linkables that a set of modules depends on
362 = do { pls <- readIORef v_PersistentLinkerState ;
364 -- 1. Find the dependent home-pkg-modules/packages from each iface
365 (mods_s, pkgs_s) = unzip (map get_deps mods) ;
367 -- 2. Exclude ones already linked
368 -- Main reason: avoid findModule calls in get_linkable
369 mods_needed = nub (concat mods_s) `minusList` linked_mods ;
370 pkgs_needed = nub (concat pkgs_s) `minusList` pkgs_loaded pls ;
372 linked_mods = map linkableModule (objs_loaded pls ++ bcos_loaded pls)
375 -- 3. For each dependent module, find its linkable
376 -- This will either be in the HPT or (in the case of one-shot
377 -- compilation) we may need to use maybe_getFileLinkable
378 lnks_needed <- mapM get_linkable mods_needed ;
380 return (lnks_needed, pkgs_needed) }
382 get_deps :: Module -> ([Module],[PackageId])
383 -- Get the things needed for the specified module
384 -- This is rather similar to the code in RnNames.importsFromImportDecl
386 | ExtPackage p <- mi_package iface
387 = ([], p : dep_pkgs deps)
389 = (mod : [m | (m,_) <- dep_mods deps], dep_pkgs deps)
391 iface = get_iface mod
394 get_iface mod = case lookupIface hpt pit mod of
396 Nothing -> pprPanic "getLinkDeps" (no_iface mod)
397 no_iface mod = ptext SLIT("No iface for") <+> ppr mod
398 -- This one is a GHC bug
400 no_obj mod = dieWith (ptext SLIT("No compiled code for") <+> ppr mod)
401 -- This one is a build-system bug
403 get_linkable mod_name -- A home-package module
404 | Just mod_info <- lookupModuleEnv hpt mod_name
405 = ASSERT(isJust (hm_linkable mod_info))
406 return (fromJust (hm_linkable mod_info))
408 = -- It's not in the HPT because we are in one shot mode,
409 -- so use the Finder to get a ModLocation...
410 do { mb_stuff <- findModule hsc_env mod_name False ;
412 Found loc _ -> found loc mod_name ;
416 found loc mod_name = do {
417 -- ...and then find the linkable for it
418 mb_lnk <- findObjectLinkableMaybe mod_name loc ;
420 Nothing -> no_obj mod_name ;
421 Just lnk -> return lnk
426 %************************************************************************
429 The linkables may consist of a mixture of
430 byte-code modules and object modules
432 %************************************************************************
435 linkModules :: DynFlags -> [Linkable] -> IO SuccessFlag
436 linkModules dflags linkables
437 = block $ do -- don't want to be interrupted by ^C in here
439 let (objs, bcos) = partition isObjectLinkable
440 (concatMap partitionLinkable linkables)
442 -- Load objects first; they can't depend on BCOs
443 ok_flag <- dynLinkObjs dflags objs
445 if failed ok_flag then
452 -- HACK to support f-x-dynamic in the interpreter; no other purpose
453 partitionLinkable :: Linkable -> [Linkable]
455 = let li_uls = linkableUnlinked li
456 li_uls_obj = filter isObject li_uls
457 li_uls_bco = filter isInterpretable li_uls
459 case (li_uls_obj, li_uls_bco) of
460 (objs@(_:_), bcos@(_:_))
461 -> [li{linkableUnlinked=li_uls_obj}, li{linkableUnlinked=li_uls_bco}]
465 findModuleLinkable_maybe :: [Linkable] -> Module -> Maybe Linkable
466 findModuleLinkable_maybe lis mod
467 = case [LM time nm us | LM time nm us <- lis, nm == mod] of
470 many -> pprPanic "findModuleLinkable" (ppr mod)
472 linkableInSet :: Linkable -> [Linkable] -> Bool
473 linkableInSet l objs_loaded =
474 case findModuleLinkable_maybe objs_loaded (linkableModule l) of
476 Just m -> linkableTime l == linkableTime m
480 %************************************************************************
482 \subsection{The object-code linker}
484 %************************************************************************
487 dynLinkObjs :: DynFlags -> [Linkable] -> IO SuccessFlag
488 -- Side-effects the PersistentLinkerState
490 dynLinkObjs dflags objs
491 = do pls <- readIORef v_PersistentLinkerState
493 -- Load the object files and link them
494 let (objs_loaded', new_objs) = rmDupLinkables (objs_loaded pls) objs
495 pls1 = pls { objs_loaded = objs_loaded' }
496 unlinkeds = concatMap linkableUnlinked new_objs
498 mapM loadObj (map nameOfObject unlinkeds)
500 -- Link the all together
503 -- If resolving failed, unload all our
504 -- object modules and carry on
505 if succeeded ok then do
506 writeIORef v_PersistentLinkerState pls1
509 pls2 <- unload_wkr dflags [] pls1
510 writeIORef v_PersistentLinkerState pls2
514 rmDupLinkables :: [Linkable] -- Already loaded
515 -> [Linkable] -- New linkables
516 -> ([Linkable], -- New loaded set (including new ones)
517 [Linkable]) -- New linkables (excluding dups)
518 rmDupLinkables already ls
521 go already extras [] = (already, extras)
522 go already extras (l:ls)
523 | linkableInSet l already = go already extras ls
524 | otherwise = go (l:already) (l:extras) ls
527 %************************************************************************
529 \subsection{The byte-code linker}
531 %************************************************************************
534 dynLinkBCOs :: [Linkable] -> IO ()
535 -- Side-effects the persistent linker state
537 = do pls <- readIORef v_PersistentLinkerState
539 let (bcos_loaded', new_bcos) = rmDupLinkables (bcos_loaded pls) bcos
540 pls1 = pls { bcos_loaded = bcos_loaded' }
541 unlinkeds :: [Unlinked]
542 unlinkeds = concatMap linkableUnlinked new_bcos
544 cbcs :: [CompiledByteCode]
545 cbcs = map byteCodeOfObject unlinkeds
548 ul_bcos = [b | ByteCode bs _ <- cbcs, b <- bs]
549 ies = [ie | ByteCode _ ie <- cbcs]
550 gce = closure_env pls
551 final_ie = foldr plusNameEnv (itbl_env pls) ies
553 (final_gce, linked_bcos) <- linkSomeBCOs True final_ie gce ul_bcos
554 -- What happens to these linked_bcos?
556 let pls2 = pls1 { closure_env = final_gce,
557 itbl_env = final_ie }
559 writeIORef v_PersistentLinkerState pls2
562 -- Link a bunch of BCOs and return them + updated closure env.
563 linkSomeBCOs :: Bool -- False <=> add _all_ BCOs to returned closure env
564 -- True <=> add only toplevel BCOs to closure env
568 -> IO (ClosureEnv, [HValue])
569 -- The returned HValues are associated 1-1 with
570 -- the incoming unlinked BCOs. Each gives the
571 -- value of the corresponding unlinked BCO
574 linkSomeBCOs toplevs_only ie ce_in ul_bcos
575 = do let nms = map unlinkedBCOName ul_bcos
577 ( \ hvs -> let ce_out = extendClosureEnv ce_in (zipLazy nms hvs)
578 in mapM (linkBCO ie ce_out) ul_bcos )
580 let ce_all_additions = zip nms hvals
581 ce_top_additions = filter (isExternalName.fst) ce_all_additions
582 ce_additions = if toplevs_only then ce_top_additions
583 else ce_all_additions
584 ce_out = -- make sure we're not inserting duplicate names into the
585 -- closure environment, which leads to trouble.
586 ASSERT (all (not . (`elemNameEnv` ce_in)) (map fst ce_additions))
587 extendClosureEnv ce_in ce_additions
588 return (ce_out, hvals)
593 %************************************************************************
595 Unload some object modules
597 %************************************************************************
600 -- ---------------------------------------------------------------------------
601 -- Unloading old objects ready for a new compilation sweep.
603 -- The compilation manager provides us with a list of linkables that it
604 -- considers "stable", i.e. won't be recompiled this time around. For
605 -- each of the modules current linked in memory,
607 -- * if the linkable is stable (and it's the same one - the
608 -- user may have recompiled the module on the side), we keep it,
610 -- * otherwise, we unload it.
612 -- * we also implicitly unload all temporary bindings at this point.
614 unload :: DynFlags -> [Linkable] -> IO ()
615 -- The 'linkables' are the ones to *keep*
617 unload dflags linkables
618 = block $ do -- block, so we're safe from Ctrl-C in here
620 -- Initialise the linker (if it's not been done already)
623 pls <- readIORef v_PersistentLinkerState
624 new_pls <- unload_wkr dflags linkables pls
625 writeIORef v_PersistentLinkerState new_pls
627 debugTraceMsg dflags 3 (showSDoc
628 (text "unload: retaining objs" <+> ppr (objs_loaded new_pls)))
629 debugTraceMsg dflags 3 (showSDoc
630 (text "unload: retaining bcos" <+> ppr (bcos_loaded new_pls)))
634 unload_wkr :: DynFlags
635 -> [Linkable] -- stable linkables
636 -> PersistentLinkerState
637 -> IO PersistentLinkerState
638 -- Does the core unload business
639 -- (the wrapper blocks exceptions and deals with the PLS get and put)
641 unload_wkr dflags linkables pls
642 = do let (objs_to_keep, bcos_to_keep) = partition isObjectLinkable linkables
644 objs_loaded' <- filterM (maybeUnload objs_to_keep) (objs_loaded pls)
645 bcos_loaded' <- filterM (maybeUnload bcos_to_keep) (bcos_loaded pls)
647 let bcos_retained = map linkableModule bcos_loaded'
648 itbl_env' = filterNameMap bcos_retained (itbl_env pls)
649 closure_env' = filterNameMap bcos_retained (closure_env pls)
650 new_pls = pls { itbl_env = itbl_env',
651 closure_env = closure_env',
652 bcos_loaded = bcos_loaded',
653 objs_loaded = objs_loaded' }
657 maybeUnload :: [Linkable] -> Linkable -> IO Bool
658 maybeUnload keep_linkables lnk
659 | linkableInSet lnk linkables = return True
661 = do mapM_ unloadObj [f | DotO f <- linkableUnlinked lnk]
662 -- The components of a BCO linkable may contain
663 -- dot-o files. Which is very confusing.
665 -- But the BCO parts can be unlinked just by
666 -- letting go of them (plus of course depopulating
667 -- the symbol table which is done in the main body)
672 %************************************************************************
676 %************************************************************************
681 = Object FilePath -- Full path name of a .o file, including trailing .o
682 -- For dynamic objects only, try to find the object
683 -- file in all the directories specified in
684 -- v_Library_paths before giving up.
686 | DLL String -- "Unadorned" name of a .DLL/.so
687 -- e.g. On unix "qt" denotes "libqt.so"
688 -- On WinDoze "burble" denotes "burble.DLL"
689 -- loadDLL is platform-specific and adds the lib/.so/.DLL
690 -- suffixes platform-dependently
692 | DLLPath FilePath -- Absolute or relative pathname to a dynamic library
693 -- (ends with .dll or .so).
695 | Framework String -- Only used for darwin, but does no harm
697 -- If this package is already part of the GHCi binary, we'll already
698 -- have the right DLLs for this package loaded, so don't try to
701 -- But on Win32 we must load them 'again'; doing so is a harmless no-op
702 -- as far as the loader is concerned, but it does initialise the list
703 -- of DLL handles that rts/Linker.c maintains, and that in turn is
704 -- used by lookupSymbol. So we must call addDLL for each library
705 -- just to get the DLL handle into the list.
707 # if defined(mingw32_TARGET_OS) || defined(darwin_TARGET_OS)
710 = [ "base", "haskell98", "template-haskell", "readline" ]
713 showLS (Object nm) = "(static) " ++ nm
714 showLS (DLL nm) = "(dynamic) " ++ nm
715 showLS (DLLPath nm) = "(dynamic) " ++ nm
716 showLS (Framework nm) = "(framework) " ++ nm
718 linkPackages :: DynFlags -> [PackageId] -> IO ()
719 -- Link exactly the specified packages, and their dependents
720 -- (unless of course they are already linked)
721 -- The dependents are linked automatically, and it doesn't matter
722 -- what order you specify the input packages.
724 -- NOTE: in fact, since each module tracks all the packages it depends on,
725 -- we don't really need to use the package-config dependencies.
726 -- However we do need the package-config stuff (to find aux libs etc),
727 -- and following them lets us load libraries in the right order, which
728 -- perhaps makes the error message a bit more localised if we get a link
729 -- failure. So the dependency walking code is still here.
731 linkPackages dflags new_pkgs
732 = do { pls <- readIORef v_PersistentLinkerState
733 ; let pkg_map = pkgIdMap (pkgState dflags)
735 ; pkgs' <- link pkg_map (pkgs_loaded pls) new_pkgs
737 ; writeIORef v_PersistentLinkerState (pls { pkgs_loaded = pkgs' })
740 link :: PackageConfigMap -> [PackageId] -> [PackageId] -> IO [PackageId]
741 link pkg_map pkgs new_pkgs
742 = foldM (link_one pkg_map) pkgs new_pkgs
744 link_one pkg_map pkgs new_pkg
745 | new_pkg `elem` pkgs -- Already linked
748 | Just pkg_cfg <- lookupPackage pkg_map new_pkg
749 = do { -- Link dependents first
750 pkgs' <- link pkg_map pkgs (map mkPackageId (depends pkg_cfg))
751 -- Now link the package itself
752 ; linkPackage dflags pkg_cfg
753 ; return (new_pkg : pkgs') }
756 = throwDyn (CmdLineError ("unknown package: " ++ packageIdString new_pkg))
759 linkPackage :: DynFlags -> PackageConfig -> IO ()
760 linkPackage dflags pkg
762 let dirs = Packages.libraryDirs pkg
763 let libs = Packages.hsLibraries pkg ++ Packages.extraLibraries pkg
764 ++ [ lib | '-':'l':lib <- Packages.ldOptions pkg ]
765 classifieds <- mapM (locateOneObj dirs) libs
767 -- Complication: all the .so's must be loaded before any of the .o's.
768 let dlls = [ dll | DLL dll <- classifieds ]
769 objs = [ obj | Object obj <- classifieds ]
771 maybePutStr dflags ("Loading package " ++ showPackageId (package pkg) ++ " ... ")
773 -- See comments with partOfGHCi
774 when (pkgName (package pkg) `notElem` partOfGHCi) $ do
776 -- When a library A needs symbols from a library B, the order in
777 -- extra_libraries/extra_ld_opts is "-lA -lB", because that's the
778 -- way ld expects it for static linking. Dynamic linking is a
779 -- different story: When A has no dependency information for B,
780 -- dlopen-ing A with RTLD_NOW (see addDLL in Linker.c) will fail
781 -- when B has not been loaded before. In a nutshell: Reverse the
782 -- order of DLLs for dynamic linking.
783 -- This fixes a problem with the HOpenGL package (see "Compiling
784 -- HOpenGL under recent versions of GHC" on the HOpenGL list).
785 mapM_ (load_dyn dirs) (reverse dlls)
787 -- After loading all the DLLs, we can load the static objects.
788 -- Ordering isn't important here, because we do one final link
789 -- step to resolve everything.
792 maybePutStr dflags "linking ... "
794 if succeeded ok then maybePutStrLn dflags "done."
795 else throwDyn (InstallationError ("unable to load package `" ++ showPackageId (package pkg) ++ "'"))
797 load_dyn dirs dll = do r <- loadDynamic dirs dll
800 Just err -> throwDyn (CmdLineError ("can't load .so/.DLL for: "
801 ++ dll ++ " (" ++ err ++ ")" ))
802 #ifndef darwin_TARGET_OS
803 loadFrameworks pkg = return ()
805 loadFrameworks pkg = mapM_ load frameworks
807 fw_dirs = Packages.frameworkDirs pkg
808 frameworks = Packages.frameworks pkg
810 load fw = do r <- loadFramework fw_dirs fw
813 Just err -> throwDyn (CmdLineError ("can't load framework: "
814 ++ fw ++ " (" ++ err ++ ")" ))
817 -- Try to find an object file for a given library in the given paths.
818 -- If it isn't present, we assume it's a dynamic library.
819 locateOneObj :: [FilePath] -> String -> IO LibrarySpec
820 locateOneObj dirs lib
821 = do { mb_obj_path <- findFile mk_obj_path dirs
822 ; case mb_obj_path of
823 Just obj_path -> return (Object obj_path)
825 do { mb_lib_path <- findFile mk_dyn_lib_path dirs
826 ; case mb_lib_path of
827 Just lib_path -> return (DLL (lib ++ "_dyn"))
828 Nothing -> return (DLL lib) }} -- We assume
830 mk_obj_path dir = dir `joinFileName` (lib `joinFileExt` "o")
831 mk_dyn_lib_path dir = dir `joinFileName` mkSOName (lib ++ "_dyn")
834 -- ----------------------------------------------------------------------------
835 -- Loading a dyanmic library (dlopen()-ish on Unix, LoadLibrary-ish on Win32)
837 -- return Nothing == success, else Just error message from dlopen
838 loadDynamic paths rootname
839 = do { mb_dll <- findFile mk_dll_path paths
841 Just dll -> loadDLL dll
842 Nothing -> loadDLL (mkSOName rootname) }
843 -- Tried all our known library paths, so let
844 -- dlopen() search its own builtin paths now.
846 mk_dll_path dir = dir `joinFileName` mkSOName rootname
848 #if defined(darwin_TARGET_OS)
849 mkSOName root = ("lib" ++ root) `joinFileExt` "dylib"
850 #elif defined(mingw32_TARGET_OS)
851 -- Win32 DLLs have no .dll extension here, because addDLL tries
852 -- both foo.dll and foo.drv
855 mkSOName root = ("lib" ++ root) `joinFileExt` "so"
858 -- Darwin / MacOS X only: load a framework
859 -- a framework is a dynamic library packaged inside a directory of the same
860 -- name. They are searched for in different paths than normal libraries.
861 #ifdef darwin_TARGET_OS
862 loadFramework extraPaths rootname
863 = do { mb_fwk <- findFile mk_fwk (extraPaths ++ defaultFrameworkPaths)
865 Just fwk_path -> loadDLL fwk_path
866 Nothing -> return (Just "not found") }
867 -- Tried all our known library paths, but dlopen()
868 -- has no built-in paths for frameworks: give up
870 mk_fwk dir = dir `joinFileName` (rootname ++ ".framework/" ++ rootname)
871 -- sorry for the hardcoded paths, I hope they won't change anytime soon:
872 defaultFrameworkPaths = ["/Library/Frameworks", "/System/Library/Frameworks"]
876 %************************************************************************
880 %************************************************************************
883 findFile :: (FilePath -> FilePath) -- Maps a directory path to a file path
884 -> [FilePath] -- Directories to look in
885 -> IO (Maybe FilePath) -- The first file path to match
886 findFile mk_file_path []
888 findFile mk_file_path (dir:dirs)
889 = do { let file_path = mk_file_path dir
890 ; b <- doesFileExist file_path
892 return (Just file_path)
894 findFile mk_file_path dirs }
898 maybePutStr dflags s | verbosity dflags > 0 = putStr s
899 | otherwise = return ()
901 maybePutStrLn dflags s | verbosity dflags > 0 = putStrLn s
902 | otherwise = return ()