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