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