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