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 )
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 pls <- readIORef v_PersistentLinkerState
621 new_pls <- unload_wkr dflags linkables pls
622 writeIORef v_PersistentLinkerState new_pls
624 debugTraceMsg dflags 3 (showSDoc
625 (text "unload: retaining objs" <+> ppr (objs_loaded new_pls)))
626 debugTraceMsg dflags 3 (showSDoc
627 (text "unload: retaining bcos" <+> ppr (bcos_loaded new_pls)))
631 unload_wkr :: DynFlags
632 -> [Linkable] -- stable linkables
633 -> PersistentLinkerState
634 -> IO PersistentLinkerState
635 -- Does the core unload business
636 -- (the wrapper blocks exceptions and deals with the PLS get and put)
638 unload_wkr dflags linkables pls
639 = do let (objs_to_keep, bcos_to_keep) = partition isObjectLinkable linkables
641 objs_loaded' <- filterM (maybeUnload objs_to_keep) (objs_loaded pls)
642 bcos_loaded' <- filterM (maybeUnload bcos_to_keep) (bcos_loaded pls)
644 let bcos_retained = map linkableModule bcos_loaded'
645 itbl_env' = filterNameMap bcos_retained (itbl_env pls)
646 closure_env' = filterNameMap bcos_retained (closure_env pls)
647 new_pls = pls { itbl_env = itbl_env',
648 closure_env = closure_env',
649 bcos_loaded = bcos_loaded',
650 objs_loaded = objs_loaded' }
654 maybeUnload :: [Linkable] -> Linkable -> IO Bool
655 maybeUnload keep_linkables lnk
656 | linkableInSet lnk linkables = return True
658 = do mapM_ unloadObj [f | DotO f <- linkableUnlinked lnk]
659 -- The components of a BCO linkable may contain
660 -- dot-o files. Which is very confusing.
662 -- But the BCO parts can be unlinked just by
663 -- letting go of them (plus of course depopulating
664 -- the symbol table which is done in the main body)
669 %************************************************************************
673 %************************************************************************
678 = Object FilePath -- Full path name of a .o file, including trailing .o
679 -- For dynamic objects only, try to find the object
680 -- file in all the directories specified in
681 -- v_Library_paths before giving up.
683 | DLL String -- "Unadorned" name of a .DLL/.so
684 -- e.g. On unix "qt" denotes "libqt.so"
685 -- On WinDoze "burble" denotes "burble.DLL"
686 -- loadDLL is platform-specific and adds the lib/.so/.DLL
687 -- suffixes platform-dependently
689 | DLLPath FilePath -- Absolute or relative pathname to a dynamic library
690 -- (ends with .dll or .so).
692 | Framework String -- Only used for darwin, but does no harm
694 -- If this package is already part of the GHCi binary, we'll already
695 -- have the right DLLs for this package loaded, so don't try to
698 -- But on Win32 we must load them 'again'; doing so is a harmless no-op
699 -- as far as the loader is concerned, but it does initialise the list
700 -- of DLL handles that rts/Linker.c maintains, and that in turn is
701 -- used by lookupSymbol. So we must call addDLL for each library
702 -- just to get the DLL handle into the list.
704 # if defined(mingw32_TARGET_OS) || defined(darwin_TARGET_OS)
707 = [ "base", "haskell98", "template-haskell", "readline" ]
710 showLS (Object nm) = "(static) " ++ nm
711 showLS (DLL nm) = "(dynamic) " ++ nm
712 showLS (DLLPath nm) = "(dynamic) " ++ nm
713 showLS (Framework nm) = "(framework) " ++ nm
715 linkPackages :: DynFlags -> [PackageId] -> IO ()
716 -- Link exactly the specified packages, and their dependents
717 -- (unless of course they are already linked)
718 -- The dependents are linked automatically, and it doesn't matter
719 -- what order you specify the input packages.
721 -- NOTE: in fact, since each module tracks all the packages it depends on,
722 -- we don't really need to use the package-config dependencies.
723 -- However we do need the package-config stuff (to find aux libs etc),
724 -- and following them lets us load libraries in the right order, which
725 -- perhaps makes the error message a bit more localised if we get a link
726 -- failure. So the dependency walking code is still here.
728 linkPackages dflags new_pkgs
729 = do { pls <- readIORef v_PersistentLinkerState
730 ; let pkg_map = pkgIdMap (pkgState dflags)
732 ; pkgs' <- link pkg_map (pkgs_loaded pls) new_pkgs
734 ; writeIORef v_PersistentLinkerState (pls { pkgs_loaded = pkgs' })
737 link :: PackageConfigMap -> [PackageId] -> [PackageId] -> IO [PackageId]
738 link pkg_map pkgs new_pkgs
739 = foldM (link_one pkg_map) pkgs new_pkgs
741 link_one pkg_map pkgs new_pkg
742 | new_pkg `elem` pkgs -- Already linked
745 | Just pkg_cfg <- lookupPackage pkg_map new_pkg
746 = do { -- Link dependents first
747 pkgs' <- link pkg_map pkgs (map mkPackageId (depends pkg_cfg))
748 -- Now link the package itself
749 ; linkPackage dflags pkg_cfg
750 ; return (new_pkg : pkgs') }
753 = throwDyn (CmdLineError ("unknown package: " ++ packageIdString new_pkg))
756 linkPackage :: DynFlags -> PackageConfig -> IO ()
757 linkPackage dflags pkg
759 let dirs = Packages.libraryDirs pkg
760 let libs = Packages.hsLibraries pkg ++ Packages.extraLibraries pkg
761 ++ [ lib | '-':'l':lib <- Packages.ldOptions pkg ]
762 classifieds <- mapM (locateOneObj dirs) libs
764 -- Complication: all the .so's must be loaded before any of the .o's.
765 let dlls = [ dll | DLL dll <- classifieds ]
766 objs = [ obj | Object obj <- classifieds ]
768 maybePutStr dflags ("Loading package " ++ showPackageId (package pkg) ++ " ... ")
770 -- See comments with partOfGHCi
771 when (pkgName (package pkg) `notElem` partOfGHCi) $ do
773 -- When a library A needs symbols from a library B, the order in
774 -- extra_libraries/extra_ld_opts is "-lA -lB", because that's the
775 -- way ld expects it for static linking. Dynamic linking is a
776 -- different story: When A has no dependency information for B,
777 -- dlopen-ing A with RTLD_NOW (see addDLL in Linker.c) will fail
778 -- when B has not been loaded before. In a nutshell: Reverse the
779 -- order of DLLs for dynamic linking.
780 -- This fixes a problem with the HOpenGL package (see "Compiling
781 -- HOpenGL under recent versions of GHC" on the HOpenGL list).
782 mapM_ (load_dyn dirs) (reverse dlls)
784 -- After loading all the DLLs, we can load the static objects.
785 -- Ordering isn't important here, because we do one final link
786 -- step to resolve everything.
789 maybePutStr dflags "linking ... "
791 if succeeded ok then maybePutStrLn dflags "done."
792 else throwDyn (InstallationError ("unable to load package `" ++ showPackageId (package pkg) ++ "'"))
794 load_dyn dirs dll = do r <- loadDynamic dirs dll
797 Just err -> throwDyn (CmdLineError ("can't load .so/.DLL for: "
798 ++ dll ++ " (" ++ err ++ ")" ))
799 #ifndef darwin_TARGET_OS
800 loadFrameworks pkg = return ()
802 loadFrameworks pkg = mapM_ load frameworks
804 fw_dirs = Packages.frameworkDirs pkg
805 frameworks = Packages.frameworks pkg
807 load fw = do r <- loadFramework fw_dirs fw
810 Just err -> throwDyn (CmdLineError ("can't load framework: "
811 ++ fw ++ " (" ++ err ++ ")" ))
814 -- Try to find an object file for a given library in the given paths.
815 -- If it isn't present, we assume it's a dynamic library.
816 locateOneObj :: [FilePath] -> String -> IO LibrarySpec
817 locateOneObj dirs lib
818 = do { mb_obj_path <- findFile mk_obj_path dirs
819 ; case mb_obj_path of
820 Just obj_path -> return (Object obj_path)
822 do { mb_lib_path <- findFile mk_dyn_lib_path dirs
823 ; case mb_lib_path of
824 Just lib_path -> return (DLL (lib ++ "_dyn"))
825 Nothing -> return (DLL lib) }} -- We assume
827 mk_obj_path dir = dir ++ '/':lib ++ ".o"
828 mk_dyn_lib_path dir = dir ++ '/':mkSOName (lib ++ "_dyn")
831 -- ----------------------------------------------------------------------------
832 -- Loading a dyanmic library (dlopen()-ish on Unix, LoadLibrary-ish on Win32)
834 -- return Nothing == success, else Just error message from dlopen
835 loadDynamic paths rootname
836 = do { mb_dll <- findFile mk_dll_path paths
838 Just dll -> loadDLL dll
839 Nothing -> loadDLL (mkSOName rootname) }
840 -- Tried all our known library paths, so let
841 -- dlopen() search its own builtin paths now.
843 mk_dll_path dir = dir ++ '/':mkSOName rootname
845 #if defined(darwin_TARGET_OS)
846 mkSOName root = "lib" ++ root ++ ".dylib"
847 #elif defined(mingw32_TARGET_OS)
848 -- Win32 DLLs have no .dll extension here, because addDLL tries
849 -- both foo.dll and foo.drv
852 mkSOName root = "lib" ++ root ++ ".so"
855 -- Darwin / MacOS X only: load a framework
856 -- a framework is a dynamic library packaged inside a directory of the same
857 -- name. They are searched for in different paths than normal libraries.
858 #ifdef darwin_TARGET_OS
859 loadFramework extraPaths rootname
860 = do { mb_fwk <- findFile mk_fwk (extraPaths ++ defaultFrameworkPaths)
862 Just fwk_path -> loadDLL fwk_path
863 Nothing -> return (Just "not found") }
864 -- Tried all our known library paths, but dlopen()
865 -- has no built-in paths for frameworks: give up
867 mk_fwk dir = dir ++ '/' : rootname ++ ".framework/" ++ rootname
868 -- sorry for the hardcoded paths, I hope they won't change anytime soon:
869 defaultFrameworkPaths = ["/Library/Frameworks", "/System/Library/Frameworks"]
873 %************************************************************************
877 %************************************************************************
880 findFile :: (FilePath -> FilePath) -- Maps a directory path to a file path
881 -> [FilePath] -- Directories to look in
882 -> IO (Maybe FilePath) -- The first file path to match
883 findFile mk_file_path []
885 findFile mk_file_path (dir:dirs)
886 = do { let file_path = mk_file_path dir
887 ; b <- doesFileExist file_path
889 return (Just file_path)
891 findFile mk_file_path dirs }
895 maybePutStr dflags s | verbosity dflags > 0 = putStr s
896 | otherwise = return ()
898 maybePutStrLn dflags s | verbosity dflags > 0 = putStrLn s
899 | otherwise = return ()