875f1d63314c9d4e645432db550931f5759929a8
[ghc-hetmet.git] / compiler / ghci / ByteCodeLink.lhs
1 %
2 % (c) The University of Glasgow 2000
3 %
4 \section[ByteCodeLink]{Bytecode assembler and linker}
5
6 \begin{code}
7
8 {-# OPTIONS -optc-DNON_POSIX_SOURCE #-}
9
10 module ByteCodeLink ( 
11         HValue, 
12         ClosureEnv, emptyClosureEnv, extendClosureEnv,
13         linkBCO, lookupStaticPtr
14   ) where
15
16 #include "HsVersions.h"
17
18 import ByteCodeItbls    ( ItblEnv, ItblPtr )
19 import ByteCodeAsm      ( UnlinkedBCO(..), BCOPtr(..), sizeSS, ssElts )
20 import ObjLink          ( lookupSymbol )
21
22 import Name             ( Name,  nameModule, nameOccName, isExternalName )
23 import NameEnv
24 import OccName          ( occNameFS )
25 import PrimOp           ( PrimOp, primOpOcc )
26 import Module           ( moduleFS )
27 import FastString       ( FastString(..), unpackFS, zEncodeFS )
28 import Outputable
29 import Panic            ( GhcException(..) )
30
31 -- Standard libraries
32 import GHC.Word         ( Word(..) )
33
34 import Data.Array.IArray ( listArray )
35 import Data.Array.Base
36 import GHC.Arr          ( STArray(..) )
37
38 import Control.Exception ( throwDyn )
39 import Control.Monad    ( zipWithM )
40 import Control.Monad.ST ( stToIO )
41
42 import GHC.Exts         ( BCO#, newBCO#, unsafeCoerce#, Int#,
43                           ByteArray#, Array#, addrToHValue#, mkApUpd0# )
44
45 import GHC.Arr          ( Array(..) )
46 import GHC.IOBase       ( IO(..) )
47 import GHC.Ptr          ( Ptr(..) )
48 import GHC.Base         ( writeArray#, RealWorld, Int(..) )
49 \end{code}
50
51
52 %************************************************************************
53 %*                                                                      *
54 \subsection{Linking interpretables into something we can run}
55 %*                                                                      *
56 %************************************************************************
57
58 \begin{code}
59 type ClosureEnv = NameEnv (Name, HValue)
60 newtype HValue = HValue (forall a . a)
61
62 emptyClosureEnv = emptyNameEnv
63
64 extendClosureEnv :: ClosureEnv -> [(Name,HValue)] -> ClosureEnv
65 extendClosureEnv cl_env pairs
66   = extendNameEnvList cl_env [ (n, (n,v)) | (n,v) <- pairs]
67 \end{code}
68
69
70 %************************************************************************
71 %*                                                                      *
72 \subsection{Linking interpretables into something we can run}
73 %*                                                                      *
74 %************************************************************************
75
76 \begin{code}
77 {- 
78 data BCO# = BCO# ByteArray#             -- instrs   :: Array Word16#
79                  ByteArray#             -- literals :: Array Word32#
80                  PtrArray#              -- ptrs     :: Array HValue
81                  ByteArray#             -- itbls    :: Array Addr#
82 -}
83
84 linkBCO :: ItblEnv -> ClosureEnv -> UnlinkedBCO -> IO HValue
85 linkBCO ie ce ul_bco
86    = do BCO bco# <- linkBCO' ie ce ul_bco
87         -- SDM: Why do we need mkApUpd0 here?  I *think* it's because
88         -- otherwise top-level interpreted CAFs don't get updated 
89         -- after evaluation.   A top-level BCO will evaluate itself and
90         -- return its value when entered, but it won't update itself.
91         -- Wrapping the BCO in an AP_UPD thunk will take care of the
92         -- update for us.
93         --
94         -- Update: the above is true, but now we also have extra invariants:
95         --   (a) An AP thunk *must* point directly to a BCO
96         --   (b) A zero-arity BCO *must* be wrapped in an AP thunk
97         --   (c) An AP is always fully saturated, so we *can't* wrap
98         --       non-zero arity BCOs in an AP thunk.
99         -- 
100         if (unlinkedBCOArity ul_bco > 0) 
101            then return (unsafeCoerce# bco#)
102            else case mkApUpd0# bco# of { (# final_bco #) -> return final_bco }
103
104
105 linkBCO' :: ItblEnv -> ClosureEnv -> UnlinkedBCO -> IO BCO
106 linkBCO' ie ce (UnlinkedBCO nm arity insns_barr bitmap literalsSS ptrsSS itblsSS)
107    -- Raises an IO exception on failure
108    = do let literals = ssElts literalsSS
109             ptrs     = ssElts ptrsSS
110             itbls    = ssElts itblsSS
111
112         linked_itbls    <- mapM (lookupIE ie) itbls
113         linked_literals <- mapM lookupLiteral literals
114
115         let n_literals = sizeSS literalsSS
116             n_ptrs     = sizeSS ptrsSS
117             n_itbls    = sizeSS itblsSS
118
119         ptrs_arr <- mkPtrsArray ie ce n_ptrs ptrs
120
121         let 
122             ptrs_parr = case ptrs_arr of Array lo hi parr -> parr
123
124             itbls_arr = listArray (0, n_itbls-1) linked_itbls
125                         :: UArray Int ItblPtr
126             itbls_barr = case itbls_arr of UArray lo hi barr -> barr
127
128             literals_arr = listArray (0, n_literals-1) linked_literals
129                            :: UArray Int Word
130             literals_barr = case literals_arr of UArray lo hi barr -> barr
131
132             (I# arity#)  = arity
133
134         newBCO insns_barr literals_barr ptrs_parr itbls_barr arity# bitmap
135
136
137 -- we recursively link any sub-BCOs while making the ptrs array
138 mkPtrsArray :: ItblEnv -> ClosureEnv -> Int -> [BCOPtr] -> IO (Array Int HValue)
139 mkPtrsArray ie ce n_ptrs ptrs = do
140   marr <- newArray_ (0, n_ptrs-1)
141   let 
142     fill (BCOPtrName n)     i = do
143         ptr <- lookupName ce n
144         unsafeWrite marr i ptr
145     fill (BCOPtrPrimOp op)  i = do
146         ptr <- lookupPrimOp op
147         unsafeWrite marr i ptr
148     fill (BCOPtrBCO ul_bco) i = do
149         BCO bco# <- linkBCO' ie ce ul_bco
150         writeArrayBCO marr i bco#
151   zipWithM fill ptrs [0..]
152   unsafeFreeze marr
153
154 newtype IOArray i e = IOArray (STArray RealWorld i e)
155
156 instance HasBounds IOArray where
157     bounds (IOArray marr) = bounds marr
158
159 instance MArray IOArray e IO where
160     newArray lu init = stToIO $ do
161         marr <- newArray lu init; return (IOArray marr)
162     newArray_ lu = stToIO $ do
163         marr <- newArray_ lu; return (IOArray marr)
164     unsafeRead (IOArray marr) i = stToIO (unsafeRead marr i)
165     unsafeWrite (IOArray marr) i e = stToIO (unsafeWrite marr i e)
166
167 -- XXX HACK: we should really have a new writeArray# primop that takes a BCO#.
168 writeArrayBCO :: IOArray Int a -> Int -> BCO# -> IO ()
169 writeArrayBCO (IOArray (STArray _ _ marr#)) (I# i#) bco# = IO $ \s# ->
170   case (unsafeCoerce# writeArray#) marr# i# bco# s# of { s# ->
171   (# s#, () #) }
172
173 data BCO = BCO BCO#
174
175 newBCO :: ByteArray# -> ByteArray# -> Array# a
176          -> ByteArray# -> Int# -> ByteArray# -> IO BCO
177 newBCO instrs lits ptrs itbls arity bitmap
178    = IO $ \s -> case newBCO# instrs lits ptrs itbls arity bitmap s of 
179                   (# s1, bco #) -> (# s1, BCO bco #)
180
181
182 lookupLiteral :: Either Word FastString -> IO Word
183 lookupLiteral (Left lit)  = return lit
184 lookupLiteral (Right sym) = do Ptr addr <- lookupStaticPtr sym
185                                return (W# (unsafeCoerce# addr)) 
186      -- Can't be bothered to find the official way to convert Addr# to Word#;
187      -- the FFI/Foreign designers make it too damn difficult
188      -- Hence we apply the Blunt Instrument, which works correctly
189      -- on all reasonable architectures anyway
190
191 lookupStaticPtr :: FastString -> IO (Ptr ())
192 lookupStaticPtr addr_of_label_string 
193    = do let label_to_find = unpackFS addr_of_label_string
194         m <- lookupSymbol label_to_find 
195         case m of
196            Just ptr -> return ptr
197            Nothing  -> linkFail "ByteCodeLink: can't find label" 
198                                 label_to_find
199
200 lookupPrimOp :: PrimOp -> IO HValue
201 lookupPrimOp primop
202    = do let sym_to_find = primopToCLabel primop "closure"
203         m <- lookupSymbol sym_to_find
204         case m of
205            Just (Ptr addr) -> case addrToHValue# addr of
206                                  (# hval #) -> return hval
207            Nothing -> linkFail "ByteCodeLink.lookupCE(primop)" sym_to_find
208
209 lookupName :: ClosureEnv -> Name -> IO HValue
210 lookupName ce nm
211    = case lookupNameEnv ce nm of
212         Just (_,aa) -> return aa
213         Nothing 
214            -> ASSERT2(isExternalName nm, ppr nm)
215               do let sym_to_find = nameToCLabel nm "closure"
216                  m <- lookupSymbol sym_to_find
217                  case m of
218                     Just (Ptr addr) -> case addrToHValue# addr of
219                                           (# hval #) -> return hval
220                     Nothing         -> linkFail "ByteCodeLink.lookupCE" sym_to_find
221
222 lookupIE :: ItblEnv -> Name -> IO (Ptr a)
223 lookupIE ie con_nm 
224    = case lookupNameEnv ie con_nm of
225         Just (_, Ptr a) -> return (Ptr a)
226         Nothing
227            -> do -- try looking up in the object files.
228                  let sym_to_find1 = nameToCLabel con_nm "con_info"
229                  m <- lookupSymbol sym_to_find1
230                  case m of
231                     Just addr -> return addr
232                     Nothing 
233                        -> do -- perhaps a nullary constructor?
234                              let sym_to_find2 = nameToCLabel con_nm "static_info"
235                              n <- lookupSymbol sym_to_find2
236                              case n of
237                                 Just addr -> return addr
238                                 Nothing   -> linkFail "ByteCodeLink.lookupIE" 
239                                                 (sym_to_find1 ++ " or " ++ sym_to_find2)
240
241 linkFail :: String -> String -> IO a
242 linkFail who what
243    = throwDyn (ProgramError $
244         unlines [ ""
245                 , "During interactive linking, GHCi couldn't find the following symbol:"
246                 , ' ' : ' ' : what 
247                 , "This may be due to you not asking GHCi to load extra object files,"
248                 , "archives or DLLs needed by your current session.  Restart GHCi, specifying"
249                 , "the missing library using the -L/path/to/object/dir and -lmissinglibname"
250                 , "flags, or simply by naming the relevant files on the GHCi command line."
251                 , "Alternatively, this link failure might indicate a bug in GHCi."
252                 , "If you suspect the latter, please send a bug report to:"
253                 , "  glasgow-haskell-bugs@haskell.org"
254                 ])
255
256 -- HACKS!!!  ToDo: cleaner
257 nameToCLabel :: Name -> String{-suffix-} -> String
258 nameToCLabel n suffix
259    = unpackFS (zEncodeFS (moduleFS (nameModule n)))
260      ++ '_': unpackFS (zEncodeFS (occNameFS (nameOccName n))) ++ '_':suffix
261
262 primopToCLabel :: PrimOp -> String{-suffix-} -> String
263 primopToCLabel primop suffix
264    = let str = "GHCziPrimopWrappers_" ++ unpackFS (zEncodeFS (occNameFS (primOpOcc primop))) ++ '_':suffix
265      in --trace ("primopToCLabel: " ++ str)
266         str
267 \end{code}
268