2 % (c) The University of Glasgow 2005-2006
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
15 {-# OPTIONS -optc-DNON_POSIX_SOURCE -#include "Linker.h" #-}
17 module Linker ( HValue, getHValue, showLinkerState,
18 linkExpr, unload, withExtendedLinkEnv,
19 extendLinkEnv, deleteFromLinkEnv,
21 linkPackages,initDynLinker,
25 #include "HsVersions.h"
42 import qualified OccName
65 import Foreign.C.Types
66 import Foreign.C.String
67 import Foreign.Storable
70 import System.Directory
72 import Control.Exception
77 %************************************************************************
81 %************************************************************************
83 The persistent linker state *must* match the actual state of the
84 C dynamic linker at all times, so we keep it in a private global variable.
87 The PersistentLinkerState maps Names to actual closures (for
88 interpreted code only), for use during linking.
91 GLOBAL_VAR(v_PersistentLinkerState, panic "Dynamic linker not initialised", PersistentLinkerState)
92 GLOBAL_VAR(v_InitLinkerDone, False, Bool) -- Set True when dynamic linker is initialised
94 data PersistentLinkerState
95 = PersistentLinkerState {
97 -- Current global mapping from Names to their true values
98 closure_env :: ClosureEnv,
100 -- The current global mapping from RdrNames of DataCons to
101 -- info table addresses.
102 -- When a new Unlinked is linked into the running image, or an existing
103 -- module in the image is replaced, the itbl_env must be updated
107 -- The currently loaded interpreted modules (home package)
108 bcos_loaded :: [Linkable],
110 -- And the currently-loaded compiled modules (home package)
111 objs_loaded :: [Linkable],
113 -- The currently-loaded packages; always object code
114 -- Held, as usual, in dependency order; though I am not sure if
115 -- that is really important
116 pkgs_loaded :: [PackageId]
119 emptyPLS :: DynFlags -> PersistentLinkerState
120 emptyPLS dflags = PersistentLinkerState {
121 closure_env = emptyNameEnv,
122 itbl_env = emptyNameEnv,
123 pkgs_loaded = init_pkgs,
127 -- Packages that don't need loading, because the compiler
128 -- shares them with the interpreted program.
130 -- The linker's symbol table is populated with RTS symbols using an
131 -- explicit list. See rts/Linker.c for details.
132 where init_pkgs = [rtsPackageId]
136 extendLoadedPkgs :: [PackageId] -> IO ()
137 extendLoadedPkgs pkgs
138 = modifyIORef v_PersistentLinkerState (\s -> s{pkgs_loaded = pkgs ++ pkgs_loaded s})
140 extendLinkEnv :: [(Name,HValue)] -> IO ()
141 -- Automatically discards shadowed bindings
142 extendLinkEnv new_bindings
143 = do pls <- readIORef v_PersistentLinkerState
144 let new_closure_env = extendClosureEnv (closure_env pls) new_bindings
145 new_pls = pls { closure_env = new_closure_env }
146 writeIORef v_PersistentLinkerState new_pls
148 deleteFromLinkEnv :: [Name] -> IO ()
149 deleteFromLinkEnv to_remove
150 = do pls <- readIORef v_PersistentLinkerState
151 let new_closure_env = delListFromNameEnv (closure_env pls) to_remove
152 new_pls = pls { closure_env = new_closure_env }
153 writeIORef v_PersistentLinkerState new_pls
155 -- | Given a data constructor, find its internal name.
156 -- The info tables for data constructors have a field which records the source name
157 -- of the constructor as a CString. The format is:
159 -- Package:Module.Name
161 -- We use this string to lookup the interpreter's internal representation of the name
162 -- using the lookupOrig.
164 dataConInfoPtrToName :: Ptr () -> TcM Name
165 dataConInfoPtrToName x = do
166 theString <- ioToTcRn $ do
167 let ptr = castPtr x :: Ptr StgInfoTable
168 conDescAddress <- getConDescAddress ptr
169 str <- peekCString conDescAddress
171 let (pkg, mod, occ) = parse theString
172 occName = mkOccName OccName.dataName occ
173 modName = mkModule (stringToPackageId pkg) (mkModuleName mod)
174 lookupOrig modName occName
178 {- To find the string in the constructor's info table we need to consider
179 the layout of info tables relative to the entry code for a closure.
181 An info table can be next to the entry code for the closure, or it can
182 be separate. The former (faster) is used in registerised versions of ghc,
183 and the latter (portable) is for non-registerised versions.
185 The diagrams below show where the string is to be found relative to
186 the normal info table of the closure.
188 1) Code next to table:
191 | | <- pointer to the start of the string
193 | | <- the (start of the) info table structure
200 In this case the pointer to the start of the string can be found in
201 the memory location _one word before_ the first entry in the normal info
204 2) Code NOT next to table:
207 info table structure -> | *------------------> --------------
211 ptr to start of str -> | |
214 In this case the pointer to the start of the string can be found
215 in the memory location: info_table_ptr + info_table_size
218 getConDescAddress :: Ptr StgInfoTable -> IO (Ptr CChar)
219 getConDescAddress ptr = do
220 #ifdef GHCI_TABLES_NEXT_TO_CODE
221 offsetToString <- peek $ ptr `plusPtr` (- wORD_SIZE)
222 return $ (ptr `plusPtr` stdInfoTableSizeB) `plusPtr` (fromIntegral (offsetToString :: StgWord))
224 peek $ intPtrToPtr $ (ptrToIntPtr ptr) + stdInfoTableSizeB
227 -- parsing names is a little bit fiddly because we have a string in the form:
228 -- pkg:A.B.C.foo, and we want to split it into three parts: ("pkg", "A.B.C", "foo").
229 -- Thus we split at the leftmost colon and the rightmost occurrence of the dot.
230 -- It would be easier if the string was in the form pkg:A.B.C:foo, but alas
231 -- this is not the conventional way of writing Haskell names. We stick with
232 -- convention, even though it makes the parsing code more troublesome.
233 -- Warning: this code assumes that the string is well formed.
234 parse :: String -> (String, String, String)
236 = ASSERT (all (>0) (map length [pkg, mod, occ])) (pkg, mod, occ)
238 (pkg, rest1) = break (==':') input
240 = (concat $ intersperse "." $ reverse modWords, occWord)
242 (modWords, occWord) = ASSERT (length rest1 > 0) (parseModOcc [] (tail rest1))
243 parseModOcc :: [String] -> String -> ([String], String)
245 = case break (== '.') str of
246 (top, []) -> (acc, top)
247 (top, '.':bot) -> parseModOcc (top : acc) bot
250 getHValue :: HscEnv -> Name -> IO HValue
251 getHValue hsc_env name = do
252 when (isExternalName name) $ do
253 ok <- linkDependencies hsc_env noSrcSpan [nameModule name]
254 when (failed ok) $ throwDyn (ProgramError "")
255 pls <- readIORef v_PersistentLinkerState
256 lookupName (closure_env pls) name
258 linkDependencies :: HscEnv -> SrcSpan -> [Module] -> IO SuccessFlag
259 linkDependencies hsc_env span needed_mods = do
260 let hpt = hsc_HPT hsc_env
261 dflags = hsc_dflags hsc_env
262 -- The interpreter and dynamic linker can only handle object code built
263 -- the "normal" way, i.e. no non-std ways like profiling or ticky-ticky.
264 -- So here we check the build tag: if we're building a non-standard way
265 -- then we need to find & link object files built the "normal" way.
266 maybe_normal_osuf <- checkNonStdWay dflags span
268 -- Find what packages and linkables are required
269 eps <- readIORef (hsc_EPS hsc_env)
270 (lnks, pkgs) <- getLinkDeps hsc_env hpt (eps_PIT eps)
271 maybe_normal_osuf span needed_mods
273 -- Link the packages and modules required
274 linkPackages dflags pkgs
275 linkModules dflags lnks
278 withExtendedLinkEnv :: [(Name,HValue)] -> IO a -> IO a
279 withExtendedLinkEnv new_env action
280 = bracket set_new_env
283 where set_new_env = do pls <- readIORef v_PersistentLinkerState
284 let new_closure_env = extendClosureEnv (closure_env pls) new_env
285 new_pls = pls { closure_env = new_closure_env }
286 writeIORef v_PersistentLinkerState new_pls
287 return (closure_env pls)
288 reset_old_env env = modifyIORef v_PersistentLinkerState (\pls -> pls{ closure_env = env })
290 -- filterNameMap removes from the environment all entries except
291 -- those for a given set of modules;
292 -- Note that this removes all *local* (i.e. non-isExternal) names too
293 -- (these are the temporary bindings from the command line).
294 -- Used to filter both the ClosureEnv and ItblEnv
296 filterNameMap :: [Module] -> NameEnv (Name, a) -> NameEnv (Name, a)
297 filterNameMap mods env
298 = filterNameEnv keep_elt env
300 keep_elt (n,_) = isExternalName n
301 && (nameModule n `elem` mods)
306 showLinkerState :: IO ()
307 -- Display the persistent linker state
309 = do pls <- readIORef v_PersistentLinkerState
310 printDump (vcat [text "----- Linker state -----",
311 text "Pkgs:" <+> ppr (pkgs_loaded pls),
312 text "Objs:" <+> ppr (objs_loaded pls),
313 text "BCOs:" <+> ppr (bcos_loaded pls)])
319 %************************************************************************
321 \subsection{Initialisation}
323 %************************************************************************
325 We initialise the dynamic linker by
327 a) calling the C initialisation procedure
329 b) Loading any packages specified on the command line,
331 c) Loading any packages specified on the command line,
332 now held in the -l options in v_Opt_l
334 d) Loading any .o/.dll files specified on the command line,
335 now held in v_Ld_inputs
337 e) Loading any MacOS frameworks
340 initDynLinker :: DynFlags -> IO ()
341 -- This function is idempotent; if called more than once, it does nothing
342 -- This is useful in Template Haskell, where we call it before trying to link
344 = do { done <- readIORef v_InitLinkerDone
345 ; if done then return ()
346 else do { writeIORef v_InitLinkerDone True
347 ; reallyInitDynLinker dflags }
350 reallyInitDynLinker dflags
351 = do { -- Initialise the linker state
352 ; writeIORef v_PersistentLinkerState (emptyPLS dflags)
354 -- (a) initialise the C dynamic linker
357 -- (b) Load packages from the command-line
358 ; linkPackages dflags (preloadPackages (pkgState dflags))
360 -- (c) Link libraries from the command-line
361 ; let optl = getOpts dflags opt_l
362 ; let minus_ls = [ lib | '-':'l':lib <- optl ]
364 -- (d) Link .o files from the command-line
365 ; let lib_paths = libraryPaths dflags
366 ; cmdline_ld_inputs <- readIORef v_Ld_inputs
368 ; classified_ld_inputs <- mapM classifyLdInput cmdline_ld_inputs
370 -- (e) Link any MacOS frameworks
371 #ifdef darwin_TARGET_OS
372 ; let framework_paths = frameworkPaths dflags
373 ; let frameworks = cmdlineFrameworks dflags
375 ; let frameworks = []
376 ; let framework_paths = []
378 -- Finally do (c),(d),(e)
379 ; let cmdline_lib_specs = [ l | Just l <- classified_ld_inputs ]
381 ++ map Framework frameworks
382 ; if null cmdline_lib_specs then return ()
385 { mapM_ (preloadLib dflags lib_paths framework_paths) cmdline_lib_specs
386 ; maybePutStr dflags "final link ... "
389 ; if succeeded ok then maybePutStrLn dflags "done"
390 else throwDyn (InstallationError "linking extra libraries/objects failed")
393 classifyLdInput :: FilePath -> IO (Maybe LibrarySpec)
395 | isObjectFilename f = return (Just (Object f))
396 | isDynLibFilename f = return (Just (DLLPath f))
398 hPutStrLn stderr ("Warning: ignoring unrecognised input `" ++ f ++ "'")
401 preloadLib :: DynFlags -> [String] -> [String] -> LibrarySpec -> IO ()
402 preloadLib dflags lib_paths framework_paths lib_spec
403 = do maybePutStr dflags ("Loading object " ++ showLS lib_spec ++ " ... ")
406 -> do b <- preload_static lib_paths static_ish
407 maybePutStrLn dflags (if b then "done"
411 -> do maybe_errstr <- loadDynamic lib_paths dll_unadorned
413 Nothing -> maybePutStrLn dflags "done"
414 Just mm -> preloadFailed mm lib_paths lib_spec
417 -> do maybe_errstr <- loadDLL dll_path
419 Nothing -> maybePutStrLn dflags "done"
420 Just mm -> preloadFailed mm lib_paths lib_spec
422 #ifdef darwin_TARGET_OS
424 -> do maybe_errstr <- loadFramework framework_paths framework
426 Nothing -> maybePutStrLn dflags "done"
427 Just mm -> preloadFailed mm framework_paths lib_spec
430 preloadFailed :: String -> [String] -> LibrarySpec -> IO ()
431 preloadFailed sys_errmsg paths spec
432 = do maybePutStr dflags
433 ("failed.\nDynamic linker error message was:\n "
434 ++ sys_errmsg ++ "\nWhilst trying to load: "
435 ++ showLS spec ++ "\nDirectories to search are:\n"
436 ++ unlines (map (" "++) paths) )
439 -- Not interested in the paths in the static case.
440 preload_static paths name
441 = do b <- doesFileExist name
442 if not b then return False
443 else loadObj name >> return True
446 CmdLineError "user specified .o/.so/.DLL could not be loaded."
450 %************************************************************************
452 Link a byte-code expression
454 %************************************************************************
457 linkExpr :: HscEnv -> SrcSpan -> UnlinkedBCO -> IO HValue
459 -- Link a single expression, *including* first linking packages and
460 -- modules that this expression depends on.
462 -- Raises an IO exception if it can't find a compiled version of the
463 -- dependents to link.
465 -- Note: This function side-effects the linker state (Pepe)
467 linkExpr hsc_env span root_ul_bco
469 -- Initialise the linker (if it's not been done already)
470 let dflags = hsc_dflags hsc_env
471 ; initDynLinker dflags
473 -- Link the packages and modules required
474 ; ok <- linkDependencies hsc_env span needed_mods
476 throwDyn (ProgramError "")
479 -- Link the expression itself
480 pls <- readIORef v_PersistentLinkerState
481 ; let ie = itbl_env pls
484 -- Link the necessary packages and linkables
485 ; (_, (root_hval:_)) <- linkSomeBCOs False ie ce [root_ul_bco]
489 free_names = nameSetToList (bcoFreeNames root_ul_bco)
491 needed_mods :: [Module]
492 needed_mods = [ nameModule n | n <- free_names,
493 isExternalName n, -- Names from other modules
494 not (isWiredInName n) -- Exclude wired-in names
495 ] -- (see note below)
496 -- Exclude wired-in names because we may not have read
497 -- their interface files, so getLinkDeps will fail
498 -- All wired-in names are in the base package, which we link
499 -- by default, so we can safely ignore them here.
501 dieWith span msg = throwDyn (ProgramError (showSDoc (mkLocMessage span msg)))
504 checkNonStdWay :: DynFlags -> SrcSpan -> IO (Maybe String)
505 checkNonStdWay dflags srcspan = do
506 tag <- readIORef v_Build_tag
507 if null tag then return Nothing else do
508 let default_osuf = phaseInputExt StopLn
509 if objectSuf dflags == default_osuf
510 then failNonStd srcspan
511 else return (Just default_osuf)
513 failNonStd srcspan = dieWith srcspan $
514 ptext SLIT("Dynamic linking required, but this is a non-standard build (eg. prof).") $$
515 ptext SLIT("You need to build the program twice: once the normal way, and then") $$
516 ptext SLIT("in the desired way using -osuf to set the object file suffix.")
519 getLinkDeps :: HscEnv -> HomePackageTable -> PackageIfaceTable
520 -> Maybe String -- the "normal" object suffix
521 -> SrcSpan -- for error messages
522 -> [Module] -- If you need these
523 -> IO ([Linkable], [PackageId]) -- ... then link these first
524 -- Fails with an IO exception if it can't find enough files
526 getLinkDeps hsc_env hpt pit maybe_normal_osuf span mods
527 -- Find all the packages and linkables that a set of modules depends on
528 = do { pls <- readIORef v_PersistentLinkerState ;
530 -- 1. Find the dependent home-pkg-modules/packages from each iface
531 (mods_s, pkgs_s) = follow_deps mods emptyUniqSet emptyUniqSet;
533 -- 2. Exclude ones already linked
534 -- Main reason: avoid findModule calls in get_linkable
535 mods_needed = mods_s `minusList` linked_mods ;
536 pkgs_needed = pkgs_s `minusList` pkgs_loaded pls ;
538 linked_mods = map (moduleName.linkableModule)
539 (objs_loaded pls ++ bcos_loaded pls)
542 -- putStrLn (showSDoc (ppr mods_s)) ;
543 -- 3. For each dependent module, find its linkable
544 -- This will either be in the HPT or (in the case of one-shot
545 -- compilation) we may need to use maybe_getFileLinkable
546 lnks_needed <- mapM (get_linkable maybe_normal_osuf) mods_needed ;
548 return (lnks_needed, pkgs_needed) }
550 dflags = hsc_dflags hsc_env
551 this_pkg = thisPackage dflags
553 -- The ModIface contains the transitive closure of the module dependencies
554 -- within the current package, *except* for boot modules: if we encounter
555 -- a boot module, we have to find its real interface and discover the
556 -- dependencies of that. Hence we need to traverse the dependency
557 -- tree recursively. See bug #936, testcase ghci/prog007.
558 follow_deps :: [Module] -- modules to follow
559 -> UniqSet ModuleName -- accum. module dependencies
560 -> UniqSet PackageId -- accum. package dependencies
561 -> ([ModuleName], [PackageId]) -- result
562 follow_deps [] acc_mods acc_pkgs
563 = (uniqSetToList acc_mods, uniqSetToList acc_pkgs)
564 follow_deps (mod:mods) acc_mods acc_pkgs
566 = follow_deps mods acc_mods (addOneToUniqSet acc_pkgs' pkg)
568 = link_boot_mod_error mod
570 = follow_deps (map (mkModule this_pkg) boot_deps' ++ mods) acc_mods' acc_pkgs'
572 pkg = modulePackageId mod
573 iface = get_iface mod
576 pkg_deps = dep_pkgs deps
577 (boot_deps, mod_deps) = partitionWith is_boot (dep_mods deps)
578 where is_boot (m,True) = Left m
579 is_boot (m,False) = Right m
581 boot_deps' = filter (not . (`elementOfUniqSet` acc_mods)) boot_deps
582 acc_mods' = addListToUniqSet acc_mods (moduleName mod : mod_deps)
583 acc_pkgs' = addListToUniqSet acc_pkgs pkg_deps
586 link_boot_mod_error mod =
587 throwDyn (ProgramError (showSDoc (
588 text "module" <+> ppr mod <+>
589 text "cannot be linked; it is only available as a boot module")))
591 get_iface mod = case lookupIfaceByModule dflags hpt pit mod of
593 Nothing -> pprPanic "getLinkDeps" (no_iface mod)
594 no_iface mod = ptext SLIT("No iface for") <+> ppr mod
595 -- This one is a GHC bug
597 no_obj mod = dieWith span $
598 ptext SLIT("cannot find object file for module ") <>
602 while_linking_expr = ptext SLIT("while linking an interpreted expression")
604 -- This one is a build-system bug
606 get_linkable maybe_normal_osuf mod_name -- A home-package module
607 | Just mod_info <- lookupUFM hpt mod_name
608 = ASSERT(isJust (hm_linkable mod_info))
609 adjust_linkable (fromJust (hm_linkable mod_info))
611 = do -- It's not in the HPT because we are in one shot mode,
612 -- so use the Finder to get a ModLocation...
613 mb_stuff <- findHomeModule hsc_env mod_name
615 Found loc mod -> found loc mod
619 -- ...and then find the linkable for it
620 mb_lnk <- findObjectLinkableMaybe mod loc ;
622 Nothing -> no_obj mod ;
623 Just lnk -> adjust_linkable lnk
627 | Just osuf <- maybe_normal_osuf = do
628 new_uls <- mapM (adjust_ul osuf) (linkableUnlinked lnk)
629 return lnk{ linkableUnlinked=new_uls }
633 adjust_ul osuf (DotO file) = do
634 let new_file = replaceFilenameSuffix file osuf
635 ok <- doesFileExist new_file
638 ptext SLIT("cannot find normal object file ")
639 <> quotes (text new_file) $$ while_linking_expr
640 else return (DotO new_file)
644 %************************************************************************
647 The linkables may consist of a mixture of
648 byte-code modules and object modules
650 %************************************************************************
653 linkModules :: DynFlags -> [Linkable] -> IO SuccessFlag
654 linkModules dflags linkables
655 = block $ do -- don't want to be interrupted by ^C in here
657 let (objs, bcos) = partition isObjectLinkable
658 (concatMap partitionLinkable linkables)
660 -- Load objects first; they can't depend on BCOs
661 ok_flag <- dynLinkObjs dflags objs
663 if failed ok_flag then
670 -- HACK to support f-x-dynamic in the interpreter; no other purpose
671 partitionLinkable :: Linkable -> [Linkable]
673 = let li_uls = linkableUnlinked li
674 li_uls_obj = filter isObject li_uls
675 li_uls_bco = filter isInterpretable li_uls
677 case (li_uls_obj, li_uls_bco) of
678 (objs@(_:_), bcos@(_:_))
679 -> [li{linkableUnlinked=li_uls_obj}, li{linkableUnlinked=li_uls_bco}]
683 findModuleLinkable_maybe :: [Linkable] -> Module -> Maybe Linkable
684 findModuleLinkable_maybe lis mod
685 = case [LM time nm us | LM time nm us <- lis, nm == mod] of
688 many -> pprPanic "findModuleLinkable" (ppr mod)
690 linkableInSet :: Linkable -> [Linkable] -> Bool
691 linkableInSet l objs_loaded =
692 case findModuleLinkable_maybe objs_loaded (linkableModule l) of
694 Just m -> linkableTime l == linkableTime m
698 %************************************************************************
700 \subsection{The object-code linker}
702 %************************************************************************
705 dynLinkObjs :: DynFlags -> [Linkable] -> IO SuccessFlag
706 -- Side-effects the PersistentLinkerState
708 dynLinkObjs dflags objs
709 = do pls <- readIORef v_PersistentLinkerState
711 -- Load the object files and link them
712 let (objs_loaded', new_objs) = rmDupLinkables (objs_loaded pls) objs
713 pls1 = pls { objs_loaded = objs_loaded' }
714 unlinkeds = concatMap linkableUnlinked new_objs
716 mapM loadObj (map nameOfObject unlinkeds)
718 -- Link the all together
721 -- If resolving failed, unload all our
722 -- object modules and carry on
723 if succeeded ok then do
724 writeIORef v_PersistentLinkerState pls1
727 pls2 <- unload_wkr dflags [] pls1
728 writeIORef v_PersistentLinkerState pls2
732 rmDupLinkables :: [Linkable] -- Already loaded
733 -> [Linkable] -- New linkables
734 -> ([Linkable], -- New loaded set (including new ones)
735 [Linkable]) -- New linkables (excluding dups)
736 rmDupLinkables already ls
739 go already extras [] = (already, extras)
740 go already extras (l:ls)
741 | linkableInSet l already = go already extras ls
742 | otherwise = go (l:already) (l:extras) ls
745 %************************************************************************
747 \subsection{The byte-code linker}
749 %************************************************************************
752 dynLinkBCOs :: [Linkable] -> IO ()
753 -- Side-effects the persistent linker state
755 = do pls <- readIORef v_PersistentLinkerState
757 let (bcos_loaded', new_bcos) = rmDupLinkables (bcos_loaded pls) bcos
758 pls1 = pls { bcos_loaded = bcos_loaded' }
759 unlinkeds :: [Unlinked]
760 unlinkeds = concatMap linkableUnlinked new_bcos
762 cbcs :: [CompiledByteCode]
763 cbcs = map byteCodeOfObject unlinkeds
766 ul_bcos = [b | ByteCode bs _ <- cbcs, b <- bs]
767 ies = [ie | ByteCode _ ie <- cbcs]
768 gce = closure_env pls
769 final_ie = foldr plusNameEnv (itbl_env pls) ies
771 (final_gce, linked_bcos) <- linkSomeBCOs True final_ie gce ul_bcos
772 -- What happens to these linked_bcos?
774 let pls2 = pls1 { closure_env = final_gce,
775 itbl_env = final_ie }
777 writeIORef v_PersistentLinkerState pls2
780 -- Link a bunch of BCOs and return them + updated closure env.
781 linkSomeBCOs :: Bool -- False <=> add _all_ BCOs to returned closure env
782 -- True <=> add only toplevel BCOs to closure env
786 -> IO (ClosureEnv, [HValue])
787 -- The returned HValues are associated 1-1 with
788 -- the incoming unlinked BCOs. Each gives the
789 -- value of the corresponding unlinked BCO
791 linkSomeBCOs toplevs_only ie ce_in ul_bcos
792 = do let nms = map unlinkedBCOName ul_bcos
794 ( \ hvs -> let ce_out = extendClosureEnv ce_in (zipLazy nms hvs)
795 in mapM (linkBCO ie ce_out) ul_bcos )
796 let ce_all_additions = zip nms hvals
797 ce_top_additions = filter (isExternalName.fst) ce_all_additions
798 ce_additions = if toplevs_only then ce_top_additions
799 else ce_all_additions
800 ce_out = -- make sure we're not inserting duplicate names into the
801 -- closure environment, which leads to trouble.
802 ASSERT (all (not . (`elemNameEnv` ce_in)) (map fst ce_additions))
803 extendClosureEnv ce_in ce_additions
804 return (ce_out, hvals)
809 %************************************************************************
811 Unload some object modules
813 %************************************************************************
816 -- ---------------------------------------------------------------------------
817 -- Unloading old objects ready for a new compilation sweep.
819 -- The compilation manager provides us with a list of linkables that it
820 -- considers "stable", i.e. won't be recompiled this time around. For
821 -- each of the modules current linked in memory,
823 -- * if the linkable is stable (and it's the same one - the
824 -- user may have recompiled the module on the side), we keep it,
826 -- * otherwise, we unload it.
828 -- * we also implicitly unload all temporary bindings at this point.
830 unload :: DynFlags -> [Linkable] -> IO ()
831 -- The 'linkables' are the ones to *keep*
833 unload dflags linkables
834 = block $ do -- block, so we're safe from Ctrl-C in here
836 -- Initialise the linker (if it's not been done already)
839 pls <- readIORef v_PersistentLinkerState
840 new_pls <- unload_wkr dflags linkables pls
841 writeIORef v_PersistentLinkerState new_pls
843 debugTraceMsg dflags 3 (text "unload: retaining objs" <+> ppr (objs_loaded new_pls))
844 debugTraceMsg dflags 3 (text "unload: retaining bcos" <+> ppr (bcos_loaded new_pls))
847 unload_wkr :: DynFlags
848 -> [Linkable] -- stable linkables
849 -> PersistentLinkerState
850 -> IO PersistentLinkerState
851 -- Does the core unload business
852 -- (the wrapper blocks exceptions and deals with the PLS get and put)
854 unload_wkr dflags linkables pls
855 = do let (objs_to_keep, bcos_to_keep) = partition isObjectLinkable linkables
857 objs_loaded' <- filterM (maybeUnload objs_to_keep) (objs_loaded pls)
858 bcos_loaded' <- filterM (maybeUnload bcos_to_keep) (bcos_loaded pls)
860 let bcos_retained = map linkableModule bcos_loaded'
861 itbl_env' = filterNameMap bcos_retained (itbl_env pls)
862 closure_env' = filterNameMap bcos_retained (closure_env pls)
863 new_pls = pls { itbl_env = itbl_env',
864 closure_env = closure_env',
865 bcos_loaded = bcos_loaded',
866 objs_loaded = objs_loaded' }
870 maybeUnload :: [Linkable] -> Linkable -> IO Bool
871 maybeUnload keep_linkables lnk
872 | linkableInSet lnk linkables = return True
874 = do mapM_ unloadObj [f | DotO f <- linkableUnlinked lnk]
875 -- The components of a BCO linkable may contain
876 -- dot-o files. Which is very confusing.
878 -- But the BCO parts can be unlinked just by
879 -- letting go of them (plus of course depopulating
880 -- the symbol table which is done in the main body)
885 %************************************************************************
889 %************************************************************************
894 = Object FilePath -- Full path name of a .o file, including trailing .o
895 -- For dynamic objects only, try to find the object
896 -- file in all the directories specified in
897 -- v_Library_paths before giving up.
899 | DLL String -- "Unadorned" name of a .DLL/.so
900 -- e.g. On unix "qt" denotes "libqt.so"
901 -- On WinDoze "burble" denotes "burble.DLL"
902 -- loadDLL is platform-specific and adds the lib/.so/.DLL
903 -- suffixes platform-dependently
905 | DLLPath FilePath -- Absolute or relative pathname to a dynamic library
906 -- (ends with .dll or .so).
908 | Framework String -- Only used for darwin, but does no harm
910 -- If this package is already part of the GHCi binary, we'll already
911 -- have the right DLLs for this package loaded, so don't try to
914 -- But on Win32 we must load them 'again'; doing so is a harmless no-op
915 -- as far as the loader is concerned, but it does initialise the list
916 -- of DLL handles that rts/Linker.c maintains, and that in turn is
917 -- used by lookupSymbol. So we must call addDLL for each library
918 -- just to get the DLL handle into the list.
920 # if defined(mingw32_TARGET_OS) || defined(darwin_TARGET_OS)
923 = [ "base", "haskell98", "template-haskell", "readline" ]
926 showLS (Object nm) = "(static) " ++ nm
927 showLS (DLL nm) = "(dynamic) " ++ nm
928 showLS (DLLPath nm) = "(dynamic) " ++ nm
929 showLS (Framework nm) = "(framework) " ++ nm
931 linkPackages :: DynFlags -> [PackageId] -> IO ()
932 -- Link exactly the specified packages, and their dependents
933 -- (unless of course they are already linked)
934 -- The dependents are linked automatically, and it doesn't matter
935 -- what order you specify the input packages.
937 -- NOTE: in fact, since each module tracks all the packages it depends on,
938 -- we don't really need to use the package-config dependencies.
939 -- However we do need the package-config stuff (to find aux libs etc),
940 -- and following them lets us load libraries in the right order, which
941 -- perhaps makes the error message a bit more localised if we get a link
942 -- failure. So the dependency walking code is still here.
944 linkPackages dflags new_pkgs
945 = do { pls <- readIORef v_PersistentLinkerState
946 ; let pkg_map = pkgIdMap (pkgState dflags)
948 ; pkgs' <- link pkg_map (pkgs_loaded pls) new_pkgs
950 ; writeIORef v_PersistentLinkerState (pls { pkgs_loaded = pkgs' })
953 link :: PackageConfigMap -> [PackageId] -> [PackageId] -> IO [PackageId]
954 link pkg_map pkgs new_pkgs
955 = foldM (link_one pkg_map) pkgs new_pkgs
957 link_one pkg_map pkgs new_pkg
958 | new_pkg `elem` pkgs -- Already linked
961 | Just pkg_cfg <- lookupPackage pkg_map new_pkg
962 = do { -- Link dependents first
963 pkgs' <- link pkg_map pkgs (map mkPackageId (depends pkg_cfg))
964 -- Now link the package itself
965 ; linkPackage dflags pkg_cfg
966 ; return (new_pkg : pkgs') }
969 = throwDyn (CmdLineError ("unknown package: " ++ packageIdString new_pkg))
972 linkPackage :: DynFlags -> PackageConfig -> IO ()
973 linkPackage dflags pkg
975 let dirs = Packages.libraryDirs pkg
977 let libs = Packages.hsLibraries pkg
978 -- Because of slight differences between the GHC dynamic linker and
979 -- the native system linker some packages have to link with a
980 -- different list of libraries when using GHCi. Examples include: libs
981 -- that are actually gnu ld scripts, and the possability that the .a
982 -- libs do not exactly match the .so/.dll equivalents. So if the
983 -- package file provides an "extra-ghci-libraries" field then we use
984 -- that instead of the "extra-libraries" field.
985 ++ (if null (Packages.extraGHCiLibraries pkg)
986 then Packages.extraLibraries pkg
987 else Packages.extraGHCiLibraries pkg)
988 ++ [ lib | '-':'l':lib <- Packages.ldOptions pkg ]
989 classifieds <- mapM (locateOneObj dirs) libs
991 -- Complication: all the .so's must be loaded before any of the .o's.
992 let dlls = [ dll | DLL dll <- classifieds ]
993 objs = [ obj | Object obj <- classifieds ]
995 maybePutStr dflags ("Loading package " ++ showPackageId (package pkg) ++ " ... ")
997 -- See comments with partOfGHCi
998 when (pkgName (package pkg) `notElem` partOfGHCi) $ do
1000 -- When a library A needs symbols from a library B, the order in
1001 -- extra_libraries/extra_ld_opts is "-lA -lB", because that's the
1002 -- way ld expects it for static linking. Dynamic linking is a
1003 -- different story: When A has no dependency information for B,
1004 -- dlopen-ing A with RTLD_NOW (see addDLL in Linker.c) will fail
1005 -- when B has not been loaded before. In a nutshell: Reverse the
1006 -- order of DLLs for dynamic linking.
1007 -- This fixes a problem with the HOpenGL package (see "Compiling
1008 -- HOpenGL under recent versions of GHC" on the HOpenGL list).
1009 mapM_ (load_dyn dirs) (reverse dlls)
1011 -- After loading all the DLLs, we can load the static objects.
1012 -- Ordering isn't important here, because we do one final link
1013 -- step to resolve everything.
1016 maybePutStr dflags "linking ... "
1018 if succeeded ok then maybePutStrLn dflags "done."
1019 else throwDyn (InstallationError ("unable to load package `" ++ showPackageId (package pkg) ++ "'"))
1021 load_dyn dirs dll = do r <- loadDynamic dirs dll
1023 Nothing -> return ()
1024 Just err -> throwDyn (CmdLineError ("can't load .so/.DLL for: "
1025 ++ dll ++ " (" ++ err ++ ")" ))
1026 #ifndef darwin_TARGET_OS
1027 loadFrameworks pkg = return ()
1029 loadFrameworks pkg = mapM_ load frameworks
1031 fw_dirs = Packages.frameworkDirs pkg
1032 frameworks = Packages.frameworks pkg
1034 load fw = do r <- loadFramework fw_dirs fw
1036 Nothing -> return ()
1037 Just err -> throwDyn (CmdLineError ("can't load framework: "
1038 ++ fw ++ " (" ++ err ++ ")" ))
1041 -- Try to find an object file for a given library in the given paths.
1042 -- If it isn't present, we assume it's a dynamic library.
1043 locateOneObj :: [FilePath] -> String -> IO LibrarySpec
1044 locateOneObj dirs lib
1045 = do { mb_obj_path <- findFile mk_obj_path dirs
1046 ; case mb_obj_path of
1047 Just obj_path -> return (Object obj_path)
1049 do { mb_lib_path <- findFile mk_dyn_lib_path dirs
1050 ; case mb_lib_path of
1051 Just lib_path -> return (DLL (lib ++ "_dyn"))
1052 Nothing -> return (DLL lib) }} -- We assume
1054 mk_obj_path dir = dir `joinFileName` (lib `joinFileExt` "o")
1055 mk_dyn_lib_path dir = dir `joinFileName` mkSOName (lib ++ "_dyn")
1058 -- ----------------------------------------------------------------------------
1059 -- Loading a dyanmic library (dlopen()-ish on Unix, LoadLibrary-ish on Win32)
1061 -- return Nothing == success, else Just error message from dlopen
1062 loadDynamic paths rootname
1063 = do { mb_dll <- findFile mk_dll_path paths
1065 Just dll -> loadDLL dll
1066 Nothing -> loadDLL (mkSOName rootname) }
1067 -- Tried all our known library paths, so let
1068 -- dlopen() search its own builtin paths now.
1070 mk_dll_path dir = dir `joinFileName` mkSOName rootname
1072 #if defined(darwin_TARGET_OS)
1073 mkSOName root = ("lib" ++ root) `joinFileExt` "dylib"
1074 #elif defined(mingw32_TARGET_OS)
1075 -- Win32 DLLs have no .dll extension here, because addDLL tries
1076 -- both foo.dll and foo.drv
1077 mkSOName root = root
1079 mkSOName root = ("lib" ++ root) `joinFileExt` "so"
1082 -- Darwin / MacOS X only: load a framework
1083 -- a framework is a dynamic library packaged inside a directory of the same
1084 -- name. They are searched for in different paths than normal libraries.
1085 #ifdef darwin_TARGET_OS
1086 loadFramework extraPaths rootname
1087 = do { mb_fwk <- findFile mk_fwk (extraPaths ++ defaultFrameworkPaths)
1089 Just fwk_path -> loadDLL fwk_path
1090 Nothing -> return (Just "not found") }
1091 -- Tried all our known library paths, but dlopen()
1092 -- has no built-in paths for frameworks: give up
1094 mk_fwk dir = dir `joinFileName` (rootname ++ ".framework/" ++ rootname)
1095 -- sorry for the hardcoded paths, I hope they won't change anytime soon:
1096 defaultFrameworkPaths = ["/Library/Frameworks", "/System/Library/Frameworks"]
1100 %************************************************************************
1104 %************************************************************************
1107 findFile :: (FilePath -> FilePath) -- Maps a directory path to a file path
1108 -> [FilePath] -- Directories to look in
1109 -> IO (Maybe FilePath) -- The first file path to match
1110 findFile mk_file_path []
1112 findFile mk_file_path (dir:dirs)
1113 = do { let file_path = mk_file_path dir
1114 ; b <- doesFileExist file_path
1116 return (Just file_path)
1118 findFile mk_file_path dirs }
1122 maybePutStr dflags s | verbosity dflags > 0 = putStr s
1123 | otherwise = return ()
1125 maybePutStrLn dflags s | verbosity dflags > 0 = putStrLn s
1126 | otherwise = return ()