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