c971f91d82408ae4a8e8896a1be6f0307e750053
[ghc-hetmet.git] / ghc / compiler / ghci / Linker.lhs
1 %
2 % (c) The University of Glasgow 2005
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 "HsVersions.h"
24
25 import ObjLink          ( loadDLL, loadObj, unloadObj, resolveObjs, initObjLinker )
26 import ByteCodeLink     ( HValue, ClosureEnv, extendClosureEnv, linkBCO )
27 import ByteCodeItbls    ( ItblEnv )
28 import ByteCodeAsm      ( CompiledByteCode(..), bcoFreeNames, UnlinkedBCO(..))
29
30 import Packages
31 import DriverPhases     ( isObjectFilename, isDynLibFilename )
32 import Util             ( getFileSuffix )
33 import Finder           ( findModule, findObjectLinkableMaybe, FindResult(..) )
34 import HscTypes
35 import Name             ( Name, nameModule, isExternalName, isWiredInName )
36 import NameEnv
37 import NameSet          ( nameSetToList )
38 import Module
39 import ListSetOps       ( minusList )
40 import DynFlags         ( DynFlags(..), getOpts )
41 import BasicTypes       ( SuccessFlag(..), succeeded, failed )
42 import Outputable
43 import Panic            ( GhcException(..) )
44 import Util             ( zipLazy, global )
45 import StaticFlags      ( v_Ld_inputs )
46 import ErrUtils         ( debugTraceMsg )
47
48 -- Standard libraries
49 import Control.Monad    ( when, filterM, foldM )
50
51 import Data.IORef       ( IORef, readIORef, writeIORef )
52 import Data.List        ( partition, nub )
53
54 import System.IO        ( putStr, putStrLn, hPutStrLn, stderr, fixIO )
55 import System.Directory ( doesFileExist )
56
57 import Control.Exception ( block, throwDyn )
58 import Maybe            ( isJust, fromJust )
59
60 #if __GLASGOW_HASKELL__ >= 503
61 import GHC.IOBase       ( IO(..) )
62 #else
63 import PrelIOBase       ( IO(..) )
64 #endif
65 \end{code}
66
67
68 %************************************************************************
69 %*                                                                      *
70                         The Linker's state
71 %*                                                                      *
72 %************************************************************************
73
74 The persistent linker state *must* match the actual state of the 
75 C dynamic linker at all times, so we keep it in a private global variable.
76
77
78 The PersistentLinkerState maps Names to actual closures (for
79 interpreted code only), for use during linking.
80
81 \begin{code}
82 GLOBAL_VAR(v_PersistentLinkerState, panic "Dynamic linker not initialised", PersistentLinkerState)
83 GLOBAL_VAR(v_InitLinkerDone, False, Bool)       -- Set True when dynamic linker is initialised
84
85 data PersistentLinkerState
86    = PersistentLinkerState {
87
88         -- Current global mapping from Names to their true values
89         closure_env :: ClosureEnv,
90
91         -- The current global mapping from RdrNames of DataCons to
92         -- info table addresses.
93         -- When a new Unlinked is linked into the running image, or an existing
94         -- module in the image is replaced, the itbl_env must be updated
95         -- appropriately.
96         itbl_env    :: ItblEnv,
97
98         -- The currently loaded interpreted modules (home package)
99         bcos_loaded :: [Linkable],
100
101         -- And the currently-loaded compiled modules (home package)
102         objs_loaded :: [Linkable],
103
104         -- The currently-loaded packages; always object code
105         -- Held, as usual, in dependency order; though I am not sure if
106         -- that is really important
107         pkgs_loaded :: [PackageId]
108      }
109
110 emptyPLS :: DynFlags -> PersistentLinkerState
111 emptyPLS dflags = PersistentLinkerState { 
112                         closure_env = emptyNameEnv,
113                         itbl_env    = emptyNameEnv,
114                         pkgs_loaded = init_pkgs,
115                         bcos_loaded = [],
116                         objs_loaded = [] }
117   -- Packages that don't need loading, because the compiler 
118   -- shares them with the interpreted program.
119   --
120   -- The linker's symbol table is populated with RTS symbols using an
121   -- explicit list.  See rts/Linker.c for details.
122   where init_pkgs
123           | ExtPackage rts_id <- rtsPackageId (pkgState dflags) = [rts_id]
124           | otherwise = []
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 :: [Module] -> NameEnv (Name, a) -> NameEnv (Name, a)
143 filterNameMap mods env 
144    = filterNameEnv keep_elt env
145    where
146      keep_elt (n,_) = isExternalName n 
147                       && (nameModule n `elem` mods)
148 \end{code}
149
150
151 \begin{code}
152 showLinkerState :: IO ()
153 -- Display the persistent linker state
154 showLinkerState
155   = do pls <- readIORef v_PersistentLinkerState
156        printDump (vcat [text "----- Linker state -----",
157                         text "Pkgs:" <+> ppr (pkgs_loaded pls),
158                         text "Objs:" <+> ppr (objs_loaded pls),
159                         text "BCOs:" <+> ppr (bcos_loaded pls)])
160 \end{code}
161                         
162         
163
164
165 %************************************************************************
166 %*                                                                      *
167 \subsection{Initialisation}
168 %*                                                                      *
169 %************************************************************************
170
171 We initialise the dynamic linker by
172
173 a) calling the C initialisation procedure
174
175 b) Loading any packages specified on the command line,
176    now held in v_ExplicitPackages
177
178 c) Loading any packages specified on the command line,
179    now held in the -l options in v_Opt_l
180
181 d) Loading any .o/.dll files specified on the command line,
182    now held in v_Ld_inputs
183
184 e) Loading any MacOS frameworks
185
186 \begin{code}
187 initDynLinker :: DynFlags -> 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 dflags
191   = do  { done <- readIORef v_InitLinkerDone
192         ; if done then return () 
193                   else do { writeIORef v_InitLinkerDone True
194                           ; reallyInitDynLinker dflags }
195         }
196
197 reallyInitDynLinker dflags
198   = do  {  -- Initialise the linker state
199         ; writeIORef v_PersistentLinkerState (emptyPLS dflags)
200
201                 -- (a) initialise the C dynamic linker
202         ; initObjLinker 
203
204                 -- (b) Load packages from the command-line
205         ; linkPackages dflags (explicitPackages (pkgState dflags))
206
207                 -- (c) Link libraries from the command-line
208         ; let optl = getOpts dflags opt_l
209         ; let minus_ls = [ lib | '-':'l':lib <- optl ]
210
211                 -- (d) Link .o files from the command-line
212         ; let lib_paths = libraryPaths dflags
213         ; cmdline_ld_inputs <- readIORef v_Ld_inputs
214
215         ; classified_ld_inputs <- mapM classifyLdInput cmdline_ld_inputs
216
217                 -- (e) Link any MacOS frameworks
218 #ifdef darwin_TARGET_OS 
219         ; let framework_paths = frameworkPaths dflags
220         ; let frameworks      = cmdlineFrameworks dflags
221 #else
222         ; let frameworks      = []
223         ; let framework_paths = []
224 #endif
225                 -- Finally do (c),(d),(e)       
226         ; let cmdline_lib_specs = [ l | Just l <- classified_ld_inputs ]
227                                ++ map DLL       minus_ls 
228                                ++ map Framework frameworks
229         ; if null cmdline_lib_specs then return ()
230                                     else do
231
232         { mapM_ (preloadLib dflags lib_paths framework_paths) cmdline_lib_specs
233         ; maybePutStr dflags "final link ... "
234         ; ok <- resolveObjs
235
236         ; if succeeded ok then maybePutStrLn dflags "done"
237           else throwDyn (InstallationError "linking extra libraries/objects failed")
238         }}
239
240 classifyLdInput :: FilePath -> IO (Maybe LibrarySpec)
241 classifyLdInput f
242   | isObjectFilename f = return (Just (Object f))
243   | isDynLibFilename f = return (Just (DLLPath f))
244   | otherwise          = do
245         hPutStrLn stderr ("Warning: ignoring unrecognised input `" ++ f ++ "'")
246         return Nothing
247
248 preloadLib :: DynFlags -> [String] -> [String] -> LibrarySpec -> IO ()
249 preloadLib dflags lib_paths framework_paths lib_spec
250   = do maybePutStr dflags ("Loading object " ++ showLS lib_spec ++ " ... ")
251        case lib_spec of
252           Object static_ish
253              -> do b <- preload_static lib_paths static_ish
254                    maybePutStrLn dflags (if b  then "done"
255                                                 else "not found")
256          
257           DLL dll_unadorned
258              -> do maybe_errstr <- loadDynamic lib_paths dll_unadorned
259                    case maybe_errstr of
260                       Nothing -> maybePutStrLn dflags "done"
261                       Just mm -> preloadFailed mm lib_paths lib_spec
262
263           DLLPath dll_path
264              -> do maybe_errstr <- loadDLL dll_path
265                    case maybe_errstr of
266                       Nothing -> maybePutStrLn dflags "done"
267                       Just mm -> preloadFailed mm lib_paths lib_spec
268
269 #ifdef darwin_TARGET_OS
270           Framework framework
271              -> do maybe_errstr <- loadFramework framework_paths framework
272                    case maybe_errstr of
273                       Nothing -> maybePutStrLn dflags "done"
274                       Just mm -> preloadFailed mm framework_paths lib_spec
275 #endif
276   where
277     preloadFailed :: String -> [String] -> LibrarySpec -> IO ()
278     preloadFailed sys_errmsg paths spec
279        = do maybePutStr dflags
280                ("failed.\nDynamic linker error message was:\n   " 
281                     ++ sys_errmsg  ++ "\nWhilst trying to load:  " 
282                     ++ showLS spec ++ "\nDirectories to search are:\n"
283                     ++ unlines (map ("   "++) paths) )
284             give_up
285     
286     -- Not interested in the paths in the static case.
287     preload_static paths name
288        = do b <- doesFileExist name
289             if not b then return False
290                      else loadObj name >> return True
291     
292     give_up = throwDyn $ 
293               CmdLineError "user specified .o/.so/.DLL could not be loaded."
294 \end{code}
295
296
297 %************************************************************************
298 %*                                                                      *
299                 Link a byte-code expression
300 %*                                                                      *
301 %************************************************************************
302
303 \begin{code}
304 linkExpr :: HscEnv -> UnlinkedBCO -> IO HValue
305
306 -- Link a single expression, *including* first linking packages and 
307 -- modules that this expression depends on.
308 --
309 -- Raises an IO exception if it can't find a compiled version of the
310 -- dependents to link.
311
312 linkExpr hsc_env root_ul_bco
313   = do {  
314         -- Initialise the linker (if it's not been done already)
315      let dflags = hsc_dflags hsc_env
316    ; initDynLinker dflags
317
318         -- Find what packages and linkables are required
319    ; eps <- readIORef (hsc_EPS hsc_env)
320    ; (lnks, pkgs) <- getLinkDeps hsc_env hpt (eps_PIT eps) needed_mods
321
322         -- Link the packages and modules required
323    ; linkPackages dflags pkgs
324    ; ok <- linkModules dflags lnks
325    ; if failed ok then
326         dieWith empty
327      else do {
328
329         -- Link the expression itself
330      pls <- readIORef v_PersistentLinkerState
331    ; let ie = itbl_env pls
332          ce = closure_env pls
333
334         -- Link the necessary packages and linkables
335    ; (_, (root_hval:_)) <- linkSomeBCOs False ie ce [root_ul_bco]
336    ; return root_hval
337    }}
338    where
339      hpt    = hsc_HPT hsc_env
340      dflags = hsc_dflags hsc_env
341      free_names = nameSetToList (bcoFreeNames root_ul_bco)
342
343      needed_mods :: [Module]
344      needed_mods = [ nameModule n | n <- free_names, 
345                                     isExternalName n,           -- Names from other modules
346                                     not (isWiredInName n)       -- Exclude wired-in names
347                    ]                                            -- (see note below)
348         -- Exclude wired-in names because we may not have read
349         -- their interface files, so getLinkDeps will fail
350         -- All wired-in names are in the base package, which we link
351         -- by default, so we can safely ignore them here.
352  
353 dieWith msg = throwDyn (ProgramError (showSDoc msg))
354
355 getLinkDeps :: HscEnv -> HomePackageTable -> PackageIfaceTable
356             -> [Module]                         -- If you need these
357             -> IO ([Linkable], [PackageId])     -- ... then link these first
358 -- Fails with an IO exception if it can't find enough files
359
360 getLinkDeps hsc_env hpt pit mods
361 -- Find all the packages and linkables that a set of modules depends on
362  = do { pls <- readIORef v_PersistentLinkerState ;
363         let {
364         -- 1.  Find the dependent home-pkg-modules/packages from each iface
365             (mods_s, pkgs_s) = unzip (map get_deps mods) ;
366
367         -- 2.  Exclude ones already linked
368         --      Main reason: avoid findModule calls in get_linkable
369             mods_needed = nub (concat mods_s) `minusList` linked_mods     ;
370             pkgs_needed = nub (concat pkgs_s) `minusList` pkgs_loaded pls ;
371
372             linked_mods = map linkableModule (objs_loaded pls ++ bcos_loaded pls)
373         } ;
374         
375         -- 3.  For each dependent module, find its linkable
376         --     This will either be in the HPT or (in the case of one-shot
377         --     compilation) we may need to use maybe_getFileLinkable
378         lnks_needed <- mapM get_linkable mods_needed ;
379
380         return (lnks_needed, pkgs_needed) }
381   where
382     get_deps :: Module -> ([Module],[PackageId])
383         -- Get the things needed for the specified module
384         -- This is rather similar to the code in RnNames.importsFromImportDecl
385     get_deps mod
386         | ExtPackage p <- mi_package iface
387         = ([], p : dep_pkgs deps)
388         | otherwise
389         = (mod : [m | (m,_) <- dep_mods deps], dep_pkgs deps)
390         where
391           iface = get_iface mod
392           deps  = mi_deps iface
393
394     get_iface mod = case lookupIface hpt pit mod of
395                             Just iface -> iface
396                             Nothing    -> pprPanic "getLinkDeps" (no_iface mod)
397     no_iface mod = ptext SLIT("No iface for") <+> ppr mod
398         -- This one is a GHC bug
399
400     no_obj mod = dieWith (ptext SLIT("No compiled code for") <+> ppr mod)
401         -- This one is a build-system bug
402
403     get_linkable mod_name       -- A home-package module
404         | Just mod_info <- lookupModuleEnv hpt mod_name 
405         = ASSERT(isJust (hm_linkable mod_info))
406           return (fromJust (hm_linkable mod_info))
407         | otherwise     
408         =       -- It's not in the HPT because we are in one shot mode, 
409                 -- so use the Finder to get a ModLocation...
410           do { mb_stuff <- findModule hsc_env mod_name False ;
411                case mb_stuff of {
412                   Found loc _ -> found loc mod_name ;
413                   _ -> no_obj mod_name
414              }}
415
416     found loc mod_name = do {
417                 -- ...and then find the linkable for it
418                mb_lnk <- findObjectLinkableMaybe mod_name loc ;
419                case mb_lnk of {
420                   Nothing -> no_obj mod_name ;
421                   Just lnk -> return lnk
422               }}
423 \end{code}
424
425
426 %************************************************************************
427 %*                                                                      *
428                 Link some linkables
429         The linkables may consist of a mixture of 
430         byte-code modules and object modules
431 %*                                                                      *
432 %************************************************************************
433
434 \begin{code}
435 linkModules :: DynFlags -> [Linkable] -> IO SuccessFlag
436 linkModules dflags linkables
437   = block $ do  -- don't want to be interrupted by ^C in here
438         
439         let (objs, bcos) = partition isObjectLinkable 
440                               (concatMap partitionLinkable linkables)
441
442                 -- Load objects first; they can't depend on BCOs
443         ok_flag <- dynLinkObjs dflags objs
444
445         if failed ok_flag then 
446                 return Failed
447           else do
448                 dynLinkBCOs bcos
449                 return Succeeded
450                 
451
452 -- HACK to support f-x-dynamic in the interpreter; no other purpose
453 partitionLinkable :: Linkable -> [Linkable]
454 partitionLinkable li
455    = let li_uls = linkableUnlinked li
456          li_uls_obj = filter isObject li_uls
457          li_uls_bco = filter isInterpretable li_uls
458      in 
459          case (li_uls_obj, li_uls_bco) of
460             (objs@(_:_), bcos@(_:_)) 
461                -> [li{linkableUnlinked=li_uls_obj}, li{linkableUnlinked=li_uls_bco}]
462             other
463                -> [li]
464
465 findModuleLinkable_maybe :: [Linkable] -> Module -> Maybe Linkable
466 findModuleLinkable_maybe lis mod
467    = case [LM time nm us | LM time nm us <- lis, nm == mod] of
468         []   -> Nothing
469         [li] -> Just li
470         many -> pprPanic "findModuleLinkable" (ppr mod)
471
472 linkableInSet :: Linkable -> [Linkable] -> Bool
473 linkableInSet l objs_loaded =
474   case findModuleLinkable_maybe objs_loaded (linkableModule l) of
475         Nothing -> False
476         Just m  -> linkableTime l == linkableTime m
477 \end{code}
478
479
480 %************************************************************************
481 %*                                                                      *
482 \subsection{The object-code linker}
483 %*                                                                      *
484 %************************************************************************
485
486 \begin{code}
487 dynLinkObjs :: DynFlags -> [Linkable] -> IO SuccessFlag
488         -- Side-effects the PersistentLinkerState
489
490 dynLinkObjs dflags objs
491   = do  pls <- readIORef v_PersistentLinkerState
492
493         -- Load the object files and link them
494         let (objs_loaded', new_objs) = rmDupLinkables (objs_loaded pls) objs
495             pls1                     = pls { objs_loaded = objs_loaded' }
496             unlinkeds                = concatMap linkableUnlinked new_objs
497
498         mapM loadObj (map nameOfObject unlinkeds)
499
500         -- Link the all together
501         ok <- resolveObjs
502
503         -- If resolving failed, unload all our 
504         -- object modules and carry on
505         if succeeded ok then do
506                 writeIORef v_PersistentLinkerState pls1
507                 return Succeeded
508           else do
509                 pls2 <- unload_wkr dflags [] pls1
510                 writeIORef v_PersistentLinkerState pls2
511                 return Failed
512
513
514 rmDupLinkables :: [Linkable]    -- Already loaded
515                -> [Linkable]    -- New linkables
516                -> ([Linkable],  -- New loaded set (including new ones)
517                    [Linkable])  -- New linkables (excluding dups)
518 rmDupLinkables already ls
519   = go already [] ls
520   where
521     go already extras [] = (already, extras)
522     go already extras (l:ls)
523         | linkableInSet l already = go already     extras     ls
524         | otherwise               = go (l:already) (l:extras) ls
525 \end{code}
526
527 %************************************************************************
528 %*                                                                      *
529 \subsection{The byte-code linker}
530 %*                                                                      *
531 %************************************************************************
532
533 \begin{code}
534 dynLinkBCOs :: [Linkable] -> IO ()
535         -- Side-effects the persistent linker state
536 dynLinkBCOs bcos
537   = do  pls <- readIORef v_PersistentLinkerState
538
539         let (bcos_loaded', new_bcos) = rmDupLinkables (bcos_loaded pls) bcos
540             pls1                     = pls { bcos_loaded = bcos_loaded' }
541             unlinkeds :: [Unlinked]
542             unlinkeds                = concatMap linkableUnlinked new_bcos
543
544             cbcs :: [CompiledByteCode]
545             cbcs      = map byteCodeOfObject unlinkeds
546                       
547                       
548             ul_bcos    = [b | ByteCode bs _  <- cbcs, b <- bs]
549             ies        = [ie | ByteCode _ ie <- cbcs]
550             gce       = closure_env pls
551             final_ie  = foldr plusNameEnv (itbl_env pls) ies
552
553         (final_gce, linked_bcos) <- linkSomeBCOs True final_ie gce ul_bcos
554                 -- What happens to these linked_bcos?
555
556         let pls2 = pls1 { closure_env = final_gce,
557                           itbl_env    = final_ie }
558
559         writeIORef v_PersistentLinkerState pls2
560         return ()
561
562 -- Link a bunch of BCOs and return them + updated closure env.
563 linkSomeBCOs :: Bool    -- False <=> add _all_ BCOs to returned closure env
564                         -- True  <=> add only toplevel BCOs to closure env
565              -> ItblEnv 
566              -> ClosureEnv 
567              -> [UnlinkedBCO]
568              -> IO (ClosureEnv, [HValue])
569                         -- The returned HValues are associated 1-1 with
570                         -- the incoming unlinked BCOs.  Each gives the
571                         -- value of the corresponding unlinked BCO
572                                         
573
574 linkSomeBCOs toplevs_only ie ce_in ul_bcos
575    = do let nms = map unlinkedBCOName ul_bcos
576         hvals <- fixIO 
577                     ( \ hvs -> let ce_out = extendClosureEnv ce_in (zipLazy nms hvs)
578                                in  mapM (linkBCO ie ce_out) ul_bcos )
579
580         let ce_all_additions = zip nms hvals
581             ce_top_additions = filter (isExternalName.fst) ce_all_additions
582             ce_additions     = if toplevs_only then ce_top_additions 
583                                                else ce_all_additions
584             ce_out = -- make sure we're not inserting duplicate names into the 
585                      -- closure environment, which leads to trouble.
586                      ASSERT (all (not . (`elemNameEnv` ce_in)) (map fst ce_additions))
587                      extendClosureEnv ce_in ce_additions
588         return (ce_out, hvals)
589
590 \end{code}
591
592
593 %************************************************************************
594 %*                                                                      *
595                 Unload some object modules
596 %*                                                                      *
597 %************************************************************************
598
599 \begin{code}
600 -- ---------------------------------------------------------------------------
601 -- Unloading old objects ready for a new compilation sweep.
602 --
603 -- The compilation manager provides us with a list of linkables that it
604 -- considers "stable", i.e. won't be recompiled this time around.  For
605 -- each of the modules current linked in memory,
606 --
607 --      * if the linkable is stable (and it's the same one - the
608 --        user may have recompiled the module on the side), we keep it,
609 --
610 --      * otherwise, we unload it.
611 --
612 --      * we also implicitly unload all temporary bindings at this point.
613
614 unload :: DynFlags -> [Linkable] -> IO ()
615 -- The 'linkables' are the ones to *keep*
616
617 unload dflags linkables
618   = block $ do -- block, so we're safe from Ctrl-C in here
619   
620         -- Initialise the linker (if it's not been done already)
621         initDynLinker dflags
622
623         pls     <- readIORef v_PersistentLinkerState
624         new_pls <- unload_wkr dflags linkables pls
625         writeIORef v_PersistentLinkerState new_pls
626
627         debugTraceMsg dflags 3 (showSDoc
628                 (text "unload: retaining objs" <+> ppr (objs_loaded new_pls)))
629         debugTraceMsg dflags 3 (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.ldOptions 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.frameworks 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}