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