9ea08da4859761d567d1c6622ea1ca4b2544ed6b
[ghc-hetmet.git] / ghc / compiler / compMan / CmLink.lhs
1 %
2 % (c) The University of Glasgow, 2000
3 %
4 \section[CmLink]{Linker for GHCI}
5
6 \begin{code}
7 module CmLink ( Linkable(..),  Unlinked(..),
8                 filterModuleLinkables, 
9                 findModuleLinkable_maybe,
10                 LinkResult(..),
11                 link, 
12                 unload,
13                 PersistentLinkerState{-abstractly!-}, emptyPLS,
14 #ifdef GHCI
15                 linkExpr
16 #endif
17   ) where
18
19
20 import Interpreter
21 import DriverPipeline
22 import CmTypes
23 import CmStaticInfo     ( GhciMode(..) )
24 import Outputable       ( SDoc )
25 import Digraph          ( SCC(..), flattenSCC )
26 import Module           ( ModuleName )
27 import FiniteMap
28 import Outputable
29 import ErrUtils         ( showPass )
30 import CmdLineOpts      ( DynFlags(..) )
31 import Panic            ( panic, GhcException(..) )
32
33 import Exception
34 import List
35 import Monad
36 import IO
37
38 #include "HsVersions.h"
39 \end{code}
40
41 \begin{code}
42 data PersistentLinkerState 
43    = PersistentLinkerState {
44
45
46 #ifdef GHCI
47         -- Current global mapping from RdrNames to closure addresses
48         closure_env :: ClosureEnv,
49
50         -- the current global mapping from RdrNames of DataCons to 
51         -- info table addresses.
52         -- When a new Unlinked is linked into the running image, or an existing
53         -- module in the image is replaced, the itbl_env must be updated
54         -- appropriately.
55         itbl_env    :: ItblEnv,
56
57         -- list of objects we've loaded (we'll need to unload them again
58         -- before re-loading the same module), together with the ClockTime
59         -- of the linkable they were loaded from.
60         objects_loaded :: [Linkable]
61
62         -- notionally here, but really lives in the C part of the linker:
63         --            object_symtab :: FiniteMap String Addr
64 #else
65         dummy :: ()     --  sigh, can't have an empty record
66 #endif
67
68      }
69
70 data LinkResult 
71    = LinkOK   PersistentLinkerState
72    | LinkErrs PersistentLinkerState [SDoc]
73
74 findModuleLinkable_maybe :: [Linkable] -> ModuleName -> Maybe Linkable
75 findModuleLinkable_maybe lis mod 
76    = case [LM time nm us | LM time nm us <- lis, nm == mod] of
77         []   -> Nothing
78         [li] -> Just li
79         many -> pprPanic "findModuleLinkable" (ppr mod)
80
81
82 emptyPLS :: IO PersistentLinkerState
83 #ifdef GHCI
84 emptyPLS = return (PersistentLinkerState { closure_env = emptyFM, 
85                                            itbl_env    = emptyFM,
86                                            objects_loaded = [] })
87 #else
88 emptyPLS = return (PersistentLinkerState {})
89 #endif
90
91 -----------------------------------------------------------------------------
92 -- Unloading old objects ready for a new compilation sweep.
93 --
94 -- The compilation manager provides us with a list of linkables that it
95 -- considers "stable", i.e. won't be recompiled this time around.  For
96 -- each of the modules current linked in memory,
97 --
98 --      * if the linkable is stable (and it's the same one - the
99 --        user may have recompiled the module on the side), we keep it,
100 --
101 --      * otherwise, we unload it.
102 --
103
104 unload :: GhciMode
105        -> DynFlags
106        -> [Linkable]            -- stable linkables
107        -> PersistentLinkerState
108        -> IO PersistentLinkerState 
109
110 unload Batch       dflags linkables pls = return pls
111 unload Interactive dflags linkables pls
112   = do new_loaded <- filterM maybeUnload (objects_loaded pls)
113        let mods_retained = map linkableModName new_loaded
114            itbl_env'     = filterNameMap mods_retained (itbl_env pls)
115            closure_env'  = filterNameMap mods_retained (closure_env pls)
116
117        let verb = verbosity dflags
118        when (verb >= 3) $ do
119             hPutStrLn stderr (showSDoc 
120                 (text "CmLink.unload: retaining" <+> ppr mods_retained))
121
122        return pls{ objects_loaded = new_loaded,
123                    itbl_env = itbl_env',
124                    closure_env = closure_env' }
125   where
126         maybeUnload :: Linkable -> IO Bool
127         maybeUnload (LM time mod objs) = do
128           case findModuleLinkable_maybe linkables mod of
129                 Nothing -> do unloadObjs; return False
130                 Just l | linkableTime l /= time -> do unloadObjs; return False
131                        | otherwise              -> return True
132           where
133              unloadObjs = mapM unloadObj [ f | DotO f <- objs ]
134
135 -----------------------------------------------------------------------------
136 -- Linking
137
138 link :: GhciMode                -- interactive or batch
139      -> DynFlags                -- dynamic flags
140      -> Bool                    -- attempt linking in batch mode?
141      -> [Linkable]
142      -> PersistentLinkerState 
143      -> IO LinkResult
144
145 -- For the moment, in the batch linker, we don't bother to tell doLink
146 -- which packages to link -- it just tries all that are available.
147 -- batch_attempt_linking should only be *looked at* in batch mode.  It
148 -- should only be True if the upsweep was successful and someone
149 -- exports main, i.e., we have good reason to believe that linking
150 -- will succeed.
151
152 -- There will be (ToDo: are) two lists passed to link.  These
153 -- correspond to
154 --
155 --      1. The list of all linkables in the current home package.  This is
156 --         used by the batch linker to link the program, and by the interactive
157 --         linker to decide which modules from the previous link it can 
158 --         throw away.
159 --      2. The list of modules on which we just called "compile".  This list
160 --         is used by the interactive linker to decide which modules need
161 --         to be actually linked this time around (or unlinked and re-linked 
162 --         if the module was recompiled).
163
164 link mode dflags batch_attempt_linking linkables pls1
165    = do let verb = verbosity dflags
166         when (verb >= 3) $ do
167              hPutStrLn stderr "CmLink.link: linkables are ..."
168              hPutStrLn stderr (showSDoc (vcat (map ppr linkables)))
169         res <- link' mode dflags batch_attempt_linking linkables pls1
170         when (verb >= 3) $ 
171              hPutStrLn stderr "CmLink.link: done"
172         return res
173
174 link' Batch dflags batch_attempt_linking linkables pls1
175    | batch_attempt_linking
176    = do let o_files = concatMap getOfiles linkables
177         when (verb >= 1) $
178              hPutStrLn stderr "ghc: linking ..."
179         -- don't showPass in Batch mode; doLink will do that for us.
180         doLink o_files
181         -- doLink only returns if it succeeds
182         return (LinkOK pls1)
183    | otherwise
184    = do when (verb >= 3) $ do
185             hPutStrLn stderr "CmLink.link(batch): upsweep (partially) failed OR"
186             hPutStrLn stderr "   Main.main not exported; not linking."
187         return (LinkOK pls1)
188    where
189       verb = verbosity dflags
190       getOfiles (LM _ _ us) = map nameOfObject (filter isObject us)
191
192 link' Interactive dflags batch_attempt_linking linkables pls
193     = do showPass dflags "Linking"
194          let (objs, bcos) = partition (isObject.head.linkableUnlinked) linkables
195          linkObjs (objs ++ bcos) pls
196            -- get the objects first
197
198 ppLinkableSCC :: SCC Linkable -> SDoc
199 ppLinkableSCC = ppr . flattenSCC
200
201 filterModuleLinkables :: (ModuleName -> Bool) -> [Linkable] -> [Linkable]
202 filterModuleLinkables p [] = []
203 filterModuleLinkables p (li:lis)
204    = case li of
205         LM _ modnm _ -> if p modnm then retain else dump
206      where
207         dump   = filterModuleLinkables p lis
208         retain = li : dump
209
210 -----------------------------------------------------------------------------
211 -- Linker for interactive mode
212
213 #ifndef GHCI
214 linkObjs      = panic "CmLink.linkObjs: no interpreter"
215 unload        = panic "CmLink.unload: no interpreter"
216 lookupClosure = panic "CmLink.lookupClosure: no interpreter"
217 #else
218 linkObjs [] pls = linkFinish pls []
219 linkObjs (l@(LM _ m uls) : ls) pls
220    | all isObject uls = do
221         if isLoaded l pls then linkObjs ls pls else do
222         let objs = [ file | DotO file <- uls ] 
223         mapM_ loadObj objs
224         linkObjs ls pls{objects_loaded = l : objects_loaded pls}
225    | all isInterpretable uls  = linkInterpretedCode (l:ls) [] pls
226    | otherwise                = invalidLinkable
227
228 isLoaded :: Linkable -> PersistentLinkerState -> Bool
229 isLoaded l pls = 
230   case findModuleLinkable_maybe (objects_loaded pls) (linkableModName l) of
231         Nothing -> False
232         Just m  -> linkableTime l == linkableTime m
233  
234 linkInterpretedCode [] ul_trees pls = linkFinish pls ul_trees
235 linkInterpretedCode (LM _ m uls : ls) ul_trees pls
236    | all isInterpretable uls = 
237         linkInterpretedCode ls (uls++ul_trees) pls
238    | any isObject uls
239         = throwDyn (OtherError 
240              "can't link object code that depends on interpreted code")
241    | otherwise = invalidLinkable
242
243 invalidLinkable = panic "CmLink: linkable doesn't contain entirely objects or interpreted code"
244
245
246 -- link all the interpreted code in one go.
247 linkFinish pls ul_bcos = do
248    resolveObjs
249
250    let stuff = [ (bcos,itbls) | BCOs bcos itbls <- ul_bcos ]
251
252    (ibinds, new_itbl_env, new_closure_env) <-
253         linkIModules (itbl_env pls) (closure_env pls) stuff
254
255    let new_pls = pls { closure_env = new_closure_env,
256                        itbl_env    = new_itbl_env
257                      }
258    return (LinkOK new_pls)
259
260 linkExpr :: PersistentLinkerState -> UnlinkedBCOExpr -> IO HValue
261 linkExpr PersistentLinkerState{ itbl_env = ie, closure_env = ce } bcos
262   = linkIExpr ie ce bcos
263 #endif
264 \end{code}