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