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