2 % (c) The University of Glasgow 2000
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, initDynLinker, showLinkerState,
19 linkExpr, unload, extendLinkEnv,
23 #include "../includes/config.h"
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 DriverState ( v_Library_paths, v_Opt_l, v_Ld_inputs, getStaticOpts, v_ExplicitPackages )
33 #ifdef darwin_TARGET_OS
34 import DriverState ( v_Cmdline_frameworks, v_Framework_paths )
36 import Finder ( findModule, findLinkable )
38 import Name ( Name, nameModule, isExternalName )
40 import NameSet ( nameSetToList )
42 import FastString ( FastString(..), unpackFS )
43 import ListSetOps ( minusList )
44 import CmdLineOpts ( DynFlags(verbosity), getDynFlags )
45 import BasicTypes ( SuccessFlag(..), succeeded, failed )
47 import Panic ( GhcException(..) )
48 import Util ( zipLazy, global )
51 import Control.Monad ( when, filterM, foldM )
53 import Data.IORef ( IORef, readIORef, writeIORef )
54 import Data.List ( partition, nub )
56 import System.IO ( putStr, putStrLn, hPutStrLn, stderr, fixIO )
57 import System.Directory ( doesFileExist )
59 import Control.Exception ( block, throwDyn )
61 #if __GLASGOW_HASKELL__ >= 503
62 import GHC.IOBase ( IO(..) )
64 import PrelIOBase ( IO(..) )
69 %************************************************************************
73 %************************************************************************
75 The persistent linker state *must* match the actual state of the
76 C dynamic linker at all times, so we keep it in a private global variable.
79 The PersistentLinkerState maps Names to actual closures (for
80 interpreted code only), for use during linking.
83 GLOBAL_VAR(v_PersistentLinkerState, panic "Dynamic linker not initialised", PersistentLinkerState)
84 GLOBAL_VAR(v_InitLinkerDone, False, Bool) -- Set True when dynamic linker is initialised
86 data PersistentLinkerState
87 = PersistentLinkerState {
89 -- Current global mapping from Names to their true values
90 closure_env :: ClosureEnv,
92 -- The current global mapping from RdrNames of DataCons to
93 -- info table addresses.
94 -- When a new Unlinked is linked into the running image, or an existing
95 -- module in the image is replaced, the itbl_env must be updated
99 -- The currently loaded interpreted modules (home package)
100 bcos_loaded :: [Linkable],
102 -- And the currently-loaded compiled modules (home package)
103 objs_loaded :: [Linkable],
105 -- The currently-loaded packages; always object code
106 -- Held, as usual, in dependency order; though I am not sure if
107 -- that is really important
108 pkgs_loaded :: [PackageName]
111 emptyPLS :: PersistentLinkerState
112 emptyPLS = PersistentLinkerState { closure_env = emptyNameEnv,
113 itbl_env = emptyNameEnv,
114 pkgs_loaded = init_pkgs_loaded,
118 -- Packages that don't need loading, because the compiler
119 -- shares them with the interpreted program.
121 -- The linker's symbol table is populated with RTS symbols using an
122 -- explicit list. See rts/Linker.c for details.
123 init_pkgs_loaded = [ FSLIT("rts") ]
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 :: [ModuleName] -> NameEnv (Name, a) -> NameEnv (Name, a)
142 filterNameMap mods env
143 = filterNameEnv keep_elt env
145 keep_elt (n,_) = isExternalName n
146 && (moduleName (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 :: 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 }
197 = do { dflags <- getDynFlags
199 -- Initialise the linker state
200 ; writeIORef v_PersistentLinkerState emptyPLS
202 -- (a) initialise the C dynamic linker
205 -- (b) Load packages from the command-line
206 ; expl <- readIORef v_ExplicitPackages
207 ; linkPackages dflags expl
209 -- (c) Link libraries from the command-line
210 ; opt_l <- getStaticOpts v_Opt_l
211 ; let minus_ls = [ lib | '-':'l':lib <- opt_l ]
213 -- (d) Link .o files from the command-line
214 ; lib_paths <- readIORef v_Library_paths
215 ; cmdline_objs <- readIORef v_Ld_inputs
217 -- (e) Link any MacOS frameworks
218 #ifdef darwin_TARGET_OS
219 ; framework_paths <- readIORef v_Framework_paths
220 ; frameworks <- readIORef v_Cmdline_frameworks
222 ; let frameworks = []
223 ; let framework_paths = []
225 -- Finally do (c),(d),(e)
226 ; let cmdline_lib_specs = map Object cmdline_objs
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 preloadLib :: DynFlags -> [String] -> [String] -> LibrarySpec -> IO ()
241 preloadLib dflags lib_paths framework_paths lib_spec
242 = do maybePutStr dflags ("Loading object " ++ showLS lib_spec ++ " ... ")
245 -> do b <- preload_static lib_paths static_ish
246 maybePutStrLn dflags (if b then "done"
250 -> do maybe_errstr <- loadDynamic lib_paths dll_unadorned
252 Nothing -> maybePutStrLn dflags "done"
253 Just mm -> preloadFailed mm lib_paths lib_spec
255 #ifdef darwin_TARGET_OS
257 -> do maybe_errstr <- loadFramework framework_paths framework
259 Nothing -> maybePutStrLn dflags "done"
260 Just mm -> preloadFailed mm framework_paths lib_spec
263 preloadFailed :: String -> [String] -> LibrarySpec -> IO ()
264 preloadFailed sys_errmsg paths spec
265 = do maybePutStr dflags
266 ("failed.\nDynamic linker error message was:\n "
267 ++ sys_errmsg ++ "\nWhilst trying to load: "
268 ++ showLS spec ++ "\nDirectories to search are:\n"
269 ++ unlines (map (" "++) paths) )
272 -- Not interested in the paths in the static case.
273 preload_static paths name
274 = do b <- doesFileExist name
275 if not b then return False
276 else loadObj name >> return True
279 CmdLineError "user specified .o/.so/.DLL could not be loaded."
283 %************************************************************************
285 Link a byte-code expression
287 %************************************************************************
290 linkExpr :: HscEnv -> PersistentCompilerState
291 -> UnlinkedBCO -> IO HValue
293 -- Link a single expression, *including* first linking packages and
294 -- modules that this expression depends on.
296 -- Raises an IO exception if it can't find a compiled version of the
297 -- dependents to link.
299 linkExpr hsc_env pcs root_ul_bco
301 -- Initialise the linker (if it's not been done already)
304 -- Find what packages and linkables are required
305 ; (lnks, pkgs) <- getLinkDeps hpt pit needed_mods
307 -- Link the packages and modules required
308 ; linkPackages dflags pkgs
309 ; ok <- linkModules dflags lnks
314 -- Link the expression itself
315 pls <- readIORef v_PersistentLinkerState
316 ; let ie = itbl_env pls
319 -- Link the necessary packages and linkables
320 ; (_, (root_hval:_)) <- linkSomeBCOs False ie ce [root_ul_bco]
324 pit = eps_PIT (pcs_EPS pcs)
325 hpt = hsc_HPT hsc_env
326 dflags = hsc_dflags hsc_env
327 free_names = nameSetToList (bcoFreeNames root_ul_bco)
329 needed_mods :: [Module]
330 needed_mods = [ nameModule n | n <- free_names, isExternalName n ]
332 dieWith msg = throwDyn (ProgramError (showSDoc msg))
334 getLinkDeps :: HomePackageTable -> PackageIfaceTable
335 -> [Module] -- If you need these
336 -> IO ([Linkable], [PackageName]) -- ... then link these first
337 -- Fails with an IO exception if it can't find enough files
339 getLinkDeps hpt pit mods
340 -- Find all the packages and linkables that a set of modules depends on
341 = do { pls <- readIORef v_PersistentLinkerState ;
343 -- 1. Find the dependent home-pkg-modules/packages from each iface
344 (mods_s, pkgs_s) = unzip (map get_deps mods) ;
346 -- 2. Exclude ones already linked
347 -- Main reason: avoid findModule calls in get_linkable
348 mods_needed = nub (concat mods_s) `minusList` linked_mods ;
349 pkgs_needed = nub (concat pkgs_s) `minusList` pkgs_loaded pls ;
351 linked_mods = map linkableModName (objs_loaded pls ++ bcos_loaded pls)
354 -- 3. For each dependent module, find its linkable
355 -- This will either be in the HPT or (in the case of one-shot
356 -- compilation) we may need to use maybe_getFileLinkable
357 lnks_needed <- mapM get_linkable mods_needed ;
359 return (lnks_needed, pkgs_needed) }
361 get_deps :: Module -> ([ModuleName],[PackageName])
362 -- Get the things needed for the specified module
363 -- This is rather similar to the code in RnNames.importsFromImportDecl
365 | isHomeModule (mi_module iface)
366 = (moduleName mod : [m | (m,_) <- dep_mods deps], dep_pkgs deps)
368 = ([], mi_package iface : dep_pkgs deps)
370 iface = get_iface mod
373 get_iface mod = case lookupIface hpt pit mod of
375 Nothing -> pprPanic "getLinkDeps" (no_iface mod)
376 no_iface mod = ptext SLIT("No iface for") <+> ppr mod
377 -- This one is a GHC bug
379 no_obj mod = dieWith (ptext SLIT("No compiled code for") <+> ppr mod)
380 -- This one is a build-system bug
382 get_linkable mod_name -- A home-package module
383 | Just mod_info <- lookupModuleEnvByName hpt mod_name
384 = return (hm_linkable mod_info)
386 = -- It's not in the HPT because we are in one shot mode,
387 -- so use the Finder to get a ModLocation...
388 do { mb_stuff <- findModule mod_name ;
390 Left _ -> no_obj mod_name ;
391 Right (_, loc) -> do {
393 -- ...and then find the linkable for it
394 mb_lnk <- findLinkable mod_name loc ;
396 Nothing -> no_obj mod_name ;
397 Just lnk -> return lnk
402 %************************************************************************
405 The linkables may consist of a mixture of
406 byte-code modules and object modules
408 %************************************************************************
411 linkModules :: DynFlags -> [Linkable] -> IO SuccessFlag
412 linkModules dflags linkables
413 = block $ do -- don't want to be interrupted by ^C in here
415 let (objs, bcos) = partition isObjectLinkable
416 (concatMap partitionLinkable linkables)
418 -- Load objects first; they can't depend on BCOs
419 ok_flag <- dynLinkObjs dflags objs
421 if failed ok_flag then
428 -- HACK to support f-x-dynamic in the interpreter; no other purpose
429 partitionLinkable :: Linkable -> [Linkable]
431 = let li_uls = linkableUnlinked li
432 li_uls_obj = filter isObject li_uls
433 li_uls_bco = filter isInterpretable li_uls
435 case (li_uls_obj, li_uls_bco) of
436 (objs@(_:_), bcos@(_:_))
437 -> [li{linkableUnlinked=li_uls_obj}, li{linkableUnlinked=li_uls_bco}]
441 findModuleLinkable_maybe :: [Linkable] -> ModuleName -> Maybe Linkable
442 findModuleLinkable_maybe lis mod
443 = case [LM time nm us | LM time nm us <- lis, nm == mod] of
446 many -> pprPanic "findModuleLinkable" (ppr mod)
448 filterModuleLinkables :: (ModuleName -> Bool) -> [Linkable] -> [Linkable]
449 filterModuleLinkables p ls = filter (p . linkableModName) ls
451 linkableInSet :: Linkable -> [Linkable] -> Bool
452 linkableInSet l objs_loaded =
453 case findModuleLinkable_maybe objs_loaded (linkableModName l) of
455 Just m -> linkableTime l == linkableTime m
459 %************************************************************************
461 \subsection{The object-code linker}
463 %************************************************************************
466 dynLinkObjs :: DynFlags -> [Linkable] -> IO SuccessFlag
467 -- Side-effects the PersistentLinkerState
469 dynLinkObjs dflags objs
470 = do pls <- readIORef v_PersistentLinkerState
472 -- Load the object files and link them
473 let (objs_loaded', new_objs) = rmDupLinkables (objs_loaded pls) objs
474 pls1 = pls { objs_loaded = objs_loaded' }
475 unlinkeds = concatMap linkableUnlinked new_objs
477 mapM loadObj (map nameOfObject unlinkeds)
479 -- Link the all together
482 -- If resolving failed, unload all our
483 -- object modules and carry on
484 if succeeded ok then do
485 writeIORef v_PersistentLinkerState pls1
488 pls2 <- unload_wkr dflags [] pls1
489 writeIORef v_PersistentLinkerState pls2
493 rmDupLinkables :: [Linkable] -- Already loaded
494 -> [Linkable] -- New linkables
495 -> ([Linkable], -- New loaded set (including new ones)
496 [Linkable]) -- New linkables (excluding dups)
497 rmDupLinkables already ls
500 go already extras [] = (already, extras)
501 go already extras (l:ls)
502 | linkableInSet l already = go already extras ls
503 | otherwise = go (l:already) (l:extras) ls
506 %************************************************************************
508 \subsection{The byte-code linker}
510 %************************************************************************
513 dynLinkBCOs :: [Linkable] -> IO ()
514 -- Side-effects the persistent linker state
516 = do pls <- readIORef v_PersistentLinkerState
518 let (bcos_loaded', new_bcos) = rmDupLinkables (bcos_loaded pls) bcos
519 pls1 = pls { bcos_loaded = bcos_loaded' }
520 unlinkeds :: [Unlinked]
521 unlinkeds = concatMap linkableUnlinked new_bcos
523 cbcs :: [CompiledByteCode]
524 cbcs = map byteCodeOfObject unlinkeds
527 ul_bcos = [b | ByteCode bs _ <- cbcs, b <- bs]
528 ies = [ie | ByteCode _ ie <- cbcs]
529 gce = closure_env pls
530 final_ie = foldr plusNameEnv (itbl_env pls) ies
532 (final_gce, linked_bcos) <- linkSomeBCOs True final_ie gce ul_bcos
533 -- What happens to these linked_bcos?
535 let pls2 = pls1 { closure_env = final_gce,
536 itbl_env = final_ie }
538 writeIORef v_PersistentLinkerState pls2
541 -- Link a bunch of BCOs and return them + updated closure env.
542 linkSomeBCOs :: Bool -- False <=> add _all_ BCOs to returned closure env
543 -- True <=> add only toplevel BCOs to closure env
547 -> IO (ClosureEnv, [HValue])
548 -- The returned HValues are associated 1-1 with
549 -- the incoming unlinked BCOs. Each gives the
550 -- value of the corresponding unlinked BCO
553 linkSomeBCOs toplevs_only ie ce_in ul_bcos
554 = do let nms = map unlinkedBCOName ul_bcos
556 ( \ hvs -> let ce_out = extendClosureEnv ce_in (zipLazy nms hvs)
557 in mapM (linkBCO ie ce_out) ul_bcos )
559 let ce_all_additions = zip nms hvals
560 ce_top_additions = filter (isExternalName.fst) ce_all_additions
561 ce_additions = if toplevs_only then ce_top_additions
562 else ce_all_additions
563 ce_out = -- make sure we're not inserting duplicate names into the
564 -- closure environment, which leads to trouble.
565 ASSERT (all (not . (`elemNameEnv` ce_in)) (map fst ce_additions))
566 extendClosureEnv ce_in ce_additions
567 return (ce_out, hvals)
572 %************************************************************************
574 Unload some object modules
576 %************************************************************************
579 -- ---------------------------------------------------------------------------
580 -- Unloading old objects ready for a new compilation sweep.
582 -- The compilation manager provides us with a list of linkables that it
583 -- considers "stable", i.e. won't be recompiled this time around. For
584 -- each of the modules current linked in memory,
586 -- * if the linkable is stable (and it's the same one - the
587 -- user may have recompiled the module on the side), we keep it,
589 -- * otherwise, we unload it.
591 -- * we also implicitly unload all temporary bindings at this point.
593 unload :: DynFlags -> [Linkable] -> IO ()
594 -- The 'linkables' are the ones to *keep*
596 unload dflags linkables
597 = block $ do -- block, so we're safe from Ctrl-C in here
599 pls <- readIORef v_PersistentLinkerState
600 new_pls <- unload_wkr dflags linkables pls
601 writeIORef v_PersistentLinkerState new_pls
603 let verb = verbosity dflags
604 when (verb >= 3) $ do
605 hPutStrLn stderr (showSDoc
606 (text "unload: retaining objs" <+> ppr (objs_loaded new_pls)))
607 hPutStrLn stderr (showSDoc
608 (text "unload: retaining bcos" <+> ppr (bcos_loaded new_pls)))
612 unload_wkr :: DynFlags
613 -> [Linkable] -- stable linkables
614 -> PersistentLinkerState
615 -> IO PersistentLinkerState
616 -- Does the core unload business
617 -- (the wrapper blocks exceptions and deals with the PLS get and put)
619 unload_wkr dflags linkables pls
620 = do let (objs_to_keep, bcos_to_keep) = partition isObjectLinkable linkables
622 objs_loaded' <- filterM (maybeUnload objs_to_keep) (objs_loaded pls)
623 bcos_loaded' <- filterM (maybeUnload bcos_to_keep) (bcos_loaded pls)
625 let objs_retained = map linkableModName objs_loaded'
626 bcos_retained = map linkableModName bcos_loaded'
627 itbl_env' = filterNameMap bcos_retained (itbl_env pls)
628 closure_env' = filterNameMap bcos_retained (closure_env pls)
629 new_pls = pls { itbl_env = itbl_env',
630 closure_env = closure_env',
631 bcos_loaded = bcos_loaded',
632 objs_loaded = objs_loaded' }
636 maybeUnload :: [Linkable] -> Linkable -> IO Bool
637 maybeUnload keep_linkables lnk
638 | linkableInSet lnk linkables = return True
640 = do mapM_ unloadObj [f | DotO f <- linkableUnlinked lnk]
641 -- The components of a BCO linkable may contain
642 -- dot-o files. Which is very confusing.
644 -- But the BCO parts can be unlinked just by
645 -- letting go of them (plus of course depopulating
646 -- the symbol table which is done in the main body)
651 %************************************************************************
655 %************************************************************************
660 = Object FilePath -- Full path name of a .o file, including trailing .o
661 -- For dynamic objects only, try to find the object
662 -- file in all the directories specified in
663 -- v_Library_paths before giving up.
665 | DLL String -- "Unadorned" name of a .DLL/.so
666 -- e.g. On unix "qt" denotes "libqt.so"
667 -- On WinDoze "burble" denotes "burble.DLL"
668 -- loadDLL is platform-specific and adds the lib/.so/.DLL
669 -- suffixes platform-dependently
671 | Framework String -- Only used for darwin, but does no harm
673 -- If this package is already part of the GHCi binary, we'll already
674 -- have the right DLLs for this package loaded, so don't try to
677 -- But on Win32 we must load them 'again'; doing so is a harmless no-op
678 -- as far as the loader is concerned, but it does initialise the list
679 -- of DLL handles that rts/Linker.c maintains, and that in turn is
680 -- used by lookupSymbol. So we must call addDLL for each library
681 -- just to get the DLL handle into the list.
683 # if defined(mingw32_TARGET_OS) || defined(darwin_TARGET_OS)
686 = [ "base", "haskell98", "haskell-src", "readline" ]
689 showLS (Object nm) = "(static) " ++ nm
690 showLS (DLL nm) = "(dynamic) " ++ nm
691 showLS (Framework nm) = "(framework) " ++ nm
693 linkPackages :: DynFlags -> [PackageName] -> IO ()
694 -- Link exactly the specified packages, and their dependents
695 -- (unless of course they are already linked)
696 -- The dependents are linked automatically, and it doesn't matter
697 -- what order you specify the input packages.
699 -- NOTE: in fact, since each module tracks all the packages it depends on,
700 -- we don't really need to use the package-config dependencies.
701 -- However we do need the package-config stuff (to find aux libs etc),
702 -- and following them lets us load libraries in the right order, which
703 -- perhaps makes the error message a bit more localised if we get a link
704 -- failure. So the dependency walking code is still here.
706 linkPackages dflags new_pkgs
707 = do { pls <- readIORef v_PersistentLinkerState
708 ; pkg_map <- getPackageConfigMap
710 ; pkgs' <- link pkg_map (pkgs_loaded pls) new_pkgs
712 ; writeIORef v_PersistentLinkerState (pls { pkgs_loaded = pkgs' })
715 link :: PackageConfigMap -> [PackageName] -> [PackageName] -> IO [PackageName]
716 link pkg_map pkgs new_pkgs
717 = foldM (link_one pkg_map) pkgs new_pkgs
719 link_one pkg_map pkgs new_pkg
720 | new_pkg `elem` pkgs -- Already linked
723 | Just pkg_cfg <- lookupPkg pkg_map new_pkg
724 = do { -- Link dependents first
725 pkgs' <- link pkg_map pkgs (packageDependents pkg_cfg)
726 -- Now link the package itself
727 ; linkPackage dflags pkg_cfg
728 ; return (new_pkg : pkgs') }
731 = throwDyn (CmdLineError ("unknown package name: " ++ packageNameString new_pkg))
734 linkPackage :: DynFlags -> PackageConfig -> IO ()
735 linkPackage dflags pkg
737 let dirs = Packages.library_dirs pkg
738 let libs = Packages.hs_libraries pkg ++ extra_libraries pkg
739 ++ [ lib | '-':'l':lib <- extra_ld_opts pkg ]
740 classifieds <- mapM (locateOneObj dirs) libs
742 -- Complication: all the .so's must be loaded before any of the .o's.
743 let dlls = [ dll | DLL dll <- classifieds ]
744 objs = [ obj | Object obj <- classifieds ]
746 maybePutStr dflags ("Loading package " ++ Packages.name pkg ++ " ... ")
748 -- See comments with partOfGHCi
749 when (Packages.name pkg `notElem` partOfGHCi) $ do
751 mapM_ (load_dyn dirs) dlls
753 -- After loading all the DLLs, we can load the static objects.
756 maybePutStr dflags "linking ... "
758 if succeeded ok then maybePutStrLn dflags "done."
759 else panic ("can't load package `" ++ name pkg ++ "'")
761 load_dyn dirs dll = do r <- loadDynamic dirs dll
764 Just err -> throwDyn (CmdLineError ("can't load .so/.DLL for: "
765 ++ dll ++ " (" ++ err ++ ")" ))
766 #ifndef darwin_TARGET_OS
767 loadFrameworks pkg = return ()
769 loadFrameworks pkg = mapM_ load frameworks
771 fw_dirs = Packages.framework_dirs pkg
772 frameworks = Packages.extra_frameworks pkg
774 load fw = do r <- loadFramework fw_dirs fw
777 Just err -> throwDyn (CmdLineError ("can't load framework: "
778 ++ fw ++ " (" ++ err ++ ")" ))
781 -- Try to find an object file for a given library in the given paths.
782 -- If it isn't present, we assume it's a dynamic library.
783 locateOneObj :: [FilePath] -> String -> IO LibrarySpec
784 locateOneObj dirs lib
785 = do { mb_obj_path <- findFile mk_obj_path dirs
786 ; case mb_obj_path of
787 Just obj_path -> return (Object obj_path)
788 Nothing -> return (DLL lib) } -- We assume
790 mk_obj_path dir = dir ++ '/':lib ++ ".o"
793 -- ----------------------------------------------------------------------------
794 -- Loading a dyanmic library (dlopen()-ish on Unix, LoadLibrary-ish on Win32)
796 -- return Nothing == success, else Just error message from dlopen
797 loadDynamic paths rootname
798 = do { mb_dll <- findFile mk_dll_path paths
800 Just dll -> loadDLL dll
801 Nothing -> loadDLL (mkSOName rootname) }
802 -- Tried all our known library paths, so let
803 -- dlopen() search its own builtin paths now.
805 mk_dll_path dir = dir ++ '/':mkSOName rootname
807 #if defined(darwin_TARGET_OS)
808 mkSOName root = "lib" ++ root ++ ".dylib"
809 #elif defined(mingw32_TARGET_OS)
810 -- Win32 DLLs have no .dll extension here, because addDLL tries
811 -- both foo.dll and foo.drv
814 mkSOName root = "lib" ++ root ++ ".so"
817 -- Darwin / MacOS X only: load a framework
818 -- a framework is a dynamic library packaged inside a directory of the same
819 -- name. They are searched for in different paths than normal libraries.
820 #ifdef darwin_TARGET_OS
821 loadFramework extraPaths rootname
822 = do { mb_fwk <- findFile mk_fwk (extraPaths ++ defaultFrameworkPaths)
824 Just fwk_path -> loadDLL fwk_path
825 Nothing -> return (Just "not found") }
826 -- Tried all our known library paths, but dlopen()
827 -- has no built-in paths for frameworks: give up
829 mk_fwk dir = dir ++ '/' : rootname ++ ".framework/" ++ rootname
830 -- sorry for the hardcoded paths, I hope they won't change anytime soon:
831 defaultFrameworkPaths = ["/Library/Frameworks", "/System/Library/Frameworks"]
835 %************************************************************************
839 %************************************************************************
842 findFile :: (FilePath -> FilePath) -- Maps a directory path to a file path
843 -> [FilePath] -- Directories to look in
844 -> IO (Maybe FilePath) -- The first file path to match
845 findFile mk_file_path []
847 findFile mk_file_path (dir:dirs)
848 = do { let file_path = mk_file_path dir
849 ; b <- doesFileExist file_path
851 return (Just file_path)
853 findFile mk_file_path dirs }
857 maybePutStr dflags s | verbosity dflags > 0 = putStr s
858 | otherwise = return ()
860 maybePutStrLn dflags s | verbosity dflags > 0 = putStrLn s
861 | otherwise = return ()