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