CmLink.lhs 9.84 KB
Newer Older
1
%
2
% (c) The University of Glasgow, 2001
3
%
4
\section[CmLink]{The compilation manager's linker}
5
6

\begin{code}
7
8
9
10
11
12
13
14
module CmLink (
	LinkResult(..),	link, unload,

	filterModuleLinkables,
	findModuleLinkable_maybe,

        PersistentLinkerState{-abstractly!-}, emptyPLS,

15
#ifdef GHCI
16
17
18
	delListFromClosureEnv,
	addListToClosureEnv,
	linkExpr
19
#endif
20
  ) where
21

22

23
24
25
26
#ifdef GHCI
import ByteCodeLink	( linkIModules, linkIExpr )
#endif

27
import Interpreter
28
29
import DriverPipeline
import CmTypes
30
import HscTypes		( GhciMode(..) )
31
import Outputable	( SDoc )
32
import Name		( Name )
33
import Module		( ModuleName )
34
35
import FiniteMap
import Outputable
36
37
import ErrUtils		( showPass )
import CmdLineOpts	( DynFlags(..) )
38
import Util
39

40
#ifdef GHCI
41
import Exception	( block )
42
43
#endif

44
import IOExts
45
import List
46
import Monad
47
48
import IO

49
50
#include "HsVersions.h"

51
52
53
54
55
-- ---------------------------------------------------------------------------
-- The Linker's state

-- The PersistentLinkerState maps Names to actual closures (for
-- interpreted code only), for use during linking.
56

57
58
data PersistentLinkerState
   = PersistentLinkerState {
59

60
#ifdef GHCI
61
	-- Current global mapping from RdrNames to closure addresses
62
        closure_env :: ClosureEnv,
63

64
	-- the current global mapping from RdrNames of DataCons to
65
66
67
68
	-- info table addresses.
	-- When a new Unlinked is linked into the running image, or an existing
	-- module in the image is replaced, the itbl_env must be updated
	-- appropriately.
69
70
        itbl_env    :: ItblEnv,

71
72
	-- the currently loaded interpreted modules
	bcos_loaded :: [Linkable]
73

74
75
76
77
#else
	dummy :: ()	--  sigh, can't have an empty record
#endif

78
79
     }

80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
emptyPLS :: IO PersistentLinkerState
#ifdef GHCI
emptyPLS = return (PersistentLinkerState { closure_env = emptyFM,
                                           itbl_env    = emptyFM,
					   bcos_loaded = [] })
#else
emptyPLS = return (PersistentLinkerState {})
#endif

-- We also keep track of which object modules are currently loaded
-- into the dynamic linker, so that we can unload them again later.
--
-- This state *must* match the actual state of the dyanmic linker at
-- all times, which is why we keep it private here and don't
-- put it in the PersistentLinkerState.
--
GLOBAL_VAR(v_ObjectsLoaded, [], [Linkable])


-- ---------------------------------------------------------------------------
-- Utils
101

102
findModuleLinkable_maybe :: [Linkable] -> ModuleName -> Maybe Linkable
103
findModuleLinkable_maybe lis mod
104
   = case [LM time nm us | LM time nm us <- lis, nm == mod] of
105
106
107
        []   -> Nothing
        [li] -> Just li
        many -> pprPanic "findModuleLinkable" (ppr mod)
108

109
110
111
112
113
114
115
116
filterModuleLinkables :: (ModuleName -> Bool) -> [Linkable] -> [Linkable]
filterModuleLinkables p [] = []
filterModuleLinkables p (li:lis)
   = case li of
        LM _ modnm _ -> if p modnm then retain else dump
     where
        dump   = filterModuleLinkables p lis
        retain = li : dump
117

118
119
120
121
122
linkableInSet :: Linkable -> [Linkable] -> Bool
linkableInSet l objs_loaded =
  case findModuleLinkable_maybe objs_loaded (linkableModName l) of
	Nothing -> False
	Just m  -> linkableTime l == linkableTime m
123

124
125
-- These two are used to add/remove entries from the closure env for
-- new bindings made at the prompt.
126
#ifdef GHCI
127
128
129
130
131
delListFromClosureEnv :: PersistentLinkerState -> [Name]
  	-> IO PersistentLinkerState
delListFromClosureEnv pls names
  = return pls{ closure_env = delListFromFM (closure_env pls) names }

132
addListToClosureEnv :: PersistentLinkerState -> [(Name,HValue)]
133
	-> IO PersistentLinkerState
134
addListToClosureEnv pls new_bindings
135
  = return pls{ closure_env = addListToFM (closure_env pls) new_bindings }
136
#endif
137

138
-- ---------------------------------------------------------------------------
139
140
141
142
143
144
145
146
147
148
149
-- Unloading old objects ready for a new compilation sweep.
--
-- The compilation manager provides us with a list of linkables that it
-- considers "stable", i.e. won't be recompiled this time around.  For
-- each of the modules current linked in memory,
--
--	* if the linkable is stable (and it's the same one - the
--	  user may have recompiled the module on the side), we keep it,
--
--	* otherwise, we unload it.
--
150
--      * we also implicitly unload all temporary bindings at this point.
151
152
153
154
155

unload :: GhciMode
       -> DynFlags
       -> [Linkable]		-- stable linkables
       -> PersistentLinkerState
156
       -> IO PersistentLinkerState
157

158
159
unload Batch dflags linkables pls = return pls

160
#ifdef GHCI
161
unload Interactive dflags linkables pls
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
  = block $ do -- block, so we're safe from Ctrl-C in here
	objs_loaded  <- readIORef v_ObjectsLoaded
	objs_loaded' <- filterM (maybeUnload objs_to_keep) objs_loaded
	writeIORef v_ObjectsLoaded objs_loaded'

        bcos_loaded' <- filterM (maybeUnload bcos_to_keep) (bcos_loaded pls)

       	let objs_retained = map linkableModName objs_loaded'
	    bcos_retained = map linkableModName bcos_loaded'
	    itbl_env'     = filterNameMap bcos_retained (itbl_env pls)
            closure_env'  = filterNameMap bcos_retained (closure_env pls)

       	let verb = verbosity dflags
       	when (verb >= 3) $ do
	    hPutStrLn stderr (showSDoc
		(text "CmLink.unload: retaining objs" <+> ppr objs_retained))
	    hPutStrLn stderr (showSDoc
		(text "CmLink.unload: retaining bcos" <+> ppr bcos_retained))

       	return pls{ itbl_env = itbl_env',
	            closure_env = closure_env',
		    bcos_loaded = bcos_loaded' }
184
  where
185
186
187
188
189
190
191
192
193
	(objs_to_keep, bcos_to_keep) = partition isObjectLinkable linkables

	maybeUnload :: [Linkable] -> Linkable -> IO Bool
	maybeUnload keep_linkables l@(LM time mod objs)
	   | linkableInSet l linkables
		= return True
	   | otherwise
		= do mapM unloadObj [ f | DotO f <- objs ]
		     return False
194
#else
195
unload Interactive dflags linkables pls = panic "CmLink.unload: no interpreter"
196
#endif
197

198
199
200
-----------------------------------------------------------------------------
-- Linking

201
202
203
204
data LinkResult
   = LinkOK   PersistentLinkerState
   | LinkErrs PersistentLinkerState [SDoc]

205
link :: GhciMode		-- interactive or batch
206
     -> DynFlags		-- dynamic flags
207
     -> Bool			-- attempt linking in batch mode?
208
     -> [Linkable]
209
     -> PersistentLinkerState
210
     -> IO LinkResult
211

212
213
214
215
216
217
218
219
220
221
222
223
-- For the moment, in the batch linker, we don't bother to tell doLink
-- which packages to link -- it just tries all that are available.
-- batch_attempt_linking should only be *looked at* in batch mode.  It
-- should only be True if the upsweep was successful and someone
-- exports main, i.e., we have good reason to believe that linking
-- will succeed.

-- There will be (ToDo: are) two lists passed to link.  These
-- correspond to
--
--	1. The list of all linkables in the current home package.  This is
--	   used by the batch linker to link the program, and by the interactive
224
--	   linker to decide which modules from the previous link it can
225
226
227
--	   throw away.
--	2. The list of modules on which we just called "compile".  This list
--	   is used by the interactive linker to decide which modules need
228
--	   to be actually linked this time around (or unlinked and re-linked
229
230
--	   if the module was recompiled).

231
232
233
234
235
236
link mode dflags batch_attempt_linking linkables pls1
   = do let verb = verbosity dflags
        when (verb >= 3) $ do
	     hPutStrLn stderr "CmLink.link: linkables are ..."
             hPutStrLn stderr (showSDoc (vcat (map ppr linkables)))
	res <- link' mode dflags batch_attempt_linking linkables pls1
237
        when (verb >= 3) $
238
	     hPutStrLn stderr "CmLink.link: done"
239
240
	return res

241
link' Batch dflags batch_attempt_linking linkables pls1
242
243
   | batch_attempt_linking
   = do let o_files = concatMap getOfiles linkables
244
245
        when (verb >= 1) $
             hPutStrLn stderr "ghc: linking ..."
246
	-- don't showPass in Batch mode; doLink will do that for us.
247
        doLink o_files
248
	-- doLink only returns if it succeeds
249
        return (LinkOK pls1)
250
   | otherwise
251
252
253
   = do when (verb >= 3) $ do
	    hPutStrLn stderr "CmLink.link(batch): upsweep (partially) failed OR"
            hPutStrLn stderr "   Main.main not exported; not linking."
254
255
        return (LinkOK pls1)
   where
256
      verb = verbosity dflags
257
      getOfiles (LM _ _ us) = map nameOfObject (filter isObject us)
258

259
#ifdef GHCI
260
link' Interactive dflags batch_attempt_linking linkables pls
261
    = do showPass dflags "Linking"
262
	 block $ do -- don't want to be interrupted by ^C in here
263

264
265
266
	    -- Always load objects first.  Objects aren't allowed to
	    -- depend on BCOs.
	    let (objs, bcos) = partition isObjectLinkable linkables
267

268
269
270
	    objs_loaded  <- readIORef v_ObjectsLoaded
	    objs_loaded' <- linkObjs objs objs_loaded
	    writeIORef v_ObjectsLoaded objs_loaded'
271

272
273
274
275
276
277
	    -- resolve symbols within the object files
	    resolveObjs

	    -- finally link the interpreted linkables
	    linkBCOs bcos [] pls
#endif
278

279
280
-----------------------------------------------------------------------------
-- Linker for interactive mode
281

282
283
284
285
286
287
288
289
290
291
292
293
294
#ifdef GHCI
linkObjs [] objs_loaded = return objs_loaded
linkObjs (l@(LM _ m uls) : ls) objs_loaded
   | linkableInSet l objs_loaded  = linkObjs ls objs_loaded -- already loaded
   | otherwise = do mapM_ loadObj [ file | DotO file <- uls ]
	  	    linkObjs ls (l:objs_loaded)

linkBCOs [] ul_trees pls = linkFinish pls ul_trees
linkBCOs (l@(LM _ m uls) : ls) ul_trees pls
   | linkableInSet l (bcos_loaded pls)
	= linkBCOs ls ul_trees pls
   | otherwise
	= linkBCOs ls (uls++ul_trees) pls{bcos_loaded = l : bcos_loaded pls}
295

296
297
298
299
-- link all the interpreted code in one go.
linkFinish pls ul_bcos = do

   let stuff = [ (bcos,itbls) | BCOs bcos itbls <- ul_bcos ]
300
301

   (ibinds, new_itbl_env, new_closure_env) <-
302
	linkIModules (itbl_env pls) (closure_env pls) stuff
303

304
305
306
   let new_pls = pls { closure_env = new_closure_env,
		       itbl_env    = new_itbl_env
		     }
307
   return (LinkOK new_pls)
308
#endif
309

310
311
312
313
-- ---------------------------------------------------------------------------
-- Link a single expression

#ifdef GHCI
314
315
316
linkExpr :: PersistentLinkerState -> UnlinkedBCOExpr -> IO HValue
linkExpr PersistentLinkerState{ itbl_env = ie, closure_env = ce } bcos
  = linkIExpr ie ce bcos
317
#endif
318
\end{code}