9137031fd97d6787a2ead7669ca0377e0122f97a
[ghc-hetmet.git] / ghc / compiler / ghci / Linker.lhs
1 %
2 % (c) The University of Glasgow 2000
3 %
4
5 -- --------------------------------------
6 --      The dynamic linker for GHCi      
7 -- --------------------------------------
8
9 This module deals with the top-level issues of dynamic linking,
10 calling the object-code linker and the byte-code linker where
11 necessary.
12
13
14 \begin{code}
15
16 {-# OPTIONS -optc-DNON_POSIX_SOURCE -#include "Linker.h" #-}
17
18 module Linker ( HValue, initDynLinker, showLinkerState,
19                 linkExpr, unload, extendLinkEnv, 
20                 linkPackages,
21         ) where
22
23 #include "../includes/config.h"
24 #include "HsVersions.h"
25
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(..))
30
31 import Packages
32 import DriverState      ( v_Library_paths, v_Opt_l, v_Ld_inputs, getStaticOpts, v_ExplicitPackages )
33 import DriverUtil       ( getFileSuffix )
34 #ifdef darwin_TARGET_OS
35 import DriverState      ( v_Cmdline_frameworks, v_Framework_paths )
36 #endif
37 import Finder           ( findModule, findLinkable )
38 import HscTypes
39 import Name             ( Name,  nameModule, isExternalName, isWiredInName )
40 import NameEnv
41 import NameSet          ( nameSetToList )
42 import Module
43 import FastString       ( FastString(..), unpackFS )
44 import ListSetOps       ( minusList )
45 import CmdLineOpts      ( DynFlags(verbosity), getDynFlags )
46 import BasicTypes       ( SuccessFlag(..), succeeded, failed )
47 import Outputable
48 import Panic            ( GhcException(..) )
49 import Util             ( zipLazy, global )
50
51 -- Standard libraries
52 import Control.Monad    ( when, filterM, foldM )
53
54 import Data.IORef       ( IORef, readIORef, writeIORef )
55 import Data.List        ( partition, nub )
56
57 import System.IO        ( putStr, putStrLn, hPutStrLn, stderr, fixIO )
58 import System.Directory ( doesFileExist )
59
60 import Control.Exception ( block, throwDyn )
61
62 #if __GLASGOW_HASKELL__ >= 503
63 import GHC.IOBase       ( IO(..) )
64 #else
65 import PrelIOBase       ( IO(..) )
66 #endif
67 \end{code}
68
69
70 %************************************************************************
71 %*                                                                      *
72                         The Linker's state
73 %*                                                                      *
74 %************************************************************************
75
76 The persistent linker state *must* match the actual state of the 
77 C dynamic linker at all times, so we keep it in a private global variable.
78
79
80 The PersistentLinkerState maps Names to actual closures (for
81 interpreted code only), for use during linking.
82
83 \begin{code}
84 GLOBAL_VAR(v_PersistentLinkerState, panic "Dynamic linker not initialised", PersistentLinkerState)
85 GLOBAL_VAR(v_InitLinkerDone, False, Bool)       -- Set True when dynamic linker is initialised
86
87 data PersistentLinkerState
88    = PersistentLinkerState {
89
90         -- Current global mapping from Names to their true values
91         closure_env :: ClosureEnv,
92
93         -- The current global mapping from RdrNames of DataCons to
94         -- info table addresses.
95         -- When a new Unlinked is linked into the running image, or an existing
96         -- module in the image is replaced, the itbl_env must be updated
97         -- appropriately.
98         itbl_env    :: ItblEnv,
99
100         -- The currently loaded interpreted modules (home package)
101         bcos_loaded :: [Linkable],
102
103         -- And the currently-loaded compiled modules (home package)
104         objs_loaded :: [Linkable],
105
106         -- The currently-loaded packages; always object code
107         -- Held, as usual, in dependency order; though I am not sure if
108         -- that is really important
109         pkgs_loaded :: [PackageName]
110      }
111
112 emptyPLS :: PersistentLinkerState
113 emptyPLS = PersistentLinkerState { closure_env = emptyNameEnv,
114                                    itbl_env    = emptyNameEnv,
115                                    pkgs_loaded = init_pkgs_loaded,
116                                    bcos_loaded = [],
117                                    objs_loaded = [] }
118
119 -- Packages that don't need loading, because the compiler 
120 -- shares them with the interpreted program.
121 --
122 -- The linker's symbol table is populated with RTS symbols using an
123 -- explicit list.  See rts/Linker.c for details.
124 init_pkgs_loaded = [ FSLIT("rts") ]
125 \end{code}
126
127 \begin{code}
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
135
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
141
142 filterNameMap :: [ModuleName] -> NameEnv (Name, a) -> NameEnv (Name, a)
143 filterNameMap mods env 
144    = filterNameEnv keep_elt env
145    where
146      keep_elt (n,_) = isExternalName n 
147                       && (moduleName (nameModule n) `elem` mods)
148 \end{code}
149
150
151 \begin{code}
152 showLinkerState :: IO ()
153 -- Display the persistent linker state
154 showLinkerState
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)])
160 \end{code}
161                         
162         
163
164
165 %************************************************************************
166 %*                                                                      *
167 \subsection{Initialisation}
168 %*                                                                      *
169 %************************************************************************
170
171 We initialise the dynamic linker by
172
173 a) calling the C initialisation procedure
174
175 b) Loading any packages specified on the command line,
176    now held in v_ExplicitPackages
177
178 c) Loading any packages specified on the command line,
179    now held in the -l options in v_Opt_l
180
181 d) Loading any .o/.dll files specified on the command line,
182    now held in v_Ld_inputs
183
184 e) Loading any MacOS frameworks
185
186 \begin{code}
187 initDynLinker :: IO ()
188 -- This function is idempotent; if called more than once, it does nothing
189 -- This is useful in Template Haskell, where we call it before trying to link
190 initDynLinker 
191   = do  { done <- readIORef v_InitLinkerDone
192         ; if done then return () 
193                   else do { writeIORef v_InitLinkerDone True
194                           ; reallyInitDynLinker }
195         }
196
197 reallyInitDynLinker
198   = do  { dflags <- getDynFlags
199
200                 -- Initialise the linker state
201         ; writeIORef v_PersistentLinkerState emptyPLS
202
203                 -- (a) initialise the C dynamic linker
204         ; initObjLinker 
205
206                 -- (b) Load packages from the command-line
207         ; expl <- readIORef v_ExplicitPackages
208         ; linkPackages dflags expl
209
210                 -- (c) Link libraries from the command-line
211         ; opt_l  <- getStaticOpts v_Opt_l
212         ; let minus_ls = [ lib | '-':'l':lib <- opt_l ]
213
214                 -- (d) Link .o files from the command-line
215         ; lib_paths <- readIORef v_Library_paths
216         ; cmdline_ld_inputs <- readIORef v_Ld_inputs
217
218         ; let (cmdline_libs, cmdline_objs) = partition libish cmdline_ld_inputs
219
220                 -- (e) Link any MacOS frameworks
221 #ifdef darwin_TARGET_OS 
222         ; framework_paths <- readIORef v_Framework_paths
223         ; frameworks      <- readIORef v_Cmdline_frameworks
224 #else
225         ; let frameworks      = []
226         ; let framework_paths = []
227 #endif
228                 -- Finally do (c),(d),(e)       
229         ; let cmdline_lib_specs = map Object    cmdline_objs
230                                ++ map DLLPath   cmdline_libs
231                                ++ map DLL       minus_ls 
232                                ++ map Framework frameworks
233         ; if null cmdline_lib_specs then return ()
234                                     else do
235
236         { mapM_ (preloadLib dflags lib_paths framework_paths) cmdline_lib_specs
237         ; maybePutStr dflags "final link ... "
238         ; ok <- resolveObjs
239
240         ; if succeeded ok then maybePutStrLn dflags "done"
241           else throwDyn (InstallationError "linking extra libraries/objects failed")
242         }}
243
244 libish :: String -> Bool
245 libish f = getFileSuffix f `elem` dynlib_suffixes
246
247 #ifdef mingw32_TARGET_OS
248 dynlib_suffixes = ["dll", "DLL"]
249 #else
250 dynlib_suffixes = ["so"]
251 #endif
252
253 preloadLib :: DynFlags -> [String] -> [String] -> LibrarySpec -> IO ()
254 preloadLib dflags lib_paths framework_paths lib_spec
255   = do maybePutStr dflags ("Loading object " ++ showLS lib_spec ++ " ... ")
256        case lib_spec of
257           Object static_ish
258              -> do b <- preload_static lib_paths static_ish
259                    maybePutStrLn dflags (if b  then "done"
260                                                 else "not found")
261          
262           DLL dll_unadorned
263              -> do maybe_errstr <- loadDynamic lib_paths dll_unadorned
264                    case maybe_errstr of
265                       Nothing -> maybePutStrLn dflags "done"
266                       Just mm -> preloadFailed mm lib_paths lib_spec
267
268           DLLPath dll_path
269              -> do maybe_errstr <- loadDLL dll_path
270                    case maybe_errstr of
271                       Nothing -> maybePutStrLn dflags "done"
272                       Just mm -> preloadFailed mm lib_paths lib_spec
273
274 #ifdef darwin_TARGET_OS
275           Framework framework
276              -> do maybe_errstr <- loadFramework framework_paths framework
277                    case maybe_errstr of
278                       Nothing -> maybePutStrLn dflags "done"
279                       Just mm -> preloadFailed mm framework_paths lib_spec
280 #endif
281   where
282     preloadFailed :: String -> [String] -> LibrarySpec -> IO ()
283     preloadFailed sys_errmsg paths spec
284        = do maybePutStr dflags
285                ("failed.\nDynamic linker error message was:\n   " 
286                     ++ sys_errmsg  ++ "\nWhilst trying to load:  " 
287                     ++ showLS spec ++ "\nDirectories to search are:\n"
288                     ++ unlines (map ("   "++) paths) )
289             give_up
290     
291     -- Not interested in the paths in the static case.
292     preload_static paths name
293        = do b <- doesFileExist name
294             if not b then return False
295                      else loadObj name >> return True
296     
297     give_up = throwDyn $ 
298               CmdLineError "user specified .o/.so/.DLL could not be loaded."
299 \end{code}
300
301
302 %************************************************************************
303 %*                                                                      *
304                 Link a byte-code expression
305 %*                                                                      *
306 %************************************************************************
307
308 \begin{code}
309 linkExpr :: HscEnv -> PersistentCompilerState
310          -> UnlinkedBCO -> IO HValue
311
312 -- Link a single expression, *including* first linking packages and 
313 -- modules that this expression depends on.
314 --
315 -- Raises an IO exception if it can't find a compiled version of the
316 -- dependents to link.
317
318 linkExpr hsc_env pcs root_ul_bco
319   = do {  
320         -- Initialise the linker (if it's not been done already)
321      initDynLinker
322
323         -- Find what packages and linkables are required
324    ; (lnks, pkgs) <- getLinkDeps hpt pit needed_mods
325
326         -- Link the packages and modules required
327    ; linkPackages dflags pkgs
328    ; ok <- linkModules dflags lnks
329    ; if failed ok then
330         dieWith empty
331      else do {
332
333         -- Link the expression itself
334      pls <- readIORef v_PersistentLinkerState
335    ; let ie = itbl_env pls
336          ce = closure_env pls
337
338         -- Link the necessary packages and linkables
339    ; (_, (root_hval:_)) <- linkSomeBCOs False ie ce [root_ul_bco]
340    ; return root_hval
341    }}
342    where
343      pit    = eps_PIT (pcs_EPS pcs)
344      hpt    = hsc_HPT hsc_env
345      dflags = hsc_dflags hsc_env
346      free_names = nameSetToList (bcoFreeNames root_ul_bco)
347
348      needed_mods :: [Module]
349      needed_mods = [ nameModule n | n <- free_names, 
350                                     isExternalName n,           -- Names from other modules
351                                     not (isWiredInName n)       -- Exclude wired-in names
352                    ]                                            -- (see note below)
353         -- Exclude wired-in names because we may not have read
354         -- their interface files, so getLinkDeps will fail
355         -- All wired-in names are in the base package, which we link
356         -- by default, so we can safely ignore them here.
357  
358 dieWith msg = throwDyn (ProgramError (showSDoc msg))
359
360 getLinkDeps :: HomePackageTable -> PackageIfaceTable
361             -> [Module]                         -- If you need these
362             -> IO ([Linkable], [PackageName])   -- ... then link these first
363 -- Fails with an IO exception if it can't find enough files
364
365 getLinkDeps hpt pit mods
366 -- Find all the packages and linkables that a set of modules depends on
367  = do { pls <- readIORef v_PersistentLinkerState ;
368         let {
369         -- 1.  Find the dependent home-pkg-modules/packages from each iface
370             (mods_s, pkgs_s) = unzip (map get_deps mods) ;
371
372         -- 2.  Exclude ones already linked
373         --      Main reason: avoid findModule calls in get_linkable
374             mods_needed = nub (concat mods_s) `minusList` linked_mods     ;
375             pkgs_needed = nub (concat pkgs_s) `minusList` pkgs_loaded pls ;
376
377             linked_mods = map linkableModName (objs_loaded pls ++ bcos_loaded pls)
378         } ;
379         
380         -- 3.  For each dependent module, find its linkable
381         --     This will either be in the HPT or (in the case of one-shot
382         --     compilation) we may need to use maybe_getFileLinkable
383         lnks_needed <- mapM get_linkable mods_needed ;
384
385         return (lnks_needed, pkgs_needed) }
386   where
387     get_deps :: Module -> ([ModuleName],[PackageName])
388         -- Get the things needed for the specified module
389         -- This is rather similar to the code in RnNames.importsFromImportDecl
390     get_deps mod
391         | isHomeModule (mi_module iface) 
392         = (moduleName mod : [m | (m,_) <- dep_mods deps], dep_pkgs deps)
393         | otherwise
394         = ([], mi_package iface : dep_pkgs deps)
395         where
396           iface = get_iface mod
397           deps  = mi_deps iface
398
399     get_iface mod = case lookupIface hpt pit mod of
400                             Just iface -> iface
401                             Nothing    -> pprPanic "getLinkDeps" (no_iface mod)
402     no_iface mod = ptext SLIT("No iface for") <+> ppr mod
403         -- This one is a GHC bug
404
405     no_obj mod = dieWith (ptext SLIT("No compiled code for") <+> ppr mod)
406         -- This one is a build-system bug
407
408     get_linkable mod_name       -- A home-package module
409         | Just mod_info <- lookupModuleEnvByName hpt mod_name 
410         = return (hm_linkable mod_info)
411         | otherwise     
412         =       -- It's not in the HPT because we are in one shot mode, 
413                 -- so use the Finder to get a ModLocation...
414           do { mb_stuff <- findModule mod_name ;
415                case mb_stuff of {
416                   Left _ -> no_obj mod_name ;
417                   Right (_, loc) -> do {
418
419                 -- ...and then find the linkable for it
420                mb_lnk <- findLinkable mod_name loc ;
421                case mb_lnk of {
422                   Nothing -> no_obj mod_name ;
423                   Just lnk -> return lnk
424           }}}} 
425 \end{code}
426
427
428 %************************************************************************
429 %*                                                                      *
430                 Link some linkables
431         The linkables may consist of a mixture of 
432         byte-code modules and object modules
433 %*                                                                      *
434 %************************************************************************
435
436 \begin{code}
437 linkModules :: DynFlags -> [Linkable] -> IO SuccessFlag
438 linkModules dflags linkables
439   = block $ do  -- don't want to be interrupted by ^C in here
440         
441         let (objs, bcos) = partition isObjectLinkable 
442                               (concatMap partitionLinkable linkables)
443
444                 -- Load objects first; they can't depend on BCOs
445         ok_flag <- dynLinkObjs dflags objs
446
447         if failed ok_flag then 
448                 return Failed
449           else do
450                 dynLinkBCOs bcos
451                 return Succeeded
452                 
453
454 -- HACK to support f-x-dynamic in the interpreter; no other purpose
455 partitionLinkable :: Linkable -> [Linkable]
456 partitionLinkable li
457    = let li_uls = linkableUnlinked li
458          li_uls_obj = filter isObject li_uls
459          li_uls_bco = filter isInterpretable li_uls
460      in 
461          case (li_uls_obj, li_uls_bco) of
462             (objs@(_:_), bcos@(_:_)) 
463                -> [li{linkableUnlinked=li_uls_obj}, li{linkableUnlinked=li_uls_bco}]
464             other
465                -> [li]
466
467 findModuleLinkable_maybe :: [Linkable] -> ModuleName -> Maybe Linkable
468 findModuleLinkable_maybe lis mod
469    = case [LM time nm us | LM time nm us <- lis, nm == mod] of
470         []   -> Nothing
471         [li] -> Just li
472         many -> pprPanic "findModuleLinkable" (ppr mod)
473
474 filterModuleLinkables :: (ModuleName -> Bool) -> [Linkable] -> [Linkable]
475 filterModuleLinkables p ls = filter (p . linkableModName) ls
476
477 linkableInSet :: Linkable -> [Linkable] -> Bool
478 linkableInSet l objs_loaded =
479   case findModuleLinkable_maybe objs_loaded (linkableModName l) of
480         Nothing -> False
481         Just m  -> linkableTime l == linkableTime m
482 \end{code}
483
484
485 %************************************************************************
486 %*                                                                      *
487 \subsection{The object-code linker}
488 %*                                                                      *
489 %************************************************************************
490
491 \begin{code}
492 dynLinkObjs :: DynFlags -> [Linkable] -> IO SuccessFlag
493         -- Side-effects the PersistentLinkerState
494
495 dynLinkObjs dflags objs
496   = do  pls <- readIORef v_PersistentLinkerState
497
498         -- Load the object files and link them
499         let (objs_loaded', new_objs) = rmDupLinkables (objs_loaded pls) objs
500             pls1                     = pls { objs_loaded = objs_loaded' }
501             unlinkeds                = concatMap linkableUnlinked new_objs
502
503         mapM loadObj (map nameOfObject unlinkeds)
504
505         -- Link the all together
506         ok <- resolveObjs
507
508         -- If resolving failed, unload all our 
509         -- object modules and carry on
510         if succeeded ok then do
511                 writeIORef v_PersistentLinkerState pls1
512                 return Succeeded
513           else do
514                 pls2 <- unload_wkr dflags [] pls1
515                 writeIORef v_PersistentLinkerState pls2
516                 return Failed
517
518
519 rmDupLinkables :: [Linkable]    -- Already loaded
520                -> [Linkable]    -- New linkables
521                -> ([Linkable],  -- New loaded set (including new ones)
522                    [Linkable])  -- New linkables (excluding dups)
523 rmDupLinkables already ls
524   = go already [] ls
525   where
526     go already extras [] = (already, extras)
527     go already extras (l:ls)
528         | linkableInSet l already = go already     extras     ls
529         | otherwise               = go (l:already) (l:extras) ls
530 \end{code}
531
532 %************************************************************************
533 %*                                                                      *
534 \subsection{The byte-code linker}
535 %*                                                                      *
536 %************************************************************************
537
538 \begin{code}
539 dynLinkBCOs :: [Linkable] -> IO ()
540         -- Side-effects the persistent linker state
541 dynLinkBCOs bcos
542   = do  pls <- readIORef v_PersistentLinkerState
543
544         let (bcos_loaded', new_bcos) = rmDupLinkables (bcos_loaded pls) bcos
545             pls1                     = pls { bcos_loaded = bcos_loaded' }
546             unlinkeds :: [Unlinked]
547             unlinkeds                = concatMap linkableUnlinked new_bcos
548
549             cbcs :: [CompiledByteCode]
550             cbcs      = map byteCodeOfObject unlinkeds
551                       
552                       
553             ul_bcos    = [b | ByteCode bs _  <- cbcs, b <- bs]
554             ies        = [ie | ByteCode _ ie <- cbcs]
555             gce       = closure_env pls
556             final_ie  = foldr plusNameEnv (itbl_env pls) ies
557
558         (final_gce, linked_bcos) <- linkSomeBCOs True final_ie gce ul_bcos
559                 -- What happens to these linked_bcos?
560
561         let pls2 = pls1 { closure_env = final_gce,
562                           itbl_env    = final_ie }
563
564         writeIORef v_PersistentLinkerState pls2
565         return ()
566
567 -- Link a bunch of BCOs and return them + updated closure env.
568 linkSomeBCOs :: Bool    -- False <=> add _all_ BCOs to returned closure env
569                         -- True  <=> add only toplevel BCOs to closure env
570              -> ItblEnv 
571              -> ClosureEnv 
572              -> [UnlinkedBCO]
573              -> IO (ClosureEnv, [HValue])
574                         -- The returned HValues are associated 1-1 with
575                         -- the incoming unlinked BCOs.  Each gives the
576                         -- value of the corresponding unlinked BCO
577                                         
578
579 linkSomeBCOs toplevs_only ie ce_in ul_bcos
580    = do let nms = map unlinkedBCOName ul_bcos
581         hvals <- fixIO 
582                     ( \ hvs -> let ce_out = extendClosureEnv ce_in (zipLazy nms hvs)
583                                in  mapM (linkBCO ie ce_out) ul_bcos )
584
585         let ce_all_additions = zip nms hvals
586             ce_top_additions = filter (isExternalName.fst) ce_all_additions
587             ce_additions     = if toplevs_only then ce_top_additions 
588                                                else ce_all_additions
589             ce_out = -- make sure we're not inserting duplicate names into the 
590                      -- closure environment, which leads to trouble.
591                      ASSERT (all (not . (`elemNameEnv` ce_in)) (map fst ce_additions))
592                      extendClosureEnv ce_in ce_additions
593         return (ce_out, hvals)
594
595 \end{code}
596
597
598 %************************************************************************
599 %*                                                                      *
600                 Unload some object modules
601 %*                                                                      *
602 %************************************************************************
603
604 \begin{code}
605 -- ---------------------------------------------------------------------------
606 -- Unloading old objects ready for a new compilation sweep.
607 --
608 -- The compilation manager provides us with a list of linkables that it
609 -- considers "stable", i.e. won't be recompiled this time around.  For
610 -- each of the modules current linked in memory,
611 --
612 --      * if the linkable is stable (and it's the same one - the
613 --        user may have recompiled the module on the side), we keep it,
614 --
615 --      * otherwise, we unload it.
616 --
617 --      * we also implicitly unload all temporary bindings at this point.
618
619 unload :: DynFlags -> [Linkable] -> IO ()
620 -- The 'linkables' are the ones to *keep*
621
622 unload dflags linkables
623   = block $ do -- block, so we're safe from Ctrl-C in here
624
625         pls     <- readIORef v_PersistentLinkerState
626         new_pls <- unload_wkr dflags linkables pls
627         writeIORef v_PersistentLinkerState new_pls
628
629         let verb = verbosity dflags
630         when (verb >= 3) $ do
631             hPutStrLn stderr (showSDoc
632                 (text "unload: retaining objs" <+> ppr (objs_loaded new_pls)))
633             hPutStrLn stderr (showSDoc
634                 (text "unload: retaining bcos" <+> ppr (bcos_loaded new_pls)))
635
636         return ()
637
638 unload_wkr :: DynFlags
639            -> [Linkable]                -- stable linkables
640            -> PersistentLinkerState
641            -> IO PersistentLinkerState
642 -- Does the core unload business
643 -- (the wrapper blocks exceptions and deals with the PLS get and put)
644
645 unload_wkr dflags linkables pls
646   = do  let (objs_to_keep, bcos_to_keep) = partition isObjectLinkable linkables
647
648         objs_loaded' <- filterM (maybeUnload objs_to_keep) (objs_loaded pls)
649         bcos_loaded' <- filterM (maybeUnload bcos_to_keep) (bcos_loaded pls)
650
651         let objs_retained = map linkableModName objs_loaded'
652             bcos_retained = map linkableModName bcos_loaded'
653             itbl_env'     = filterNameMap bcos_retained (itbl_env pls)
654             closure_env'  = filterNameMap bcos_retained (closure_env pls)
655             new_pls = pls { itbl_env = itbl_env',
656                             closure_env = closure_env',
657                             bcos_loaded = bcos_loaded',
658                             objs_loaded = objs_loaded' }
659
660         return new_pls
661   where
662     maybeUnload :: [Linkable] -> Linkable -> IO Bool
663     maybeUnload keep_linkables lnk
664       | linkableInSet lnk linkables = return True
665       | otherwise                   
666       = do mapM_ unloadObj [f | DotO f <- linkableUnlinked lnk]
667                 -- The components of a BCO linkable may contain
668                 -- dot-o files.  Which is very confusing.
669                 --
670                 -- But the BCO parts can be unlinked just by 
671                 -- letting go of them (plus of course depopulating
672                 -- the symbol table which is done in the main body)
673            return False
674 \end{code}
675
676
677 %************************************************************************
678 %*                                                                      *
679                 Loading packages
680 %*                                                                      *
681 %************************************************************************
682
683
684 \begin{code}
685 data LibrarySpec 
686    = Object FilePath    -- Full path name of a .o file, including trailing .o
687                         -- For dynamic objects only, try to find the object 
688                         -- file in all the directories specified in 
689                         -- v_Library_paths before giving up.
690
691    | DLL String         -- "Unadorned" name of a .DLL/.so
692                         --  e.g.    On unix     "qt"  denotes "libqt.so"
693                         --          On WinDoze  "burble"  denotes "burble.DLL"
694                         --  loadDLL is platform-specific and adds the lib/.so/.DLL
695                         --  suffixes platform-dependently
696
697    | DLLPath FilePath   -- Absolute or relative pathname to a dynamic library
698                         -- (ends with .dll or .so).
699
700    | Framework String   -- Only used for darwin, but does no harm
701
702 -- If this package is already part of the GHCi binary, we'll already
703 -- have the right DLLs for this package loaded, so don't try to
704 -- load them again.
705 -- 
706 -- But on Win32 we must load them 'again'; doing so is a harmless no-op
707 -- as far as the loader is concerned, but it does initialise the list
708 -- of DLL handles that rts/Linker.c maintains, and that in turn is 
709 -- used by lookupSymbol.  So we must call addDLL for each library 
710 -- just to get the DLL handle into the list.
711 partOfGHCi
712 #          if defined(mingw32_TARGET_OS) || defined(darwin_TARGET_OS)
713            = [ ]
714 #          else
715            = [ "base", "haskell98", "haskell-src", "readline" ]
716 #          endif
717
718 showLS (Object nm)    = "(static) " ++ nm
719 showLS (DLL nm)       = "(dynamic) " ++ nm
720 showLS (DLLPath nm)   = "(dynamic) " ++ nm
721 showLS (Framework nm) = "(framework) " ++ nm
722
723 linkPackages :: DynFlags -> [PackageName] -> IO ()
724 -- Link exactly the specified packages, and their dependents
725 -- (unless of course they are already linked)
726 -- The dependents are linked automatically, and it doesn't matter
727 -- what order you specify the input packages.
728 --
729 -- NOTE: in fact, since each module tracks all the packages it depends on,
730 --       we don't really need to use the package-config dependencies.
731 -- However we do need the package-config stuff (to find aux libs etc),
732 -- and following them lets us load libraries in the right order, which 
733 -- perhaps makes the error message a bit more localised if we get a link
734 -- failure.  So the dependency walking code is still here.
735
736 linkPackages dflags new_pkgs
737    = do { pls     <- readIORef v_PersistentLinkerState
738         ; pkg_map <- getPackageConfigMap
739
740         ; pkgs' <- link pkg_map (pkgs_loaded pls) new_pkgs
741
742         ; writeIORef v_PersistentLinkerState (pls { pkgs_loaded = pkgs' })
743         }
744    where
745      link :: PackageConfigMap -> [PackageName] -> [PackageName] -> IO [PackageName]
746      link pkg_map pkgs new_pkgs 
747         = foldM (link_one pkg_map) pkgs new_pkgs
748
749      link_one pkg_map pkgs new_pkg
750         | new_pkg `elem` pkgs   -- Already linked
751         = return pkgs
752
753         | Just pkg_cfg <- lookupPkg pkg_map new_pkg
754         = do {  -- Link dependents first
755                pkgs' <- link pkg_map pkgs (packageDependents pkg_cfg)
756                 -- Now link the package itself
757              ; linkPackage dflags pkg_cfg
758              ; return (new_pkg : pkgs') }
759
760         | otherwise
761         = throwDyn (CmdLineError ("unknown package name: " ++ packageNameString new_pkg))
762
763
764 linkPackage :: DynFlags -> PackageConfig -> IO ()
765 linkPackage dflags pkg
766    = do 
767         let dirs      =  Packages.library_dirs pkg
768         let libs      =  Packages.hs_libraries pkg ++ extra_libraries pkg
769                                 ++ [ lib | '-':'l':lib <- extra_ld_opts pkg ]
770         classifieds   <- mapM (locateOneObj dirs) libs
771
772         -- Complication: all the .so's must be loaded before any of the .o's.  
773         let dlls = [ dll | DLL dll    <- classifieds ]
774             objs = [ obj | Object obj <- classifieds ]
775
776         maybePutStr dflags ("Loading package " ++ Packages.name pkg ++ " ... ")
777
778         -- See comments with partOfGHCi
779         when (Packages.name pkg `notElem` partOfGHCi) $ do
780             loadFrameworks pkg
781             mapM_ (load_dyn dirs) dlls
782         
783         -- After loading all the DLLs, we can load the static objects.
784         mapM_ loadObj objs
785
786         maybePutStr dflags "linking ... "
787         ok <- resolveObjs
788         if succeeded ok then maybePutStrLn dflags "done."
789               else panic ("can't load package `" ++ name pkg ++ "'")
790
791 load_dyn dirs dll = do r <- loadDynamic dirs dll
792                        case r of
793                          Nothing  -> return ()
794                          Just err -> throwDyn (CmdLineError ("can't load .so/.DLL for: " 
795                                                               ++ dll ++ " (" ++ err ++ ")" ))
796 #ifndef darwin_TARGET_OS
797 loadFrameworks pkg = return ()
798 #else
799 loadFrameworks pkg = mapM_ load frameworks
800   where
801     fw_dirs    = Packages.framework_dirs pkg
802     frameworks = Packages.extra_frameworks pkg
803
804     load fw = do  r <- loadFramework fw_dirs fw
805                   case r of
806                     Nothing  -> return ()
807                     Just err -> throwDyn (CmdLineError ("can't load framework: " 
808                                                         ++ fw ++ " (" ++ err ++ ")" ))
809 #endif
810
811 -- Try to find an object file for a given library in the given paths.
812 -- If it isn't present, we assume it's a dynamic library.
813 locateOneObj :: [FilePath] -> String -> IO LibrarySpec
814 locateOneObj dirs lib
815   = do  { mb_obj_path <- findFile mk_obj_path dirs 
816         ; case mb_obj_path of
817             Just obj_path -> return (Object obj_path)
818             Nothing       -> return (DLL lib) }         -- We assume
819    where
820      mk_obj_path dir = dir ++ '/':lib ++ ".o"
821
822
823 -- ----------------------------------------------------------------------------
824 -- Loading a dyanmic library (dlopen()-ish on Unix, LoadLibrary-ish on Win32)
825
826 -- return Nothing == success, else Just error message from dlopen
827 loadDynamic paths rootname
828   = do  { mb_dll <- findFile mk_dll_path paths
829         ; case mb_dll of
830             Just dll -> loadDLL dll
831             Nothing  -> loadDLL (mkSOName rootname) }
832                         -- Tried all our known library paths, so let 
833                         -- dlopen() search its own builtin paths now.
834   where
835     mk_dll_path dir = dir ++ '/':mkSOName rootname
836
837 #if defined(darwin_TARGET_OS)
838 mkSOName root = "lib" ++ root ++ ".dylib"
839 #elif defined(mingw32_TARGET_OS)
840 -- Win32 DLLs have no .dll extension here, because addDLL tries
841 -- both foo.dll and foo.drv
842 mkSOName root = root
843 #else
844 mkSOName root = "lib" ++ root ++ ".so"
845 #endif
846
847 -- Darwin / MacOS X only: load a framework
848 -- a framework is a dynamic library packaged inside a directory of the same
849 -- name. They are searched for in different paths than normal libraries.
850 #ifdef darwin_TARGET_OS
851 loadFramework extraPaths rootname
852    = do { mb_fwk <- findFile mk_fwk (extraPaths ++ defaultFrameworkPaths)
853         ; case mb_fwk of
854             Just fwk_path -> loadDLL fwk_path
855             Nothing       -> return (Just "not found") }
856                 -- Tried all our known library paths, but dlopen()
857                 -- has no built-in paths for frameworks: give up
858    where
859      mk_fwk dir = dir ++ '/' : rootname ++ ".framework/" ++ rootname
860         -- sorry for the hardcoded paths, I hope they won't change anytime soon:
861      defaultFrameworkPaths = ["/Library/Frameworks", "/System/Library/Frameworks"]
862 #endif
863 \end{code}
864
865 %************************************************************************
866 %*                                                                      *
867                 Helper functions
868 %*                                                                      *
869 %************************************************************************
870
871 \begin{code}
872 findFile :: (FilePath -> FilePath)      -- Maps a directory path to a file path
873          -> [FilePath]                  -- Directories to look in
874          -> IO (Maybe FilePath)         -- The first file path to match
875 findFile mk_file_path [] 
876   = return Nothing
877 findFile mk_file_path (dir:dirs)
878   = do  { let file_path = mk_file_path dir
879         ; b <- doesFileExist file_path
880         ; if b then 
881              return (Just file_path)
882           else
883              findFile mk_file_path dirs }
884 \end{code}
885
886 \begin{code}
887 maybePutStr dflags s | verbosity dflags > 0 = putStr s
888                      | otherwise            = return ()
889
890 maybePutStrLn dflags s | verbosity dflags > 0 = putStrLn s
891                        | otherwise            = return ()
892 \end{code}