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