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 #-}
18 module Linker ( HValue, initLinker, showLinkerState,
19 linkLibraries, linkExpr,
20 unload, extendLinkEnv,
24 #include "../includes/config.h"
25 #include "HsVersions.h"
27 import ObjLink ( loadDLL, loadObj, unloadObj, resolveObjs, initLinker )
28 import ByteCodeLink ( HValue, ClosureEnv, extendClosureEnv, linkBCO )
29 import ByteCodeItbls ( ItblEnv )
30 import ByteCodeAsm ( CompiledByteCode(..), bcosFreeNames,
31 UnlinkedBCO, UnlinkedBCOExpr, nameOfUnlinkedBCO )
33 import Packages ( PackageConfig(..), PackageName, PackageConfigMap, lookupPkg,
34 packageDependents, packageNameString )
35 import DriverState ( v_Library_paths, v_Cmdline_libraries, getPackageConfigMap )
36 import Finder ( findModule, findLinkable )
37 import HscTypes ( Linkable(..), isObjectLinkable, nameOfObject, byteCodeOfObject,
38 Unlinked(..), isInterpretable, isObject, Dependencies(..),
39 HscEnv(..), PersistentCompilerState(..), ExternalPackageState(..),
40 HomePackageTable, PackageIfaceTable, ModIface(..), HomeModInfo(..),
42 import Name ( Name, nameModule, isExternalName )
44 import NameSet ( nameSetToList )
45 import Module ( ModLocation(..), Module, ModuleName, isHomeModule, moduleName, lookupModuleEnvByName )
46 import FastString ( FastString(..), unpackFS )
47 import ListSetOps ( minusList )
48 import CmdLineOpts ( DynFlags(verbosity) )
49 import BasicTypes ( SuccessFlag(..), succeeded, failed )
51 import Panic ( GhcException(..) )
52 import Util ( zipLazy, global )
53 import ErrUtils ( Message )
56 import Control.Monad ( when, filterM, foldM )
58 import Data.IORef ( IORef, readIORef, writeIORef )
59 import Data.List ( partition, nub )
61 import System.IO ( putStr, putStrLn, hPutStrLn, stderr, fixIO )
62 import System.Directory ( doesFileExist, getModificationTime )
64 import Control.Exception ( block, throwDyn )
66 #if __GLASGOW_HASKELL__ >= 503
67 import GHC.IOBase ( IO(..) )
69 import PrelIOBase ( IO(..) )
74 %************************************************************************
78 %************************************************************************
80 The persistent linker state *must* match the actual state of the
81 C dynamic linker at all times, so we keep it in a private global variable.
84 The PersistentLinkerState maps Names to actual closures (for
85 interpreted code only), for use during linking.
88 GLOBAL_VAR(v_PersistentLinkerState, emptyPLS, PersistentLinkerState)
90 data PersistentLinkerState
91 = PersistentLinkerState {
93 -- Current global mapping from Names to their true values
94 closure_env :: ClosureEnv,
96 -- The current global mapping from RdrNames of DataCons to
97 -- info table addresses.
98 -- When a new Unlinked is linked into the running image, or an existing
99 -- module in the image is replaced, the itbl_env must be updated
103 -- The currently loaded interpreted modules (home package)
104 bcos_loaded :: [Linkable],
106 -- And the currently-loaded compiled modules (home package)
107 objs_loaded :: [Linkable],
109 -- The currently-loaded packages; always object code
110 -- Held, as usual, in dependency order; though I am not sure if
111 -- that is really important
112 pkgs_loaded :: [PackageName]
115 emptyPLS :: PersistentLinkerState
116 emptyPLS = PersistentLinkerState { closure_env = emptyNameEnv,
117 itbl_env = emptyNameEnv,
118 pkgs_loaded = init_pkgs_loaded,
122 -- Packages that don't need loading, because the compiler
123 -- shares them with the interpreted program.
124 init_pkgs_loaded = [ FSLIT("rts") ]
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 :: [ModuleName] -> NameEnv (Name, a) -> NameEnv (Name, a)
143 filterNameMap mods env
144 = filterNameEnv keep_elt env
146 keep_elt (n,_) = isExternalName n
147 && (moduleName (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)])
164 %************************************************************************
166 Link a byte-code expression
168 %************************************************************************
171 linkExpr :: HscEnv -> PersistentCompilerState
172 -> UnlinkedBCOExpr -> IO HValue -- IO BCO# really
174 -- Link a single expression, *including* first linking packages and
175 -- modules that this expression depends on.
177 -- Raises an IO exception if it can't find a compiled version of the
178 -- dependents to link.
180 linkExpr hsc_env pcs (root_ul_bco, aux_ul_bcos)
182 -- Find what packages and linkables are required
183 (lnks, pkgs) <- getLinkDeps hpt pit needed_mods ;
185 -- Link the packages and modules required
186 linkPackages dflags pkgs
187 ; ok <- linkModules dflags lnks
192 -- Link the expression itself
193 pls <- readIORef v_PersistentLinkerState
194 ; let ie = itbl_env pls
197 -- Link the necessary packages and linkables
198 ; (_, (root_hval:_)) <- linkSomeBCOs False ie ce all_bcos
202 pit = eps_PIT (pcs_EPS pcs)
203 hpt = hsc_HPT hsc_env
204 dflags = hsc_dflags hsc_env
205 all_bcos = root_ul_bco : aux_ul_bcos
206 free_names = nameSetToList (bcosFreeNames all_bcos)
208 needed_mods :: [Module]
209 needed_mods = [ nameModule n | n <- free_names, isExternalName n ]
211 dieWith msg = throwDyn (UsageError (showSDoc msg))
213 getLinkDeps :: HomePackageTable -> PackageIfaceTable
214 -> [Module] -- If you need these
215 -> IO ([Linkable], [PackageName]) -- ... then link these first
216 -- Fails with an IO exception if it can't find enough files
218 getLinkDeps hpt pit mods
219 -- Find all the packages and linkables that a set of modules depends on
220 = do { pls <- readIORef v_PersistentLinkerState ;
222 -- 1. Find the dependent home-pkg-modules/packages from each iface
223 (mods_s, pkgs_s) = unzip (map get_deps mods) ;
225 -- 2. Exclude ones already linked
226 -- Main reason: avoid findModule calls in get_linkable
227 mods_needed = nub (concat mods_s) `minusList` linked_mods ;
228 pkgs_needed = nub (concat pkgs_s) `minusList` pkgs_loaded pls ;
230 linked_mods = map linkableModName (objs_loaded pls ++ bcos_loaded pls)
233 -- 3. For each dependent module, find its linkable
234 -- This will either be in the HPT or (in the case of one-shot compilation)
235 -- we may need to use maybe_getFileLinkable
236 lnks_needed <- mapM get_linkable mods_needed ;
238 return (lnks_needed, pkgs_needed) }
240 get_deps :: Module -> ([ModuleName],[PackageName])
241 -- Get the things needed for the specified module
242 -- This is rather similar to the code in RnNames.importsFromImportDecl
244 | isHomeModule (mi_module iface)
245 = (moduleName mod : [m | (m,_) <- dep_mods deps], dep_pkgs deps)
247 = ([], mi_package iface : dep_pkgs deps)
249 iface = get_iface mod
252 get_iface mod = case lookupIface hpt pit mod of
254 Nothing -> pprPanic "getLinkDeps" (no_iface mod)
255 no_iface mod = ptext SLIT("No iface for") <+> ppr mod
256 -- This one is a GHC bug
258 no_obj mod = dieWith (ptext SLIT("No compiled code for") <+> ppr mod)
259 -- This one is a build-system bug
261 get_linkable mod_name -- A home-package module
262 | Just mod_info <- lookupModuleEnvByName hpt mod_name
263 = return (hm_linkable mod_info)
265 = -- It's not in the HPT because we are in one shot mode,
266 -- so use the Finder to get a ModLocation...
267 do { mb_stuff <- findModule mod_name ;
269 Nothing -> no_obj mod_name ;
270 Just (_, loc) -> do {
272 -- ...and then find the linkable for it
273 mb_lnk <- findLinkable mod_name loc ;
275 Nothing -> no_obj mod_name ;
276 Just lnk -> return lnk
281 %************************************************************************
284 The linkables may consist of a mixture of
285 byte-code modules and object modules
287 %************************************************************************
290 linkModules :: DynFlags -> [Linkable] -> IO SuccessFlag
291 linkModules dflags linkables
292 = block $ do -- don't want to be interrupted by ^C in here
294 let (objs, bcos) = partition isObjectLinkable
295 (concatMap partitionLinkable linkables)
297 -- Load objects first; they can't depend on BCOs
298 ok_flag <- dynLinkObjs dflags objs
300 if failed ok_flag then
307 -- HACK to support f-x-dynamic in the interpreter; no other purpose
308 partitionLinkable :: Linkable -> [Linkable]
310 = let li_uls = linkableUnlinked li
311 li_uls_obj = filter isObject li_uls
312 li_uls_bco = filter isInterpretable li_uls
314 case (li_uls_obj, li_uls_bco) of
315 (objs@(_:_), bcos@(_:_))
316 -> [li{linkableUnlinked=li_uls_obj}, li{linkableUnlinked=li_uls_bco}]
320 findModuleLinkable_maybe :: [Linkable] -> ModuleName -> Maybe Linkable
321 findModuleLinkable_maybe lis mod
322 = case [LM time nm us | LM time nm us <- lis, nm == mod] of
325 many -> pprPanic "findModuleLinkable" (ppr mod)
327 filterModuleLinkables :: (ModuleName -> Bool) -> [Linkable] -> [Linkable]
328 filterModuleLinkables p ls = filter (p . linkableModName) ls
330 linkableInSet :: Linkable -> [Linkable] -> Bool
331 linkableInSet l objs_loaded =
332 case findModuleLinkable_maybe objs_loaded (linkableModName l) of
334 Just m -> linkableTime l == linkableTime m
338 %************************************************************************
340 \subsection{The object-code linker}
342 %************************************************************************
345 dynLinkObjs :: DynFlags -> [Linkable] -> IO SuccessFlag
346 -- Side-effects the PersistentLinkerState
348 dynLinkObjs dflags objs
349 = do pls <- readIORef v_PersistentLinkerState
351 -- Load the object files and link them
352 let (objs_loaded', new_objs) = rmDupLinkables (objs_loaded pls) objs
353 pls1 = pls { objs_loaded = objs_loaded' }
354 unlinkeds = concatMap linkableUnlinked new_objs
356 mapM loadObj (map nameOfObject unlinkeds)
358 -- Link the all together
361 -- If resolving failed, unload all our
362 -- object modules and carry on
363 if succeeded ok then do
364 writeIORef v_PersistentLinkerState pls1
367 pls2 <- unload_wkr dflags [] pls1
368 writeIORef v_PersistentLinkerState pls2
372 rmDupLinkables :: [Linkable] -- Already loaded
373 -> [Linkable] -- New linkables
374 -> ([Linkable], -- New loaded set (including new ones)
375 [Linkable]) -- New linkables (excluding dups)
376 rmDupLinkables already ls
379 go already extras [] = (already, extras)
380 go already extras (l:ls)
381 | linkableInSet l already = go already extras ls
382 | otherwise = go (l:already) (l:extras) ls
387 linkLibraries :: DynFlags
388 -> [String] -- foo.o files specified on command line
390 -- Used just at initialisation time to link in libraries
391 -- specified on the command line.
392 linkLibraries dflags objs
393 = do { lib_paths <- readIORef v_Library_paths
394 ; minus_ls <- readIORef v_Cmdline_libraries
395 ; let cmdline_lib_specs = map Object objs ++ map DLL minus_ls
397 ; if (null cmdline_lib_specs) then return ()
401 ; mapM_ (preloadLib dflags lib_paths) cmdline_lib_specs
403 ; maybePutStr dflags "final link ... "
405 ; if succeeded ok then maybePutStrLn dflags "done."
406 else throwDyn (InstallationError "linking extra libraries/objects failed")
409 preloadLib :: DynFlags -> [String] -> LibrarySpec -> IO ()
410 preloadLib dflags lib_paths lib_spec
411 = do maybePutStr dflags ("Loading object " ++ showLS lib_spec ++ " ... ")
414 -> do b <- preload_static lib_paths static_ish
415 maybePutStrLn dflags (if b then "done."
418 -> do maybe_errstr <- loadDynamic lib_paths dll_unadorned
421 Just mm -> preloadFailed mm lib_paths lib_spec
422 maybePutStrLn dflags "done"
424 preloadFailed :: String -> [String] -> LibrarySpec -> IO ()
425 preloadFailed sys_errmsg paths spec
426 = do maybePutStr dflags
427 ("failed.\nDynamic linker error message was:\n "
428 ++ sys_errmsg ++ "\nWhilst trying to load: "
429 ++ showLS spec ++ "\nDirectories to search are:\n"
430 ++ unlines (map (" "++) paths) )
433 -- not interested in the paths in the static case.
434 preload_static paths name
435 = do b <- doesFileExist name
436 if not b then return False
437 else loadObj name >> return True
440 = (throwDyn . CmdLineError)
441 "user specified .o/.so/.DLL could not be loaded."
445 %************************************************************************
447 \subsection{The byte-code linker}
449 %************************************************************************
452 dynLinkBCOs :: [Linkable] -> IO ()
453 -- Side-effects the persistent linker state
455 = do pls <- readIORef v_PersistentLinkerState
457 let (bcos_loaded', new_bcos) = rmDupLinkables (bcos_loaded pls) bcos
458 pls1 = pls { bcos_loaded = bcos_loaded' }
459 unlinkeds :: [Unlinked]
460 unlinkeds = concatMap linkableUnlinked new_bcos
462 cbcs :: [CompiledByteCode]
463 cbcs = map byteCodeOfObject unlinkeds
466 ul_bcos = [b | ByteCode bs _ <- cbcs, b <- bs]
467 ies = [ie | ByteCode _ ie <- cbcs]
468 gce = closure_env pls
469 final_ie = foldr plusNameEnv (itbl_env pls) ies
471 (final_gce, linked_bcos) <- linkSomeBCOs True final_ie gce ul_bcos
472 -- What happens to these linked_bcos?
474 let pls2 = pls1 { closure_env = final_gce,
475 itbl_env = final_ie }
477 writeIORef v_PersistentLinkerState pls2
480 -- Link a bunch of BCOs and return them + updated closure env.
481 linkSomeBCOs :: Bool -- False <=> add _all_ BCOs to returned closure env
482 -- True <=> add only toplevel BCOs to closure env
486 -> IO (ClosureEnv, [HValue])
487 -- The returned HValues are associated 1-1 with
488 -- the incoming unlinked BCOs. Each gives the
489 -- value of the corresponding unlinked BCO
492 linkSomeBCOs toplevs_only ie ce_in ul_bcos
493 = do let nms = map nameOfUnlinkedBCO ul_bcos
495 ( \ hvs -> let ce_out = extendClosureEnv ce_in (zipLazy nms hvs)
496 in mapM (linkBCO ie ce_out) ul_bcos )
498 let ce_all_additions = zip nms hvals
499 ce_top_additions = filter (isExternalName.fst) ce_all_additions
500 ce_additions = if toplevs_only then ce_top_additions
501 else ce_all_additions
502 ce_out = -- make sure we're not inserting duplicate names into the
503 -- closure environment, which leads to trouble.
504 ASSERT (all (not . (`elemNameEnv` ce_in)) (map fst ce_additions))
505 extendClosureEnv ce_in ce_additions
506 return (ce_out, hvals)
511 %************************************************************************
513 Unload some object modules
515 %************************************************************************
518 -- ---------------------------------------------------------------------------
519 -- Unloading old objects ready for a new compilation sweep.
521 -- The compilation manager provides us with a list of linkables that it
522 -- considers "stable", i.e. won't be recompiled this time around. For
523 -- each of the modules current linked in memory,
525 -- * if the linkable is stable (and it's the same one - the
526 -- user may have recompiled the module on the side), we keep it,
528 -- * otherwise, we unload it.
530 -- * we also implicitly unload all temporary bindings at this point.
532 unload :: DynFlags -> [Linkable] -> IO ()
533 -- The 'linkables' are the ones to *keep*
535 unload dflags linkables
536 = block $ do -- block, so we're safe from Ctrl-C in here
538 pls <- readIORef v_PersistentLinkerState
539 new_pls <- unload_wkr dflags linkables pls
540 writeIORef v_PersistentLinkerState new_pls
542 let verb = verbosity dflags
543 when (verb >= 3) $ do
544 hPutStrLn stderr (showSDoc
545 (text "unload: retaining objs" <+> ppr (objs_loaded new_pls)))
546 hPutStrLn stderr (showSDoc
547 (text "unload: retaining bcos" <+> ppr (bcos_loaded new_pls)))
551 unload_wkr :: DynFlags
552 -> [Linkable] -- stable linkables
553 -> PersistentLinkerState
554 -> IO PersistentLinkerState
555 -- Does the core unload business
556 -- (the wrapper blocks exceptions and deals with the PLS get and put)
558 unload_wkr dflags linkables pls
559 = do let (objs_to_keep, bcos_to_keep) = partition isObjectLinkable linkables
561 objs_loaded' <- filterM (maybeUnload objs_to_keep) (objs_loaded pls)
562 bcos_loaded' <- filterM (maybeUnload bcos_to_keep) (bcos_loaded pls)
564 let objs_retained = map linkableModName objs_loaded'
565 bcos_retained = map linkableModName bcos_loaded'
566 itbl_env' = filterNameMap bcos_retained (itbl_env pls)
567 closure_env' = filterNameMap bcos_retained (closure_env pls)
568 new_pls = pls { itbl_env = itbl_env',
569 closure_env = closure_env',
570 bcos_loaded = bcos_loaded',
571 objs_loaded = objs_loaded' }
575 maybeUnload :: [Linkable] -> Linkable -> IO Bool
576 maybeUnload keep_linkables lnk
577 | linkableInSet lnk linkables = return True
579 = do mapM_ unloadObj [f | DotO f <- linkableUnlinked lnk]
580 -- The components of a BCO linkable may contain
581 -- dot-o files. Which is very confusing.
583 -- But the BCO parts can be unlinked just by
584 -- letting go of them (plus of course depopulating
585 -- the symbol table which is done in the main body)
590 %************************************************************************
594 %************************************************************************
599 = Object FilePath -- Full path name of a .o file, including trailing .o
600 -- For dynamic objects only, try to find the object
601 -- file in all the directories specified in
602 -- v_Library_paths before giving up.
604 | DLL String -- "Unadorned" name of a .DLL/.so
605 -- e.g. On unix "qt" denotes "libqt.so"
606 -- On WinDoze "burble" denotes "burble.DLL"
607 -- loadDLL is platform-specific and adds the lib/.so/.DLL
608 -- suffixes platform-dependently
609 #ifdef darwin_TARGET_OS
613 -- If this package is already part of the GHCi binary, we'll already
614 -- have the right DLLs for this package loaded, so don't try to
617 -- But on Win32 we must load them 'again'; doing so is a harmless no-op
618 -- as far as the loader is concerned, but it does initialise the list
619 -- of DLL handles that rts/Linker.c maintains, and that in turn is
620 -- used by lookupSymbol. So we must call addDLL for each library
621 -- just to get the DLL handle into the list.
623 # ifndef mingw32_TARGET_OS
624 = [ "base", "haskell98", "haskell-src", "readline" ]
629 showLS (Object nm) = "(static) " ++ nm
630 showLS (DLL nm) = "(dynamic) " ++ nm
631 #ifdef darwin_TARGET_OS
632 showLS (Framework nm) = "(framework) " ++ nm
635 linkPackages :: DynFlags -> [PackageName] -> IO ()
636 -- Link exactly the specified packages, and their dependents
637 -- (unless of course they are already linked)
638 -- The dependents are linked automatically, and it doesn't matter
639 -- what order you specify the input packages.
641 -- NOTE: in fact, since each module tracks all the packages it depends on,
642 -- we don't really need to use the package-config dependencies.
643 -- However we do need the package-config stuff (to find aux libs etc),
644 -- and following them lets us load libraries in the right order, which
645 -- perhaps makes the error message a bit more localised if we get a link
646 -- failure. So the dependency walking code is still here.
648 linkPackages dflags new_pkgs
649 = do { pls <- readIORef v_PersistentLinkerState
650 ; pkg_map <- getPackageConfigMap
652 ; pkgs' <- link pkg_map (pkgs_loaded pls) new_pkgs
654 ; writeIORef v_PersistentLinkerState (pls { pkgs_loaded = pkgs' })
657 link :: PackageConfigMap -> [PackageName] -> [PackageName] -> IO [PackageName]
658 link pkg_map pkgs new_pkgs
659 = foldM (link_one pkg_map) pkgs new_pkgs
661 link_one pkg_map pkgs new_pkg
662 | new_pkg `elem` pkgs -- Already linked
665 | Just pkg_cfg <- lookupPkg pkg_map new_pkg
666 = do { -- Link dependents first
667 pkgs' <- link pkg_map pkgs (packageDependents pkg_cfg)
668 -- Now link the package itself
669 ; linkPackage dflags pkg_cfg
670 ; return (new_pkg : pkgs') }
673 = throwDyn (CmdLineError ("unknown package name: " ++ packageNameString new_pkg))
676 linkPackage :: DynFlags -> PackageConfig -> IO ()
677 linkPackage dflags pkg
679 let dirs = Packages.library_dirs pkg
680 let libs = Packages.hs_libraries pkg ++ extra_libraries pkg
681 classifieds <- mapM (locateOneObj dirs) libs
682 #ifdef darwin_TARGET_OS
683 let fwDirs = Packages.framework_dirs pkg
684 let frameworks= Packages.extra_frameworks pkg
687 -- Complication: all the .so's must be loaded before any of the .o's.
688 let dlls = [ dll | DLL dll <- classifieds ]
689 objs = [ obj | Object obj <- classifieds ]
691 maybePutStr dflags ("Loading package " ++ Packages.name pkg ++ " ... ")
693 -- See comments with partOfGHCi
694 when (Packages.name pkg `notElem` partOfGHCi) $ do
695 #ifdef darwin_TARGET_OS
696 loadFrameworks fwDirs frameworks
698 loadDynamics dirs dlls
700 -- After loading all the DLLs, we can load the static objects.
703 maybePutStr dflags "linking ... "
705 if succeeded ok then maybePutStrLn dflags "done."
706 else panic ("can't load package `" ++ name pkg ++ "'")
708 loadDynamics dirs [] = return ()
709 loadDynamics dirs (dll:dlls) = do
710 r <- loadDynamic dirs dll
712 Nothing -> loadDynamics dirs dlls
713 Just err -> throwDyn (CmdLineError ("can't load .so/.DLL for: "
714 ++ dll ++ " (" ++ err ++ ")" ))
715 #ifdef darwin_TARGET_OS
716 loadFrameworks dirs [] = return ()
717 loadFrameworks dirs (fw:fws) = do
718 r <- loadFramework dirs fw
720 Nothing -> loadFrameworks dirs fws
721 Just err -> throwDyn (CmdLineError ("can't load framework: "
722 ++ fw ++ " (" ++ err ++ ")" ))
725 -- Try to find an object file for a given library in the given paths.
726 -- If it isn't present, we assume it's a dynamic library.
727 locateOneObj :: [FilePath] -> String -> IO LibrarySpec
728 locateOneObj dirs lib
729 = do { mb_obj_path <- findFile mk_obj_path dirs
730 ; case mb_obj_path of
731 Just obj_path -> return (Object obj_path)
732 Nothing -> return (DLL lib) } -- we assume
734 mk_obj_path dir = dir ++ '/':lib ++ ".o"
737 -- ----------------------------------------------------------------------------
738 -- Loading a dyanmic library (dlopen()-ish on Unix, LoadLibrary-ish on Win32)
740 -- return Nothing == success, else Just error message from dlopen
741 loadDynamic paths rootname
742 = do { mb_dll <- findFile mk_dll_path paths
744 Just dll -> loadDLL dll
745 Nothing -> loadDLL (mkSOName rootname) }
746 -- Tried all our known library paths, so let
747 -- dlopen() search its own builtin paths now.
749 mk_dll_path dir = dir ++ '/':mkSOName rootname
751 #if defined(darwin_TARGET_OS)
752 mkSOName root = "lib" ++ root ++ ".dylib"
753 #elif defined(mingw32_TARGET_OS)
754 -- Win32 DLLs have no .dll extension here, because addDLL tries
755 -- both foo.dll and foo.drv
758 mkSOName root = "lib" ++ root ++ ".so"
761 -- Darwin / MacOS X only: load a framework
762 -- a framework is a dynamic library packaged inside a directory of the same
763 -- name. They are searched for in different paths than normal libraries.
764 #ifdef darwin_TARGET_OS
765 loadFramework extraPaths rootname
766 = do { mb_fwk <- findFile mk_fwk (extraPaths ++ defaultFrameworkPaths)
768 Just fwk_path -> loadDLL fwk_path
769 Nothing -> return (Just "not found") }
770 -- Tried all our known library paths, but dlopen()
771 -- has no built-in paths for frameworks: give up
773 mk_fwk dir = dir ++ '/' : rootname ++ ".framework/" ++ rootname
774 -- sorry for the hardcoded paths, I hope they won't change anytime soon:
775 defaultFrameworkPaths = ["/Library/Frameworks", "/System/Library/Frameworks"]
779 %************************************************************************
783 %************************************************************************
786 findFile :: (FilePath -> FilePath) -- Maps a directory path to a file path
787 -> [FilePath] -- Directories to look in
788 -> IO (Maybe FilePath) -- The first file path to match
789 findFile mk_file_path []
791 findFile mk_file_path (dir:dirs)
792 = do { let file_path = mk_file_path dir
793 ; b <- doesFileExist file_path
795 return (Just file_path)
797 findFile mk_file_path dirs }
801 maybePutStr dflags s | verbosity dflags > 0 = putStr s
802 | otherwise = return ()
804 maybePutStrLn dflags s | verbosity dflags > 0 = putStrLn s
805 | otherwise = return ()