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 Finder ( findModule, findObjectLinkableMaybe, FindResult(..) )
34 import Name ( Name, nameModule, isExternalName, isWiredInName )
36 import NameSet ( nameSetToList )
38 import ListSetOps ( minusList )
39 import DynFlags ( DynFlags(..), getOpts )
40 import BasicTypes ( SuccessFlag(..), succeeded, failed )
42 import Panic ( GhcException(..) )
43 import Util ( zipLazy, global, joinFileExt, joinFileName, suffixOf )
44 import StaticFlags ( v_Ld_inputs )
45 import ErrUtils ( debugTraceMsg )
48 import Control.Monad ( when, filterM, foldM )
50 import Data.IORef ( IORef, readIORef, writeIORef )
51 import Data.List ( partition, nub )
53 import System.IO ( putStr, putStrLn, hPutStrLn, stderr, fixIO )
54 import System.Directory ( doesFileExist )
56 import Control.Exception ( block, throwDyn )
57 import Maybe ( isJust, fromJust )
59 #if __GLASGOW_HASKELL__ >= 503
60 import GHC.IOBase ( IO(..) )
62 import PrelIOBase ( IO(..) )
67 %************************************************************************
71 %************************************************************************
73 The persistent linker state *must* match the actual state of the
74 C dynamic linker at all times, so we keep it in a private global variable.
77 The PersistentLinkerState maps Names to actual closures (for
78 interpreted code only), for use during linking.
81 GLOBAL_VAR(v_PersistentLinkerState, panic "Dynamic linker not initialised", PersistentLinkerState)
82 GLOBAL_VAR(v_InitLinkerDone, False, Bool) -- Set True when dynamic linker is initialised
84 data PersistentLinkerState
85 = PersistentLinkerState {
87 -- Current global mapping from Names to their true values
88 closure_env :: ClosureEnv,
90 -- The current global mapping from RdrNames of DataCons to
91 -- info table addresses.
92 -- When a new Unlinked is linked into the running image, or an existing
93 -- module in the image is replaced, the itbl_env must be updated
97 -- The currently loaded interpreted modules (home package)
98 bcos_loaded :: [Linkable],
100 -- And the currently-loaded compiled modules (home package)
101 objs_loaded :: [Linkable],
103 -- The currently-loaded packages; always object code
104 -- Held, as usual, in dependency order; though I am not sure if
105 -- that is really important
106 pkgs_loaded :: [PackageId]
109 emptyPLS :: DynFlags -> PersistentLinkerState
110 emptyPLS dflags = PersistentLinkerState {
111 closure_env = emptyNameEnv,
112 itbl_env = emptyNameEnv,
113 pkgs_loaded = init_pkgs,
116 -- Packages that don't need loading, because the compiler
117 -- shares them with the interpreted program.
119 -- The linker's symbol table is populated with RTS symbols using an
120 -- explicit list. See rts/Linker.c for details.
122 | ExtPackage rts_id <- rtsPackageId (pkgState dflags) = [rts_id]
127 extendLinkEnv :: [(Name,HValue)] -> IO ()
128 -- Automatically discards shadowed bindings
129 extendLinkEnv new_bindings
130 = do pls <- readIORef v_PersistentLinkerState
131 let new_closure_env = extendClosureEnv (closure_env pls) new_bindings
132 new_pls = pls { closure_env = new_closure_env }
133 writeIORef v_PersistentLinkerState new_pls
135 -- filterNameMap removes from the environment all entries except
136 -- those for a given set of modules;
137 -- Note that this removes all *local* (i.e. non-isExternal) names too
138 -- (these are the temporary bindings from the command line).
139 -- Used to filter both the ClosureEnv and ItblEnv
141 filterNameMap :: [Module] -> NameEnv (Name, a) -> NameEnv (Name, a)
142 filterNameMap mods env
143 = filterNameEnv keep_elt env
145 keep_elt (n,_) = isExternalName n
146 && (nameModule n `elem` mods)
151 showLinkerState :: IO ()
152 -- Display the persistent linker state
154 = do pls <- readIORef v_PersistentLinkerState
155 printDump (vcat [text "----- Linker state -----",
156 text "Pkgs:" <+> ppr (pkgs_loaded pls),
157 text "Objs:" <+> ppr (objs_loaded pls),
158 text "BCOs:" <+> ppr (bcos_loaded pls)])
164 %************************************************************************
166 \subsection{Initialisation}
168 %************************************************************************
170 We initialise the dynamic linker by
172 a) calling the C initialisation procedure
174 b) Loading any packages specified on the command line,
175 now held in v_ExplicitPackages
177 c) Loading any packages specified on the command line,
178 now held in the -l options in v_Opt_l
180 d) Loading any .o/.dll files specified on the command line,
181 now held in v_Ld_inputs
183 e) Loading any MacOS frameworks
186 initDynLinker :: DynFlags -> IO ()
187 -- This function is idempotent; if called more than once, it does nothing
188 -- This is useful in Template Haskell, where we call it before trying to link
190 = do { done <- readIORef v_InitLinkerDone
191 ; if done then return ()
192 else do { writeIORef v_InitLinkerDone True
193 ; reallyInitDynLinker dflags }
196 reallyInitDynLinker dflags
197 = do { -- Initialise the linker state
198 ; writeIORef v_PersistentLinkerState (emptyPLS dflags)
200 -- (a) initialise the C dynamic linker
203 -- (b) Load packages from the command-line
204 ; linkPackages dflags (explicitPackages (pkgState dflags))
206 -- (c) Link libraries from the command-line
207 ; let optl = getOpts dflags opt_l
208 ; let minus_ls = [ lib | '-':'l':lib <- optl ]
210 -- (d) Link .o files from the command-line
211 ; let lib_paths = libraryPaths dflags
212 ; cmdline_ld_inputs <- readIORef v_Ld_inputs
214 ; classified_ld_inputs <- mapM classifyLdInput cmdline_ld_inputs
216 -- (e) Link any MacOS frameworks
217 #ifdef darwin_TARGET_OS
218 ; let framework_paths = frameworkPaths dflags
219 ; let frameworks = cmdlineFrameworks dflags
221 ; let frameworks = []
222 ; let framework_paths = []
224 -- Finally do (c),(d),(e)
225 ; let cmdline_lib_specs = [ l | Just l <- classified_ld_inputs ]
227 ++ map Framework frameworks
228 ; if null cmdline_lib_specs then return ()
231 { mapM_ (preloadLib dflags lib_paths framework_paths) cmdline_lib_specs
232 ; maybePutStr dflags "final link ... "
235 ; if succeeded ok then maybePutStrLn dflags "done"
236 else throwDyn (InstallationError "linking extra libraries/objects failed")
239 classifyLdInput :: FilePath -> IO (Maybe LibrarySpec)
241 | isObjectFilename f = return (Just (Object f))
242 | isDynLibFilename f = return (Just (DLLPath f))
244 hPutStrLn stderr ("Warning: ignoring unrecognised input `" ++ f ++ "'")
247 preloadLib :: DynFlags -> [String] -> [String] -> LibrarySpec -> IO ()
248 preloadLib dflags lib_paths framework_paths lib_spec
249 = do maybePutStr dflags ("Loading object " ++ showLS lib_spec ++ " ... ")
252 -> do b <- preload_static lib_paths static_ish
253 maybePutStrLn dflags (if b then "done"
257 -> do maybe_errstr <- loadDynamic lib_paths dll_unadorned
259 Nothing -> maybePutStrLn dflags "done"
260 Just mm -> preloadFailed mm lib_paths lib_spec
263 -> do maybe_errstr <- loadDLL dll_path
265 Nothing -> maybePutStrLn dflags "done"
266 Just mm -> preloadFailed mm lib_paths lib_spec
268 #ifdef darwin_TARGET_OS
270 -> do maybe_errstr <- loadFramework framework_paths framework
272 Nothing -> maybePutStrLn dflags "done"
273 Just mm -> preloadFailed mm framework_paths lib_spec
276 preloadFailed :: String -> [String] -> LibrarySpec -> IO ()
277 preloadFailed sys_errmsg paths spec
278 = do maybePutStr dflags
279 ("failed.\nDynamic linker error message was:\n "
280 ++ sys_errmsg ++ "\nWhilst trying to load: "
281 ++ showLS spec ++ "\nDirectories to search are:\n"
282 ++ unlines (map (" "++) paths) )
285 -- Not interested in the paths in the static case.
286 preload_static paths name
287 = do b <- doesFileExist name
288 if not b then return False
289 else loadObj name >> return True
292 CmdLineError "user specified .o/.so/.DLL could not be loaded."
296 %************************************************************************
298 Link a byte-code expression
300 %************************************************************************
303 linkExpr :: HscEnv -> UnlinkedBCO -> IO HValue
305 -- Link a single expression, *including* first linking packages and
306 -- modules that this expression depends on.
308 -- Raises an IO exception if it can't find a compiled version of the
309 -- dependents to link.
311 linkExpr hsc_env root_ul_bco
313 -- Initialise the linker (if it's not been done already)
314 let dflags = hsc_dflags hsc_env
315 ; initDynLinker dflags
317 -- Find what packages and linkables are required
318 ; eps <- readIORef (hsc_EPS hsc_env)
319 ; (lnks, pkgs) <- getLinkDeps hsc_env hpt (eps_PIT eps) needed_mods
321 -- Link the packages and modules required
322 ; linkPackages dflags pkgs
323 ; ok <- linkModules dflags lnks
328 -- Link the expression itself
329 pls <- readIORef v_PersistentLinkerState
330 ; let ie = itbl_env pls
333 -- Link the necessary packages and linkables
334 ; (_, (root_hval:_)) <- linkSomeBCOs False ie ce [root_ul_bco]
338 hpt = hsc_HPT hsc_env
339 dflags = hsc_dflags hsc_env
340 free_names = nameSetToList (bcoFreeNames root_ul_bco)
342 needed_mods :: [Module]
343 needed_mods = [ nameModule n | n <- free_names,
344 isExternalName n, -- Names from other modules
345 not (isWiredInName n) -- Exclude wired-in names
346 ] -- (see note below)
347 -- Exclude wired-in names because we may not have read
348 -- their interface files, so getLinkDeps will fail
349 -- All wired-in names are in the base package, which we link
350 -- by default, so we can safely ignore them here.
352 dieWith msg = throwDyn (ProgramError (showSDoc msg))
354 getLinkDeps :: HscEnv -> HomePackageTable -> PackageIfaceTable
355 -> [Module] -- If you need these
356 -> IO ([Linkable], [PackageId]) -- ... then link these first
357 -- Fails with an IO exception if it can't find enough files
359 getLinkDeps hsc_env hpt pit mods
360 -- Find all the packages and linkables that a set of modules depends on
361 = do { pls <- readIORef v_PersistentLinkerState ;
363 -- 1. Find the dependent home-pkg-modules/packages from each iface
364 (mods_s, pkgs_s) = unzip (map get_deps mods) ;
366 -- 2. Exclude ones already linked
367 -- Main reason: avoid findModule calls in get_linkable
368 mods_needed = nub (concat mods_s) `minusList` linked_mods ;
369 pkgs_needed = nub (concat pkgs_s) `minusList` pkgs_loaded pls ;
371 linked_mods = map linkableModule (objs_loaded pls ++ bcos_loaded pls)
374 -- 3. For each dependent module, find its linkable
375 -- This will either be in the HPT or (in the case of one-shot
376 -- compilation) we may need to use maybe_getFileLinkable
377 lnks_needed <- mapM get_linkable mods_needed ;
379 return (lnks_needed, pkgs_needed) }
381 get_deps :: Module -> ([Module],[PackageId])
382 -- Get the things needed for the specified module
383 -- This is rather similar to the code in RnNames.importsFromImportDecl
385 | ExtPackage p <- mi_package iface
386 = ([], p : dep_pkgs deps)
388 = (mod : [m | (m,_) <- dep_mods deps], dep_pkgs deps)
390 iface = get_iface mod
393 get_iface mod = case lookupIface hpt pit mod of
395 Nothing -> pprPanic "getLinkDeps" (no_iface mod)
396 no_iface mod = ptext SLIT("No iface for") <+> ppr mod
397 -- This one is a GHC bug
399 no_obj mod = dieWith (ptext SLIT("No compiled code for") <+> ppr mod)
400 -- This one is a build-system bug
402 get_linkable mod_name -- A home-package module
403 | Just mod_info <- lookupModuleEnv hpt mod_name
404 = ASSERT(isJust (hm_linkable mod_info))
405 return (fromJust (hm_linkable mod_info))
407 = -- It's not in the HPT because we are in one shot mode,
408 -- so use the Finder to get a ModLocation...
409 do { mb_stuff <- findModule hsc_env mod_name False ;
411 Found loc _ -> found loc mod_name ;
415 found loc mod_name = do {
416 -- ...and then find the linkable for it
417 mb_lnk <- findObjectLinkableMaybe mod_name loc ;
419 Nothing -> no_obj mod_name ;
420 Just lnk -> return lnk
425 %************************************************************************
428 The linkables may consist of a mixture of
429 byte-code modules and object modules
431 %************************************************************************
434 linkModules :: DynFlags -> [Linkable] -> IO SuccessFlag
435 linkModules dflags linkables
436 = block $ do -- don't want to be interrupted by ^C in here
438 let (objs, bcos) = partition isObjectLinkable
439 (concatMap partitionLinkable linkables)
441 -- Load objects first; they can't depend on BCOs
442 ok_flag <- dynLinkObjs dflags objs
444 if failed ok_flag then
451 -- HACK to support f-x-dynamic in the interpreter; no other purpose
452 partitionLinkable :: Linkable -> [Linkable]
454 = let li_uls = linkableUnlinked li
455 li_uls_obj = filter isObject li_uls
456 li_uls_bco = filter isInterpretable li_uls
458 case (li_uls_obj, li_uls_bco) of
459 (objs@(_:_), bcos@(_:_))
460 -> [li{linkableUnlinked=li_uls_obj}, li{linkableUnlinked=li_uls_bco}]
464 findModuleLinkable_maybe :: [Linkable] -> Module -> Maybe Linkable
465 findModuleLinkable_maybe lis mod
466 = case [LM time nm us | LM time nm us <- lis, nm == mod] of
469 many -> pprPanic "findModuleLinkable" (ppr mod)
471 linkableInSet :: Linkable -> [Linkable] -> Bool
472 linkableInSet l objs_loaded =
473 case findModuleLinkable_maybe objs_loaded (linkableModule l) of
475 Just m -> linkableTime l == linkableTime m
479 %************************************************************************
481 \subsection{The object-code linker}
483 %************************************************************************
486 dynLinkObjs :: DynFlags -> [Linkable] -> IO SuccessFlag
487 -- Side-effects the PersistentLinkerState
489 dynLinkObjs dflags objs
490 = do pls <- readIORef v_PersistentLinkerState
492 -- Load the object files and link them
493 let (objs_loaded', new_objs) = rmDupLinkables (objs_loaded pls) objs
494 pls1 = pls { objs_loaded = objs_loaded' }
495 unlinkeds = concatMap linkableUnlinked new_objs
497 mapM loadObj (map nameOfObject unlinkeds)
499 -- Link the all together
502 -- If resolving failed, unload all our
503 -- object modules and carry on
504 if succeeded ok then do
505 writeIORef v_PersistentLinkerState pls1
508 pls2 <- unload_wkr dflags [] pls1
509 writeIORef v_PersistentLinkerState pls2
513 rmDupLinkables :: [Linkable] -- Already loaded
514 -> [Linkable] -- New linkables
515 -> ([Linkable], -- New loaded set (including new ones)
516 [Linkable]) -- New linkables (excluding dups)
517 rmDupLinkables already ls
520 go already extras [] = (already, extras)
521 go already extras (l:ls)
522 | linkableInSet l already = go already extras ls
523 | otherwise = go (l:already) (l:extras) ls
526 %************************************************************************
528 \subsection{The byte-code linker}
530 %************************************************************************
533 dynLinkBCOs :: [Linkable] -> IO ()
534 -- Side-effects the persistent linker state
536 = do pls <- readIORef v_PersistentLinkerState
538 let (bcos_loaded', new_bcos) = rmDupLinkables (bcos_loaded pls) bcos
539 pls1 = pls { bcos_loaded = bcos_loaded' }
540 unlinkeds :: [Unlinked]
541 unlinkeds = concatMap linkableUnlinked new_bcos
543 cbcs :: [CompiledByteCode]
544 cbcs = map byteCodeOfObject unlinkeds
547 ul_bcos = [b | ByteCode bs _ <- cbcs, b <- bs]
548 ies = [ie | ByteCode _ ie <- cbcs]
549 gce = closure_env pls
550 final_ie = foldr plusNameEnv (itbl_env pls) ies
552 (final_gce, linked_bcos) <- linkSomeBCOs True final_ie gce ul_bcos
553 -- What happens to these linked_bcos?
555 let pls2 = pls1 { closure_env = final_gce,
556 itbl_env = final_ie }
558 writeIORef v_PersistentLinkerState pls2
561 -- Link a bunch of BCOs and return them + updated closure env.
562 linkSomeBCOs :: Bool -- False <=> add _all_ BCOs to returned closure env
563 -- True <=> add only toplevel BCOs to closure env
567 -> IO (ClosureEnv, [HValue])
568 -- The returned HValues are associated 1-1 with
569 -- the incoming unlinked BCOs. Each gives the
570 -- value of the corresponding unlinked BCO
573 linkSomeBCOs toplevs_only ie ce_in ul_bcos
574 = do let nms = map unlinkedBCOName ul_bcos
576 ( \ hvs -> let ce_out = extendClosureEnv ce_in (zipLazy nms hvs)
577 in mapM (linkBCO ie ce_out) ul_bcos )
579 let ce_all_additions = zip nms hvals
580 ce_top_additions = filter (isExternalName.fst) ce_all_additions
581 ce_additions = if toplevs_only then ce_top_additions
582 else ce_all_additions
583 ce_out = -- make sure we're not inserting duplicate names into the
584 -- closure environment, which leads to trouble.
585 ASSERT (all (not . (`elemNameEnv` ce_in)) (map fst ce_additions))
586 extendClosureEnv ce_in ce_additions
587 return (ce_out, hvals)
592 %************************************************************************
594 Unload some object modules
596 %************************************************************************
599 -- ---------------------------------------------------------------------------
600 -- Unloading old objects ready for a new compilation sweep.
602 -- The compilation manager provides us with a list of linkables that it
603 -- considers "stable", i.e. won't be recompiled this time around. For
604 -- each of the modules current linked in memory,
606 -- * if the linkable is stable (and it's the same one - the
607 -- user may have recompiled the module on the side), we keep it,
609 -- * otherwise, we unload it.
611 -- * we also implicitly unload all temporary bindings at this point.
613 unload :: DynFlags -> [Linkable] -> IO ()
614 -- The 'linkables' are the ones to *keep*
616 unload dflags linkables
617 = block $ do -- block, so we're safe from Ctrl-C in here
619 -- Initialise the linker (if it's not been done already)
622 pls <- readIORef v_PersistentLinkerState
623 new_pls <- unload_wkr dflags linkables pls
624 writeIORef v_PersistentLinkerState new_pls
626 debugTraceMsg dflags 3 (text "unload: retaining objs" <+> ppr (objs_loaded new_pls))
627 debugTraceMsg dflags 3 (text "unload: retaining bcos" <+> ppr (bcos_loaded new_pls))
630 unload_wkr :: DynFlags
631 -> [Linkable] -- stable linkables
632 -> PersistentLinkerState
633 -> IO PersistentLinkerState
634 -- Does the core unload business
635 -- (the wrapper blocks exceptions and deals with the PLS get and put)
637 unload_wkr dflags linkables pls
638 = do let (objs_to_keep, bcos_to_keep) = partition isObjectLinkable linkables
640 objs_loaded' <- filterM (maybeUnload objs_to_keep) (objs_loaded pls)
641 bcos_loaded' <- filterM (maybeUnload bcos_to_keep) (bcos_loaded pls)
643 let bcos_retained = map linkableModule bcos_loaded'
644 itbl_env' = filterNameMap bcos_retained (itbl_env pls)
645 closure_env' = filterNameMap bcos_retained (closure_env pls)
646 new_pls = pls { itbl_env = itbl_env',
647 closure_env = closure_env',
648 bcos_loaded = bcos_loaded',
649 objs_loaded = objs_loaded' }
653 maybeUnload :: [Linkable] -> Linkable -> IO Bool
654 maybeUnload keep_linkables lnk
655 | linkableInSet lnk linkables = return True
657 = do mapM_ unloadObj [f | DotO f <- linkableUnlinked lnk]
658 -- The components of a BCO linkable may contain
659 -- dot-o files. Which is very confusing.
661 -- But the BCO parts can be unlinked just by
662 -- letting go of them (plus of course depopulating
663 -- the symbol table which is done in the main body)
668 %************************************************************************
672 %************************************************************************
677 = Object FilePath -- Full path name of a .o file, including trailing .o
678 -- For dynamic objects only, try to find the object
679 -- file in all the directories specified in
680 -- v_Library_paths before giving up.
682 | DLL String -- "Unadorned" name of a .DLL/.so
683 -- e.g. On unix "qt" denotes "libqt.so"
684 -- On WinDoze "burble" denotes "burble.DLL"
685 -- loadDLL is platform-specific and adds the lib/.so/.DLL
686 -- suffixes platform-dependently
688 | DLLPath FilePath -- Absolute or relative pathname to a dynamic library
689 -- (ends with .dll or .so).
691 | Framework String -- Only used for darwin, but does no harm
693 -- If this package is already part of the GHCi binary, we'll already
694 -- have the right DLLs for this package loaded, so don't try to
697 -- But on Win32 we must load them 'again'; doing so is a harmless no-op
698 -- as far as the loader is concerned, but it does initialise the list
699 -- of DLL handles that rts/Linker.c maintains, and that in turn is
700 -- used by lookupSymbol. So we must call addDLL for each library
701 -- just to get the DLL handle into the list.
703 # if defined(mingw32_TARGET_OS) || defined(darwin_TARGET_OS)
706 = [ "base", "haskell98", "template-haskell", "readline" ]
709 showLS (Object nm) = "(static) " ++ nm
710 showLS (DLL nm) = "(dynamic) " ++ nm
711 showLS (DLLPath nm) = "(dynamic) " ++ nm
712 showLS (Framework nm) = "(framework) " ++ nm
714 linkPackages :: DynFlags -> [PackageId] -> IO ()
715 -- Link exactly the specified packages, and their dependents
716 -- (unless of course they are already linked)
717 -- The dependents are linked automatically, and it doesn't matter
718 -- what order you specify the input packages.
720 -- NOTE: in fact, since each module tracks all the packages it depends on,
721 -- we don't really need to use the package-config dependencies.
722 -- However we do need the package-config stuff (to find aux libs etc),
723 -- and following them lets us load libraries in the right order, which
724 -- perhaps makes the error message a bit more localised if we get a link
725 -- failure. So the dependency walking code is still here.
727 linkPackages dflags new_pkgs
728 = do { pls <- readIORef v_PersistentLinkerState
729 ; let pkg_map = pkgIdMap (pkgState dflags)
731 ; pkgs' <- link pkg_map (pkgs_loaded pls) new_pkgs
733 ; writeIORef v_PersistentLinkerState (pls { pkgs_loaded = pkgs' })
736 link :: PackageConfigMap -> [PackageId] -> [PackageId] -> IO [PackageId]
737 link pkg_map pkgs new_pkgs
738 = foldM (link_one pkg_map) pkgs new_pkgs
740 link_one pkg_map pkgs new_pkg
741 | new_pkg `elem` pkgs -- Already linked
744 | Just pkg_cfg <- lookupPackage pkg_map new_pkg
745 = do { -- Link dependents first
746 pkgs' <- link pkg_map pkgs (map mkPackageId (depends pkg_cfg))
747 -- Now link the package itself
748 ; linkPackage dflags pkg_cfg
749 ; return (new_pkg : pkgs') }
752 = throwDyn (CmdLineError ("unknown package: " ++ packageIdString new_pkg))
755 linkPackage :: DynFlags -> PackageConfig -> IO ()
756 linkPackage dflags pkg
758 let dirs = Packages.libraryDirs pkg
759 let libs = Packages.hsLibraries pkg ++ Packages.extraLibraries pkg
760 ++ [ lib | '-':'l':lib <- Packages.ldOptions pkg ]
761 classifieds <- mapM (locateOneObj dirs) libs
763 -- Complication: all the .so's must be loaded before any of the .o's.
764 let dlls = [ dll | DLL dll <- classifieds ]
765 objs = [ obj | Object obj <- classifieds ]
767 maybePutStr dflags ("Loading package " ++ showPackageId (package pkg) ++ " ... ")
769 -- See comments with partOfGHCi
770 when (pkgName (package pkg) `notElem` partOfGHCi) $ do
772 -- When a library A needs symbols from a library B, the order in
773 -- extra_libraries/extra_ld_opts is "-lA -lB", because that's the
774 -- way ld expects it for static linking. Dynamic linking is a
775 -- different story: When A has no dependency information for B,
776 -- dlopen-ing A with RTLD_NOW (see addDLL in Linker.c) will fail
777 -- when B has not been loaded before. In a nutshell: Reverse the
778 -- order of DLLs for dynamic linking.
779 -- This fixes a problem with the HOpenGL package (see "Compiling
780 -- HOpenGL under recent versions of GHC" on the HOpenGL list).
781 mapM_ (load_dyn dirs) (reverse dlls)
783 -- After loading all the DLLs, we can load the static objects.
784 -- Ordering isn't important here, because we do one final link
785 -- step to resolve everything.
788 maybePutStr dflags "linking ... "
790 if succeeded ok then maybePutStrLn dflags "done."
791 else throwDyn (InstallationError ("unable to load package `" ++ showPackageId (package pkg) ++ "'"))
793 load_dyn dirs dll = do r <- loadDynamic dirs dll
796 Just err -> throwDyn (CmdLineError ("can't load .so/.DLL for: "
797 ++ dll ++ " (" ++ err ++ ")" ))
798 #ifndef darwin_TARGET_OS
799 loadFrameworks pkg = return ()
801 loadFrameworks pkg = mapM_ load frameworks
803 fw_dirs = Packages.frameworkDirs pkg
804 frameworks = Packages.frameworks pkg
806 load fw = do r <- loadFramework fw_dirs fw
809 Just err -> throwDyn (CmdLineError ("can't load framework: "
810 ++ fw ++ " (" ++ err ++ ")" ))
813 -- Try to find an object file for a given library in the given paths.
814 -- If it isn't present, we assume it's a dynamic library.
815 locateOneObj :: [FilePath] -> String -> IO LibrarySpec
816 locateOneObj dirs lib
817 = do { mb_obj_path <- findFile mk_obj_path dirs
818 ; case mb_obj_path of
819 Just obj_path -> return (Object obj_path)
821 do { mb_lib_path <- findFile mk_dyn_lib_path dirs
822 ; case mb_lib_path of
823 Just lib_path -> return (DLL (lib ++ "_dyn"))
824 Nothing -> return (DLL lib) }} -- We assume
826 mk_obj_path dir = dir `joinFileName` (lib `joinFileExt` "o")
827 mk_dyn_lib_path dir = dir `joinFileName` mkSOName (lib ++ "_dyn")
830 -- ----------------------------------------------------------------------------
831 -- Loading a dyanmic library (dlopen()-ish on Unix, LoadLibrary-ish on Win32)
833 -- return Nothing == success, else Just error message from dlopen
834 loadDynamic paths rootname
835 = do { mb_dll <- findFile mk_dll_path paths
837 Just dll -> loadDLL dll
838 Nothing -> loadDLL (mkSOName rootname) }
839 -- Tried all our known library paths, so let
840 -- dlopen() search its own builtin paths now.
842 mk_dll_path dir = dir `joinFileName` mkSOName rootname
844 #if defined(darwin_TARGET_OS)
845 mkSOName root = ("lib" ++ root) `joinFileExt` "dylib"
846 #elif defined(mingw32_TARGET_OS)
847 -- Win32 DLLs have no .dll extension here, because addDLL tries
848 -- both foo.dll and foo.drv
851 mkSOName root = ("lib" ++ root) `joinFileExt` "so"
854 -- Darwin / MacOS X only: load a framework
855 -- a framework is a dynamic library packaged inside a directory of the same
856 -- name. They are searched for in different paths than normal libraries.
857 #ifdef darwin_TARGET_OS
858 loadFramework extraPaths rootname
859 = do { mb_fwk <- findFile mk_fwk (extraPaths ++ defaultFrameworkPaths)
861 Just fwk_path -> loadDLL fwk_path
862 Nothing -> return (Just "not found") }
863 -- Tried all our known library paths, but dlopen()
864 -- has no built-in paths for frameworks: give up
866 mk_fwk dir = dir `joinFileName` (rootname ++ ".framework/" ++ rootname)
867 -- sorry for the hardcoded paths, I hope they won't change anytime soon:
868 defaultFrameworkPaths = ["/Library/Frameworks", "/System/Library/Frameworks"]
872 %************************************************************************
876 %************************************************************************
879 findFile :: (FilePath -> FilePath) -- Maps a directory path to a file path
880 -> [FilePath] -- Directories to look in
881 -> IO (Maybe FilePath) -- The first file path to match
882 findFile mk_file_path []
884 findFile mk_file_path (dir:dirs)
885 = do { let file_path = mk_file_path dir
886 ; b <- doesFileExist file_path
888 return (Just file_path)
890 findFile mk_file_path dirs }
894 maybePutStr dflags s | verbosity dflags > 0 = putStr s
895 | otherwise = return ()
897 maybePutStrLn dflags s | verbosity dflags > 0 = putStrLn s
898 | otherwise = return ()