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,
25 #include "../includes/config.h"
26 #include "HsVersions.h"
28 import ObjLink ( loadDLL, loadObj, unloadObj, resolveObjs, initLinker )
29 import ByteCodeLink ( HValue, ClosureEnv, extendClosureEnv, linkBCO )
30 import ByteCodeItbls ( ItblEnv )
31 import ByteCodeAsm ( CompiledByteCode(..), bcoFreeNames, UnlinkedBCO(..))
34 import DriverState ( v_Library_paths, v_Opt_l, getStaticOpts )
35 import Finder ( findModule, findLinkable )
37 import Name ( Name, nameModule, isExternalName )
39 import NameSet ( nameSetToList )
41 import FastString ( FastString(..), unpackFS )
42 import ListSetOps ( minusList )
43 import CmdLineOpts ( DynFlags(verbosity) )
44 import BasicTypes ( SuccessFlag(..), succeeded, failed )
46 import Panic ( GhcException(..) )
47 import Util ( zipLazy, global )
50 import Control.Monad ( when, filterM, foldM )
52 import Data.IORef ( IORef, readIORef, writeIORef )
53 import Data.List ( partition, nub )
55 import System.IO ( putStr, putStrLn, hPutStrLn, stderr, fixIO )
56 import System.Directory ( doesFileExist )
58 import Control.Exception ( block, throwDyn )
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, emptyPLS, PersistentLinkerState)
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 :: [PackageName]
109 emptyPLS :: PersistentLinkerState
110 emptyPLS = PersistentLinkerState { closure_env = emptyNameEnv,
111 itbl_env = emptyNameEnv,
112 pkgs_loaded = init_pkgs_loaded,
116 -- Packages that don't need loading, because the compiler
117 -- shares them with the interpreted program.
118 init_pkgs_loaded = [ FSLIT("rts") ]
122 extendLinkEnv :: [(Name,HValue)] -> IO ()
123 -- Automatically discards shadowed bindings
124 extendLinkEnv new_bindings
125 = do pls <- readIORef v_PersistentLinkerState
126 let new_closure_env = extendClosureEnv (closure_env pls) new_bindings
127 new_pls = pls { closure_env = new_closure_env }
128 writeIORef v_PersistentLinkerState new_pls
130 -- filterNameMap removes from the environment all entries except
131 -- those for a given set of modules;
132 -- Note that this removes all *local* (i.e. non-isExternal) names too
133 -- (these are the temporary bindings from the command line).
134 -- Used to filter both the ClosureEnv and ItblEnv
136 filterNameMap :: [ModuleName] -> NameEnv (Name, a) -> NameEnv (Name, a)
137 filterNameMap mods env
138 = filterNameEnv keep_elt env
140 keep_elt (n,_) = isExternalName n
141 && (moduleName (nameModule n) `elem` mods)
146 showLinkerState :: IO ()
147 -- Display the persistent linker state
149 = do pls <- readIORef v_PersistentLinkerState
150 printDump (vcat [text "----- Linker state -----",
151 text "Pkgs:" <+> ppr (pkgs_loaded pls),
152 text "Objs:" <+> ppr (objs_loaded pls),
153 text "BCOs:" <+> ppr (bcos_loaded pls)])
158 %************************************************************************
160 Link a byte-code expression
162 %************************************************************************
165 linkExpr :: HscEnv -> PersistentCompilerState
166 -> UnlinkedBCO -> IO HValue
168 -- Link a single expression, *including* first linking packages and
169 -- modules that this expression depends on.
171 -- Raises an IO exception if it can't find a compiled version of the
172 -- dependents to link.
174 linkExpr hsc_env pcs root_ul_bco
176 -- Find what packages and linkables are required
177 (lnks, pkgs) <- getLinkDeps hpt pit needed_mods ;
179 -- Link the packages and modules required
180 linkPackages dflags pkgs
181 ; ok <- linkModules dflags lnks
186 -- Link the expression itself
187 pls <- readIORef v_PersistentLinkerState
188 ; let ie = itbl_env pls
191 -- Link the necessary packages and linkables
192 ; (_, (root_hval:_)) <- linkSomeBCOs False ie ce [root_ul_bco]
196 pit = eps_PIT (pcs_EPS pcs)
197 hpt = hsc_HPT hsc_env
198 dflags = hsc_dflags hsc_env
199 free_names = nameSetToList (bcoFreeNames root_ul_bco)
201 needed_mods :: [Module]
202 needed_mods = [ nameModule n | n <- free_names, isExternalName n ]
204 dieWith msg = throwDyn (UsageError (showSDoc msg))
206 getLinkDeps :: HomePackageTable -> PackageIfaceTable
207 -> [Module] -- If you need these
208 -> IO ([Linkable], [PackageName]) -- ... then link these first
209 -- Fails with an IO exception if it can't find enough files
211 getLinkDeps hpt pit mods
212 -- Find all the packages and linkables that a set of modules depends on
213 = do { pls <- readIORef v_PersistentLinkerState ;
215 -- 1. Find the dependent home-pkg-modules/packages from each iface
216 (mods_s, pkgs_s) = unzip (map get_deps mods) ;
218 -- 2. Exclude ones already linked
219 -- Main reason: avoid findModule calls in get_linkable
220 mods_needed = nub (concat mods_s) `minusList` linked_mods ;
221 pkgs_needed = nub (concat pkgs_s) `minusList` pkgs_loaded pls ;
223 linked_mods = map linkableModName (objs_loaded pls ++ bcos_loaded pls)
226 -- 3. For each dependent module, find its linkable
227 -- This will either be in the HPT or (in the case of one-shot
228 -- compilation) we may need to use maybe_getFileLinkable
229 lnks_needed <- mapM get_linkable mods_needed ;
231 return (lnks_needed, pkgs_needed) }
233 get_deps :: Module -> ([ModuleName],[PackageName])
234 -- Get the things needed for the specified module
235 -- This is rather similar to the code in RnNames.importsFromImportDecl
237 | isHomeModule (mi_module iface)
238 = (moduleName mod : [m | (m,_) <- dep_mods deps], dep_pkgs deps)
240 = ([], mi_package iface : dep_pkgs deps)
242 iface = get_iface mod
245 get_iface mod = case lookupIface hpt pit mod of
247 Nothing -> pprPanic "getLinkDeps" (no_iface mod)
248 no_iface mod = ptext SLIT("No iface for") <+> ppr mod
249 -- This one is a GHC bug
251 no_obj mod = dieWith (ptext SLIT("No compiled code for") <+> ppr mod)
252 -- This one is a build-system bug
254 get_linkable mod_name -- A home-package module
255 | Just mod_info <- lookupModuleEnvByName hpt mod_name
256 = return (hm_linkable mod_info)
258 = -- It's not in the HPT because we are in one shot mode,
259 -- so use the Finder to get a ModLocation...
260 do { mb_stuff <- findModule mod_name ;
262 Nothing -> no_obj mod_name ;
263 Just (_, loc) -> do {
265 -- ...and then find the linkable for it
266 mb_lnk <- findLinkable mod_name loc ;
268 Nothing -> no_obj mod_name ;
269 Just lnk -> return lnk
274 %************************************************************************
277 The linkables may consist of a mixture of
278 byte-code modules and object modules
280 %************************************************************************
283 linkModules :: DynFlags -> [Linkable] -> IO SuccessFlag
284 linkModules dflags linkables
285 = block $ do -- don't want to be interrupted by ^C in here
287 let (objs, bcos) = partition isObjectLinkable
288 (concatMap partitionLinkable linkables)
290 -- Load objects first; they can't depend on BCOs
291 ok_flag <- dynLinkObjs dflags objs
293 if failed ok_flag then
300 -- HACK to support f-x-dynamic in the interpreter; no other purpose
301 partitionLinkable :: Linkable -> [Linkable]
303 = let li_uls = linkableUnlinked li
304 li_uls_obj = filter isObject li_uls
305 li_uls_bco = filter isInterpretable li_uls
307 case (li_uls_obj, li_uls_bco) of
308 (objs@(_:_), bcos@(_:_))
309 -> [li{linkableUnlinked=li_uls_obj}, li{linkableUnlinked=li_uls_bco}]
313 findModuleLinkable_maybe :: [Linkable] -> ModuleName -> Maybe Linkable
314 findModuleLinkable_maybe lis mod
315 = case [LM time nm us | LM time nm us <- lis, nm == mod] of
318 many -> pprPanic "findModuleLinkable" (ppr mod)
320 filterModuleLinkables :: (ModuleName -> Bool) -> [Linkable] -> [Linkable]
321 filterModuleLinkables p ls = filter (p . linkableModName) ls
323 linkableInSet :: Linkable -> [Linkable] -> Bool
324 linkableInSet l objs_loaded =
325 case findModuleLinkable_maybe objs_loaded (linkableModName l) of
327 Just m -> linkableTime l == linkableTime m
331 %************************************************************************
333 \subsection{The object-code linker}
335 %************************************************************************
338 dynLinkObjs :: DynFlags -> [Linkable] -> IO SuccessFlag
339 -- Side-effects the PersistentLinkerState
341 dynLinkObjs dflags objs
342 = do pls <- readIORef v_PersistentLinkerState
344 -- Load the object files and link them
345 let (objs_loaded', new_objs) = rmDupLinkables (objs_loaded pls) objs
346 pls1 = pls { objs_loaded = objs_loaded' }
347 unlinkeds = concatMap linkableUnlinked new_objs
349 mapM loadObj (map nameOfObject unlinkeds)
351 -- Link the all together
354 -- If resolving failed, unload all our
355 -- object modules and carry on
356 if succeeded ok then do
357 writeIORef v_PersistentLinkerState pls1
360 pls2 <- unload_wkr dflags [] pls1
361 writeIORef v_PersistentLinkerState pls2
365 rmDupLinkables :: [Linkable] -- Already loaded
366 -> [Linkable] -- New linkables
367 -> ([Linkable], -- New loaded set (including new ones)
368 [Linkable]) -- New linkables (excluding dups)
369 rmDupLinkables already ls
372 go already extras [] = (already, extras)
373 go already extras (l:ls)
374 | linkableInSet l already = go already extras ls
375 | otherwise = go (l:already) (l:extras) ls
380 linkLibraries :: DynFlags
381 -> [String] -- foo.o files specified on command line
383 -- Used just at initialisation time to link in libraries
384 -- specified on the command line.
385 linkLibraries dflags objs
386 = do { lib_paths <- readIORef v_Library_paths
387 ; opt_l <- getStaticOpts v_Opt_l
388 ; let minus_ls = [ lib | '-':'l':lib <- opt_l ]
389 ; let cmdline_lib_specs = map Object objs ++ map DLL minus_ls
391 ; if (null cmdline_lib_specs) then return ()
395 ; mapM_ (preloadLib dflags lib_paths) cmdline_lib_specs
397 ; maybePutStr dflags "final link ... "
399 ; if succeeded ok then maybePutStrLn dflags "done."
400 else throwDyn (InstallationError "linking extra libraries/objects failed")
403 preloadLib :: DynFlags -> [String] -> LibrarySpec -> IO ()
404 preloadLib dflags lib_paths lib_spec
405 = do maybePutStr dflags ("Loading object " ++ showLS lib_spec ++ " ... ")
408 -> do b <- preload_static lib_paths static_ish
409 maybePutStrLn dflags (if b then "done."
412 -> do maybe_errstr <- loadDynamic lib_paths dll_unadorned
415 Just mm -> preloadFailed mm lib_paths lib_spec
416 maybePutStrLn dflags "done"
418 preloadFailed :: String -> [String] -> LibrarySpec -> IO ()
419 preloadFailed sys_errmsg paths spec
420 = do maybePutStr dflags
421 ("failed.\nDynamic linker error message was:\n "
422 ++ sys_errmsg ++ "\nWhilst trying to load: "
423 ++ showLS spec ++ "\nDirectories to search are:\n"
424 ++ unlines (map (" "++) paths) )
427 -- not interested in the paths in the static case.
428 preload_static paths name
429 = do b <- doesFileExist name
430 if not b then return False
431 else loadObj name >> return True
434 = (throwDyn . CmdLineError)
435 "user specified .o/.so/.DLL could not be loaded."
439 %************************************************************************
441 \subsection{The byte-code linker}
443 %************************************************************************
446 dynLinkBCOs :: [Linkable] -> IO ()
447 -- Side-effects the persistent linker state
449 = do pls <- readIORef v_PersistentLinkerState
451 let (bcos_loaded', new_bcos) = rmDupLinkables (bcos_loaded pls) bcos
452 pls1 = pls { bcos_loaded = bcos_loaded' }
453 unlinkeds :: [Unlinked]
454 unlinkeds = concatMap linkableUnlinked new_bcos
456 cbcs :: [CompiledByteCode]
457 cbcs = map byteCodeOfObject unlinkeds
460 ul_bcos = [b | ByteCode bs _ <- cbcs, b <- bs]
461 ies = [ie | ByteCode _ ie <- cbcs]
462 gce = closure_env pls
463 final_ie = foldr plusNameEnv (itbl_env pls) ies
465 (final_gce, linked_bcos) <- linkSomeBCOs True final_ie gce ul_bcos
466 -- What happens to these linked_bcos?
468 let pls2 = pls1 { closure_env = final_gce,
469 itbl_env = final_ie }
471 writeIORef v_PersistentLinkerState pls2
474 -- Link a bunch of BCOs and return them + updated closure env.
475 linkSomeBCOs :: Bool -- False <=> add _all_ BCOs to returned closure env
476 -- True <=> add only toplevel BCOs to closure env
480 -> IO (ClosureEnv, [HValue])
481 -- The returned HValues are associated 1-1 with
482 -- the incoming unlinked BCOs. Each gives the
483 -- value of the corresponding unlinked BCO
486 linkSomeBCOs toplevs_only ie ce_in ul_bcos
487 = do let nms = map unlinkedBCOName ul_bcos
489 ( \ hvs -> let ce_out = extendClosureEnv ce_in (zipLazy nms hvs)
490 in mapM (linkBCO ie ce_out) ul_bcos )
492 let ce_all_additions = zip nms hvals
493 ce_top_additions = filter (isExternalName.fst) ce_all_additions
494 ce_additions = if toplevs_only then ce_top_additions
495 else ce_all_additions
496 ce_out = -- make sure we're not inserting duplicate names into the
497 -- closure environment, which leads to trouble.
498 ASSERT (all (not . (`elemNameEnv` ce_in)) (map fst ce_additions))
499 extendClosureEnv ce_in ce_additions
500 return (ce_out, hvals)
505 %************************************************************************
507 Unload some object modules
509 %************************************************************************
512 -- ---------------------------------------------------------------------------
513 -- Unloading old objects ready for a new compilation sweep.
515 -- The compilation manager provides us with a list of linkables that it
516 -- considers "stable", i.e. won't be recompiled this time around. For
517 -- each of the modules current linked in memory,
519 -- * if the linkable is stable (and it's the same one - the
520 -- user may have recompiled the module on the side), we keep it,
522 -- * otherwise, we unload it.
524 -- * we also implicitly unload all temporary bindings at this point.
526 unload :: DynFlags -> [Linkable] -> IO ()
527 -- The 'linkables' are the ones to *keep*
529 unload dflags linkables
530 = block $ do -- block, so we're safe from Ctrl-C in here
532 pls <- readIORef v_PersistentLinkerState
533 new_pls <- unload_wkr dflags linkables pls
534 writeIORef v_PersistentLinkerState new_pls
536 let verb = verbosity dflags
537 when (verb >= 3) $ do
538 hPutStrLn stderr (showSDoc
539 (text "unload: retaining objs" <+> ppr (objs_loaded new_pls)))
540 hPutStrLn stderr (showSDoc
541 (text "unload: retaining bcos" <+> ppr (bcos_loaded new_pls)))
545 unload_wkr :: DynFlags
546 -> [Linkable] -- stable linkables
547 -> PersistentLinkerState
548 -> IO PersistentLinkerState
549 -- Does the core unload business
550 -- (the wrapper blocks exceptions and deals with the PLS get and put)
552 unload_wkr dflags linkables pls
553 = do let (objs_to_keep, bcos_to_keep) = partition isObjectLinkable linkables
555 objs_loaded' <- filterM (maybeUnload objs_to_keep) (objs_loaded pls)
556 bcos_loaded' <- filterM (maybeUnload bcos_to_keep) (bcos_loaded pls)
558 let objs_retained = map linkableModName objs_loaded'
559 bcos_retained = map linkableModName bcos_loaded'
560 itbl_env' = filterNameMap bcos_retained (itbl_env pls)
561 closure_env' = filterNameMap bcos_retained (closure_env pls)
562 new_pls = pls { itbl_env = itbl_env',
563 closure_env = closure_env',
564 bcos_loaded = bcos_loaded',
565 objs_loaded = objs_loaded' }
569 maybeUnload :: [Linkable] -> Linkable -> IO Bool
570 maybeUnload keep_linkables lnk
571 | linkableInSet lnk linkables = return True
573 = do mapM_ unloadObj [f | DotO f <- linkableUnlinked lnk]
574 -- The components of a BCO linkable may contain
575 -- dot-o files. Which is very confusing.
577 -- But the BCO parts can be unlinked just by
578 -- letting go of them (plus of course depopulating
579 -- the symbol table which is done in the main body)
584 %************************************************************************
588 %************************************************************************
593 = Object FilePath -- Full path name of a .o file, including trailing .o
594 -- For dynamic objects only, try to find the object
595 -- file in all the directories specified in
596 -- v_Library_paths before giving up.
598 | DLL String -- "Unadorned" name of a .DLL/.so
599 -- e.g. On unix "qt" denotes "libqt.so"
600 -- On WinDoze "burble" denotes "burble.DLL"
601 -- loadDLL is platform-specific and adds the lib/.so/.DLL
602 -- suffixes platform-dependently
603 #ifdef darwin_TARGET_OS
607 -- If this package is already part of the GHCi binary, we'll already
608 -- have the right DLLs for this package loaded, so don't try to
611 -- But on Win32 we must load them 'again'; doing so is a harmless no-op
612 -- as far as the loader is concerned, but it does initialise the list
613 -- of DLL handles that rts/Linker.c maintains, and that in turn is
614 -- used by lookupSymbol. So we must call addDLL for each library
615 -- just to get the DLL handle into the list.
617 # ifndef mingw32_TARGET_OS
618 = [ "base", "haskell98", "haskell-src", "readline" ]
623 showLS (Object nm) = "(static) " ++ nm
624 showLS (DLL nm) = "(dynamic) " ++ nm
625 #ifdef darwin_TARGET_OS
626 showLS (Framework nm) = "(framework) " ++ nm
629 linkPackages :: DynFlags -> [PackageName] -> IO ()
630 -- Link exactly the specified packages, and their dependents
631 -- (unless of course they are already linked)
632 -- The dependents are linked automatically, and it doesn't matter
633 -- what order you specify the input packages.
635 -- NOTE: in fact, since each module tracks all the packages it depends on,
636 -- we don't really need to use the package-config dependencies.
637 -- However we do need the package-config stuff (to find aux libs etc),
638 -- and following them lets us load libraries in the right order, which
639 -- perhaps makes the error message a bit more localised if we get a link
640 -- failure. So the dependency walking code is still here.
642 linkPackages dflags new_pkgs
643 = do { pls <- readIORef v_PersistentLinkerState
644 ; pkg_map <- getPackageConfigMap
646 ; pkgs' <- link pkg_map (pkgs_loaded pls) new_pkgs
648 ; writeIORef v_PersistentLinkerState (pls { pkgs_loaded = pkgs' })
651 link :: PackageConfigMap -> [PackageName] -> [PackageName] -> IO [PackageName]
652 link pkg_map pkgs new_pkgs
653 = foldM (link_one pkg_map) pkgs new_pkgs
655 link_one pkg_map pkgs new_pkg
656 | new_pkg `elem` pkgs -- Already linked
659 | Just pkg_cfg <- lookupPkg pkg_map new_pkg
660 = do { -- Link dependents first
661 pkgs' <- link pkg_map pkgs (packageDependents pkg_cfg)
662 -- Now link the package itself
663 ; linkPackage dflags pkg_cfg
664 ; return (new_pkg : pkgs') }
667 = throwDyn (CmdLineError ("unknown package name: " ++ packageNameString new_pkg))
670 linkPackage :: DynFlags -> PackageConfig -> IO ()
671 linkPackage dflags pkg
673 let dirs = Packages.library_dirs pkg
674 let libs = Packages.hs_libraries pkg ++ extra_libraries pkg
675 ++ [ lib | '-':'l':lib <- extra_ld_opts pkg ]
676 classifieds <- mapM (locateOneObj dirs) libs
677 #ifdef darwin_TARGET_OS
678 let fwDirs = Packages.framework_dirs pkg
679 let frameworks= Packages.extra_frameworks pkg
682 -- Complication: all the .so's must be loaded before any of the .o's.
683 let dlls = [ dll | DLL dll <- classifieds ]
684 objs = [ obj | Object obj <- classifieds ]
686 maybePutStr dflags ("Loading package " ++ Packages.name pkg ++ " ... ")
688 -- See comments with partOfGHCi
689 when (Packages.name pkg `notElem` partOfGHCi) $ do
690 #ifdef darwin_TARGET_OS
691 loadFrameworks fwDirs frameworks
693 loadDynamics dirs dlls
695 -- After loading all the DLLs, we can load the static objects.
698 maybePutStr dflags "linking ... "
700 if succeeded ok then maybePutStrLn dflags "done."
701 else panic ("can't load package `" ++ name pkg ++ "'")
703 loadDynamics dirs [] = return ()
704 loadDynamics dirs (dll:dlls) = do
705 r <- loadDynamic dirs dll
707 Nothing -> loadDynamics dirs dlls
708 Just err -> throwDyn (CmdLineError ("can't load .so/.DLL for: "
709 ++ dll ++ " (" ++ err ++ ")" ))
710 #ifdef darwin_TARGET_OS
711 loadFrameworks dirs [] = return ()
712 loadFrameworks dirs (fw:fws) = do
713 r <- loadFramework dirs fw
715 Nothing -> loadFrameworks dirs fws
716 Just err -> throwDyn (CmdLineError ("can't load framework: "
717 ++ fw ++ " (" ++ err ++ ")" ))
720 -- Try to find an object file for a given library in the given paths.
721 -- If it isn't present, we assume it's a dynamic library.
722 locateOneObj :: [FilePath] -> String -> IO LibrarySpec
723 locateOneObj dirs lib
724 = do { mb_obj_path <- findFile mk_obj_path dirs
725 ; case mb_obj_path of
726 Just obj_path -> return (Object obj_path)
727 Nothing -> return (DLL lib) } -- we assume
729 mk_obj_path dir = dir ++ '/':lib ++ ".o"
732 -- ----------------------------------------------------------------------------
733 -- Loading a dyanmic library (dlopen()-ish on Unix, LoadLibrary-ish on Win32)
735 -- return Nothing == success, else Just error message from dlopen
736 loadDynamic paths rootname
737 = do { mb_dll <- findFile mk_dll_path paths
739 Just dll -> loadDLL dll
740 Nothing -> loadDLL (mkSOName rootname) }
741 -- Tried all our known library paths, so let
742 -- dlopen() search its own builtin paths now.
744 mk_dll_path dir = dir ++ '/':mkSOName rootname
746 #if defined(darwin_TARGET_OS)
747 mkSOName root = "lib" ++ root ++ ".dylib"
748 #elif defined(mingw32_TARGET_OS)
749 -- Win32 DLLs have no .dll extension here, because addDLL tries
750 -- both foo.dll and foo.drv
753 mkSOName root = "lib" ++ root ++ ".so"
756 -- Darwin / MacOS X only: load a framework
757 -- a framework is a dynamic library packaged inside a directory of the same
758 -- name. They are searched for in different paths than normal libraries.
759 #ifdef darwin_TARGET_OS
760 loadFramework extraPaths rootname
761 = do { mb_fwk <- findFile mk_fwk (extraPaths ++ defaultFrameworkPaths)
763 Just fwk_path -> loadDLL fwk_path
764 Nothing -> return (Just "not found") }
765 -- Tried all our known library paths, but dlopen()
766 -- has no built-in paths for frameworks: give up
768 mk_fwk dir = dir ++ '/' : rootname ++ ".framework/" ++ rootname
769 -- sorry for the hardcoded paths, I hope they won't change anytime soon:
770 defaultFrameworkPaths = ["/Library/Frameworks", "/System/Library/Frameworks"]
774 %************************************************************************
778 %************************************************************************
781 findFile :: (FilePath -> FilePath) -- Maps a directory path to a file path
782 -> [FilePath] -- Directories to look in
783 -> IO (Maybe FilePath) -- The first file path to match
784 findFile mk_file_path []
786 findFile mk_file_path (dir:dirs)
787 = do { let file_path = mk_file_path dir
788 ; b <- doesFileExist file_path
790 return (Just file_path)
792 findFile mk_file_path dirs }
796 maybePutStr dflags s | verbosity dflags > 0 = putStr s
797 | otherwise = return ()
799 maybePutStrLn dflags s | verbosity dflags > 0 = putStrLn s
800 | otherwise = return ()