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