cbb6b6b0f58dfd67e32a9fa25f48019c49b60da9
[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, v_ExplicitPackages )
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 )
39 import HscTypes
40 import Name             ( Name, nameModule, nameModuleName, isExternalName, isWiredInName )
41 import NameEnv
42 import NameSet          ( nameSetToList )
43 import Module
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                       && (nameModuleName 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         ; 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      initDynLinker
319
320         -- Find what packages and linkables are required
321    ; eps <- readIORef (hsc_EPS hsc_env)
322    ; (lnks, pkgs) <- getLinkDeps 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 :: HomePackageTable -> PackageIfaceTable
358             -> [Module]                         -- If you need these
359             -> IO ([Linkable], [PackageName])   -- ... then link these first
360 -- Fails with an IO exception if it can't find enough files
361
362 getLinkDeps 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 linkableModName (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 -> ([ModuleName],[PackageName])
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         | isHomeModule (mi_module iface) 
389         = (moduleName mod : [m | (m,_) <- dep_mods deps], dep_pkgs deps)
390         | otherwise
391         = ([], mi_package iface : 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 <- lookupModuleEnvByName 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 mod_name ;
412                case mb_stuff of {
413                   Left _ -> no_obj mod_name ;
414                   Right (_, loc) -> do {
415
416                 -- ...and then find the linkable for it
417                mb_lnk <- findLinkable mod_name loc ;
418                case mb_lnk of {
419                   Nothing -> no_obj mod_name ;
420                   Just lnk -> return lnk
421           }}}} 
422 \end{code}
423
424
425 %************************************************************************
426 %*                                                                      *
427                 Link some linkables
428         The linkables may consist of a mixture of 
429         byte-code modules and object modules
430 %*                                                                      *
431 %************************************************************************
432
433 \begin{code}
434 linkModules :: DynFlags -> [Linkable] -> IO SuccessFlag
435 linkModules dflags linkables
436   = block $ do  -- don't want to be interrupted by ^C in here
437         
438         let (objs, bcos) = partition isObjectLinkable 
439                               (concatMap partitionLinkable linkables)
440
441                 -- Load objects first; they can't depend on BCOs
442         ok_flag <- dynLinkObjs dflags objs
443
444         if failed ok_flag then 
445                 return Failed
446           else do
447                 dynLinkBCOs bcos
448                 return Succeeded
449                 
450
451 -- HACK to support f-x-dynamic in the interpreter; no other purpose
452 partitionLinkable :: Linkable -> [Linkable]
453 partitionLinkable li
454    = let li_uls = linkableUnlinked li
455          li_uls_obj = filter isObject li_uls
456          li_uls_bco = filter isInterpretable li_uls
457      in 
458          case (li_uls_obj, li_uls_bco) of
459             (objs@(_:_), bcos@(_:_)) 
460                -> [li{linkableUnlinked=li_uls_obj}, li{linkableUnlinked=li_uls_bco}]
461             other
462                -> [li]
463
464 findModuleLinkable_maybe :: [Linkable] -> ModuleName -> Maybe Linkable
465 findModuleLinkable_maybe lis mod
466    = case [LM time nm us | LM time nm us <- lis, nm == mod] of
467         []   -> Nothing
468         [li] -> Just li
469         many -> pprPanic "findModuleLinkable" (ppr mod)
470
471 linkableInSet :: Linkable -> [Linkable] -> Bool
472 linkableInSet l objs_loaded =
473   case findModuleLinkable_maybe objs_loaded (linkableModName l) of
474         Nothing -> False
475         Just m  -> linkableTime l == linkableTime m
476 \end{code}
477
478
479 %************************************************************************
480 %*                                                                      *
481 \subsection{The object-code linker}
482 %*                                                                      *
483 %************************************************************************
484
485 \begin{code}
486 dynLinkObjs :: DynFlags -> [Linkable] -> IO SuccessFlag
487         -- Side-effects the PersistentLinkerState
488
489 dynLinkObjs dflags objs
490   = do  pls <- readIORef v_PersistentLinkerState
491
492         -- Load the object files and link them
493         let (objs_loaded', new_objs) = rmDupLinkables (objs_loaded pls) objs
494             pls1                     = pls { objs_loaded = objs_loaded' }
495             unlinkeds                = concatMap linkableUnlinked new_objs
496
497         mapM loadObj (map nameOfObject unlinkeds)
498
499         -- Link the all together
500         ok <- resolveObjs
501
502         -- If resolving failed, unload all our 
503         -- object modules and carry on
504         if succeeded ok then do
505                 writeIORef v_PersistentLinkerState pls1
506                 return Succeeded
507           else do
508                 pls2 <- unload_wkr dflags [] pls1
509                 writeIORef v_PersistentLinkerState pls2
510                 return Failed
511
512
513 rmDupLinkables :: [Linkable]    -- Already loaded
514                -> [Linkable]    -- New linkables
515                -> ([Linkable],  -- New loaded set (including new ones)
516                    [Linkable])  -- New linkables (excluding dups)
517 rmDupLinkables already ls
518   = go already [] ls
519   where
520     go already extras [] = (already, extras)
521     go already extras (l:ls)
522         | linkableInSet l already = go already     extras     ls
523         | otherwise               = go (l:already) (l:extras) ls
524 \end{code}
525
526 %************************************************************************
527 %*                                                                      *
528 \subsection{The byte-code linker}
529 %*                                                                      *
530 %************************************************************************
531
532 \begin{code}
533 dynLinkBCOs :: [Linkable] -> IO ()
534         -- Side-effects the persistent linker state
535 dynLinkBCOs bcos
536   = do  pls <- readIORef v_PersistentLinkerState
537
538         let (bcos_loaded', new_bcos) = rmDupLinkables (bcos_loaded pls) bcos
539             pls1                     = pls { bcos_loaded = bcos_loaded' }
540             unlinkeds :: [Unlinked]
541             unlinkeds                = concatMap linkableUnlinked new_bcos
542
543             cbcs :: [CompiledByteCode]
544             cbcs      = map byteCodeOfObject unlinkeds
545                       
546                       
547             ul_bcos    = [b | ByteCode bs _  <- cbcs, b <- bs]
548             ies        = [ie | ByteCode _ ie <- cbcs]
549             gce       = closure_env pls
550             final_ie  = foldr plusNameEnv (itbl_env pls) ies
551
552         (final_gce, linked_bcos) <- linkSomeBCOs True final_ie gce ul_bcos
553                 -- What happens to these linked_bcos?
554
555         let pls2 = pls1 { closure_env = final_gce,
556                           itbl_env    = final_ie }
557
558         writeIORef v_PersistentLinkerState pls2
559         return ()
560
561 -- Link a bunch of BCOs and return them + updated closure env.
562 linkSomeBCOs :: Bool    -- False <=> add _all_ BCOs to returned closure env
563                         -- True  <=> add only toplevel BCOs to closure env
564              -> ItblEnv 
565              -> ClosureEnv 
566              -> [UnlinkedBCO]
567              -> IO (ClosureEnv, [HValue])
568                         -- The returned HValues are associated 1-1 with
569                         -- the incoming unlinked BCOs.  Each gives the
570                         -- value of the corresponding unlinked BCO
571                                         
572
573 linkSomeBCOs toplevs_only ie ce_in ul_bcos
574    = do let nms = map unlinkedBCOName ul_bcos
575         hvals <- fixIO 
576                     ( \ hvs -> let ce_out = extendClosureEnv ce_in (zipLazy nms hvs)
577                                in  mapM (linkBCO ie ce_out) ul_bcos )
578
579         let ce_all_additions = zip nms hvals
580             ce_top_additions = filter (isExternalName.fst) ce_all_additions
581             ce_additions     = if toplevs_only then ce_top_additions 
582                                                else ce_all_additions
583             ce_out = -- make sure we're not inserting duplicate names into the 
584                      -- closure environment, which leads to trouble.
585                      ASSERT (all (not . (`elemNameEnv` ce_in)) (map fst ce_additions))
586                      extendClosureEnv ce_in ce_additions
587         return (ce_out, hvals)
588
589 \end{code}
590
591
592 %************************************************************************
593 %*                                                                      *
594                 Unload some object modules
595 %*                                                                      *
596 %************************************************************************
597
598 \begin{code}
599 -- ---------------------------------------------------------------------------
600 -- Unloading old objects ready for a new compilation sweep.
601 --
602 -- The compilation manager provides us with a list of linkables that it
603 -- considers "stable", i.e. won't be recompiled this time around.  For
604 -- each of the modules current linked in memory,
605 --
606 --      * if the linkable is stable (and it's the same one - the
607 --        user may have recompiled the module on the side), we keep it,
608 --
609 --      * otherwise, we unload it.
610 --
611 --      * we also implicitly unload all temporary bindings at this point.
612
613 unload :: DynFlags -> [Linkable] -> IO ()
614 -- The 'linkables' are the ones to *keep*
615
616 unload dflags linkables
617   = block $ do -- block, so we're safe from Ctrl-C in here
618
619         pls     <- readIORef v_PersistentLinkerState
620         new_pls <- unload_wkr dflags linkables pls
621         writeIORef v_PersistentLinkerState new_pls
622
623         let verb = verbosity dflags
624         when (verb >= 3) $ do
625             hPutStrLn stderr (showSDoc
626                 (text "unload: retaining objs" <+> ppr (objs_loaded new_pls)))
627             hPutStrLn stderr (showSDoc
628                 (text "unload: retaining bcos" <+> ppr (bcos_loaded new_pls)))
629
630         return ()
631
632 unload_wkr :: DynFlags
633            -> [Linkable]                -- stable linkables
634            -> PersistentLinkerState
635            -> IO PersistentLinkerState
636 -- Does the core unload business
637 -- (the wrapper blocks exceptions and deals with the PLS get and put)
638
639 unload_wkr dflags linkables pls
640   = do  let (objs_to_keep, bcos_to_keep) = partition isObjectLinkable linkables
641
642         objs_loaded' <- filterM (maybeUnload objs_to_keep) (objs_loaded pls)
643         bcos_loaded' <- filterM (maybeUnload bcos_to_keep) (bcos_loaded pls)
644
645         let bcos_retained = map linkableModName bcos_loaded'
646             itbl_env'     = filterNameMap bcos_retained (itbl_env pls)
647             closure_env'  = filterNameMap bcos_retained (closure_env pls)
648             new_pls = pls { itbl_env = itbl_env',
649                             closure_env = closure_env',
650                             bcos_loaded = bcos_loaded',
651                             objs_loaded = objs_loaded' }
652
653         return new_pls
654   where
655     maybeUnload :: [Linkable] -> Linkable -> IO Bool
656     maybeUnload keep_linkables lnk
657       | linkableInSet lnk linkables = return True
658       | otherwise                   
659       = do mapM_ unloadObj [f | DotO f <- linkableUnlinked lnk]
660                 -- The components of a BCO linkable may contain
661                 -- dot-o files.  Which is very confusing.
662                 --
663                 -- But the BCO parts can be unlinked just by 
664                 -- letting go of them (plus of course depopulating
665                 -- the symbol table which is done in the main body)
666            return False
667 \end{code}
668
669
670 %************************************************************************
671 %*                                                                      *
672                 Loading packages
673 %*                                                                      *
674 %************************************************************************
675
676
677 \begin{code}
678 data LibrarySpec 
679    = Object FilePath    -- Full path name of a .o file, including trailing .o
680                         -- For dynamic objects only, try to find the object 
681                         -- file in all the directories specified in 
682                         -- v_Library_paths before giving up.
683
684    | DLL String         -- "Unadorned" name of a .DLL/.so
685                         --  e.g.    On unix     "qt"  denotes "libqt.so"
686                         --          On WinDoze  "burble"  denotes "burble.DLL"
687                         --  loadDLL is platform-specific and adds the lib/.so/.DLL
688                         --  suffixes platform-dependently
689
690    | DLLPath FilePath   -- Absolute or relative pathname to a dynamic library
691                         -- (ends with .dll or .so).
692
693    | Framework String   -- Only used for darwin, but does no harm
694
695 -- If this package is already part of the GHCi binary, we'll already
696 -- have the right DLLs for this package loaded, so don't try to
697 -- load them again.
698 -- 
699 -- But on Win32 we must load them 'again'; doing so is a harmless no-op
700 -- as far as the loader is concerned, but it does initialise the list
701 -- of DLL handles that rts/Linker.c maintains, and that in turn is 
702 -- used by lookupSymbol.  So we must call addDLL for each library 
703 -- just to get the DLL handle into the list.
704 partOfGHCi
705 #          if defined(mingw32_TARGET_OS) || defined(darwin_TARGET_OS)
706            = [ ]
707 #          else
708            = [ "base", "haskell98", "template-haskell", "readline" ]
709 #          endif
710
711 showLS (Object nm)    = "(static) " ++ nm
712 showLS (DLL nm)       = "(dynamic) " ++ nm
713 showLS (DLLPath nm)   = "(dynamic) " ++ nm
714 showLS (Framework nm) = "(framework) " ++ nm
715
716 linkPackages :: DynFlags -> [PackageName] -> IO ()
717 -- Link exactly the specified packages, and their dependents
718 -- (unless of course they are already linked)
719 -- The dependents are linked automatically, and it doesn't matter
720 -- what order you specify the input packages.
721 --
722 -- NOTE: in fact, since each module tracks all the packages it depends on,
723 --       we don't really need to use the package-config dependencies.
724 -- However we do need the package-config stuff (to find aux libs etc),
725 -- and following them lets us load libraries in the right order, which 
726 -- perhaps makes the error message a bit more localised if we get a link
727 -- failure.  So the dependency walking code is still here.
728
729 linkPackages dflags new_pkgs
730    = do { pls     <- readIORef v_PersistentLinkerState
731         ; pkg_map <- getPackageConfigMap
732
733         ; pkgs' <- link pkg_map (pkgs_loaded pls) new_pkgs
734
735         ; writeIORef v_PersistentLinkerState (pls { pkgs_loaded = pkgs' })
736         }
737    where
738      link :: PackageConfigMap -> [PackageName] -> [PackageName] -> IO [PackageName]
739      link pkg_map pkgs new_pkgs 
740         = foldM (link_one pkg_map) pkgs new_pkgs
741
742      link_one pkg_map pkgs new_pkg
743         | new_pkg `elem` pkgs   -- Already linked
744         = return pkgs
745
746         | Just pkg_cfg <- lookupPkg pkg_map new_pkg
747         = do {  -- Link dependents first
748                pkgs' <- link pkg_map pkgs (packageDependents pkg_cfg)
749                 -- Now link the package itself
750              ; linkPackage dflags pkg_cfg
751              ; return (new_pkg : pkgs') }
752
753         | otherwise
754         = throwDyn (CmdLineError ("unknown package name: " ++ packageNameString new_pkg))
755
756
757 linkPackage :: DynFlags -> PackageConfig -> IO ()
758 linkPackage dflags pkg
759    = do 
760         let dirs      =  Packages.libraryDirs pkg
761         let libs      =  Packages.hsLibraries pkg ++ Packages.extraLibraries pkg
762                                 ++ [ lib | '-':'l':lib <- Packages.extraLdOpts pkg ]
763         classifieds   <- mapM (locateOneObj dirs) libs
764
765         -- Complication: all the .so's must be loaded before any of the .o's.  
766         let dlls = [ dll | DLL dll    <- classifieds ]
767             objs = [ obj | Object obj <- classifieds ]
768
769         maybePutStr dflags ("Loading package " ++ showPackageId (package pkg) ++ " ... ")
770
771         -- See comments with partOfGHCi
772         when (pkgName (package pkg) `notElem` partOfGHCi) $ do
773             loadFrameworks pkg
774             -- When a library A needs symbols from a library B, the order in
775             -- extra_libraries/extra_ld_opts is "-lA -lB", because that's the
776             -- way ld expects it for static linking. Dynamic linking is a
777             -- different story: When A has no dependency information for B,
778             -- dlopen-ing A with RTLD_NOW (see addDLL in Linker.c) will fail
779             -- when B has not been loaded before. In a nutshell: Reverse the
780             -- order of DLLs for dynamic linking.
781             -- This fixes a problem with the HOpenGL package (see "Compiling
782             -- HOpenGL under recent versions of GHC" on the HOpenGL list).
783             mapM_ (load_dyn dirs) (reverse dlls)
784         
785         -- After loading all the DLLs, we can load the static objects.
786         -- Ordering isn't important here, because we do one final link
787         -- step to resolve everything.
788         mapM_ loadObj objs
789
790         maybePutStr dflags "linking ... "
791         ok <- resolveObjs
792         if succeeded ok then maybePutStrLn dflags "done."
793               else throwDyn (InstallationError ("unable to load package `" ++ showPackageId (package pkg) ++ "'"))
794
795 load_dyn dirs dll = do r <- loadDynamic dirs dll
796                        case r of
797                          Nothing  -> return ()
798                          Just err -> throwDyn (CmdLineError ("can't load .so/.DLL for: " 
799                                                               ++ dll ++ " (" ++ err ++ ")" ))
800 #ifndef darwin_TARGET_OS
801 loadFrameworks pkg = return ()
802 #else
803 loadFrameworks pkg = mapM_ load frameworks
804   where
805     fw_dirs    = Packages.framework_dirs pkg
806     frameworks = Packages.extra_frameworks pkg
807
808     load fw = do  r <- loadFramework fw_dirs fw
809                   case r of
810                     Nothing  -> return ()
811                     Just err -> throwDyn (CmdLineError ("can't load framework: " 
812                                                         ++ fw ++ " (" ++ err ++ ")" ))
813 #endif
814
815 -- Try to find an object file for a given library in the given paths.
816 -- If it isn't present, we assume it's a dynamic library.
817 locateOneObj :: [FilePath] -> String -> IO LibrarySpec
818 locateOneObj dirs lib
819   = do  { mb_obj_path <- findFile mk_obj_path dirs 
820         ; case mb_obj_path of
821             Just obj_path -> return (Object obj_path)
822             Nothing       -> return (DLL lib) }         -- We assume
823    where
824      mk_obj_path dir = dir ++ '/':lib ++ ".o"
825
826
827 -- ----------------------------------------------------------------------------
828 -- Loading a dyanmic library (dlopen()-ish on Unix, LoadLibrary-ish on Win32)
829
830 -- return Nothing == success, else Just error message from dlopen
831 loadDynamic paths rootname
832   = do  { mb_dll <- findFile mk_dll_path paths
833         ; case mb_dll of
834             Just dll -> loadDLL dll
835             Nothing  -> loadDLL (mkSOName rootname) }
836                         -- Tried all our known library paths, so let 
837                         -- dlopen() search its own builtin paths now.
838   where
839     mk_dll_path dir = dir ++ '/':mkSOName rootname
840
841 #if defined(darwin_TARGET_OS)
842 mkSOName root = "lib" ++ root ++ ".dylib"
843 #elif defined(mingw32_TARGET_OS)
844 -- Win32 DLLs have no .dll extension here, because addDLL tries
845 -- both foo.dll and foo.drv
846 mkSOName root = root
847 #else
848 mkSOName root = "lib" ++ root ++ ".so"
849 #endif
850
851 -- Darwin / MacOS X only: load a framework
852 -- a framework is a dynamic library packaged inside a directory of the same
853 -- name. They are searched for in different paths than normal libraries.
854 #ifdef darwin_TARGET_OS
855 loadFramework extraPaths rootname
856    = do { mb_fwk <- findFile mk_fwk (extraPaths ++ defaultFrameworkPaths)
857         ; case mb_fwk of
858             Just fwk_path -> loadDLL fwk_path
859             Nothing       -> return (Just "not found") }
860                 -- Tried all our known library paths, but dlopen()
861                 -- has no built-in paths for frameworks: give up
862    where
863      mk_fwk dir = dir ++ '/' : rootname ++ ".framework/" ++ rootname
864         -- sorry for the hardcoded paths, I hope they won't change anytime soon:
865      defaultFrameworkPaths = ["/Library/Frameworks", "/System/Library/Frameworks"]
866 #endif
867 \end{code}
868
869 %************************************************************************
870 %*                                                                      *
871                 Helper functions
872 %*                                                                      *
873 %************************************************************************
874
875 \begin{code}
876 findFile :: (FilePath -> FilePath)      -- Maps a directory path to a file path
877          -> [FilePath]                  -- Directories to look in
878          -> IO (Maybe FilePath)         -- The first file path to match
879 findFile mk_file_path [] 
880   = return Nothing
881 findFile mk_file_path (dir:dirs)
882   = do  { let file_path = mk_file_path dir
883         ; b <- doesFileExist file_path
884         ; if b then 
885              return (Just file_path)
886           else
887              findFile mk_file_path dirs }
888 \end{code}
889
890 \begin{code}
891 maybePutStr dflags s | verbosity dflags > 0 = putStr s
892                      | otherwise            = return ()
893
894 maybePutStrLn dflags s | verbosity dflags > 0 = putStrLn s
895                        | otherwise            = return ()
896 \end{code}