7f0779c2627e1b905c0bf159b626a553f6e2424a
[mate.git] / Mate / MethodPool.hs
1 {-# LANGUAGE CPP #-}
2 {-# LANGUAGE OverloadedStrings #-}
3 {-# LANGUAGE ForeignFunctionInterface #-}
4 #include "debug.h"
5 module Mate.MethodPool where
6
7 import Data.Binary
8 import Data.String.Utils
9 import qualified Data.Map as M
10 import qualified Data.Set as S
11 import qualified Data.ByteString.Lazy as B
12 import System.Plugins
13
14 import Foreign.Ptr
15 import Foreign.C.Types
16 import Foreign.C.String
17
18 import JVM.ClassFile
19
20 import Harpy
21 import Harpy.X86Disassembler
22
23 #ifdef DEBUG
24 import Text.Printf
25 #endif
26
27 import Mate.BasicBlocks
28 import Mate.Types
29 import Mate.X86CodeGen
30 import Mate.ClassPool
31 import Mate.Debug
32 import Mate.Utilities
33
34 foreign import ccall "dynamic"
35    code_void :: FunPtr (IO ()) -> IO ()
36
37
38 getMethodEntry :: CUInt -> CUInt -> IO CUInt
39 getMethodEntry signal_from methodtable = do
40   mmap <- getMethodMap
41   tmap <- getTrapMap
42   vmap <- getVirtualMap
43
44   let w32_from = fromIntegral signal_from
45   let mi = tmap M.! w32_from
46   let mi'@(MethodInfo method cm sig) =
47         case mi of
48           (StaticMethod x) -> x
49           (VirtualMethod   _ (MethodInfo methname _ msig)) -> newMi methname msig
50           (InterfaceMethod _ (MethodInfo methname _ msig)) -> newMi methname msig
51           _ -> error "getMethodEntry: no TrapCause found. abort."
52         where newMi mn = MethodInfo mn (vmap M.! fromIntegral methodtable)
53   -- bernhard (TODO): doesn't work with gnu classpath at some point. didn't
54   --                  figured out the problem yet :/ therefore, I have no
55   --                  testcase for replaying the situation.
56   -- setTrapMap $ M.delete w32_from tmap
57   entryaddr <- case M.lookup mi' mmap of
58     Nothing -> do
59       cls <- getClassFile cm
60       printfMp "getMethodEntry(from 0x%08x): no method \"%s\" found. compile it\n" w32_from (show mi')
61       mm <- lookupMethodRecursive method sig [] cls
62       case mm of
63         Just (mm', clsnames, cls') -> do
64             let flags = methodAccessFlags mm'
65             if S.member ACC_NATIVE flags
66               then do
67                 -- TODO(bernhard): cleaner please... *do'h*
68                 let sym1 = replace "/" "_" $ toString cm
69                     parenth = replace "(" "_" $ replace ")" "_" $ toString $ encode sig
70                     sym2 = replace ";" "_" $ replace "/" "_" parenth
71                     symbol = sym1 ++ "__" ++ toString method ++ "__" ++ sym2
72                 printfMp "native-call: symbol: %s\n" symbol
73                 nf <- loadNativeFunction symbol
74                 setMethodMap $ M.insert mi' nf mmap
75                 return nf
76               else do
77                 hmap <- parseMethod cls' method sig
78                 case hmap of
79                   Just hmap' -> do
80                     entry <- compileBB hmap' (MethodInfo method (thisClass cls') sig)
81                     addMethodRef entry mi' clsnames
82                     return $ fromIntegral entry
83                   Nothing -> error $ show method ++ " not found. abort"
84         Nothing -> error $ show method ++ " not found. abort"
85     Just w32 -> return w32
86   return $ fromIntegral entryaddr
87
88 lookupMethodRecursive :: B.ByteString -> MethodSignature -> [B.ByteString] -> Class Direct
89                          -> IO (Maybe (Method Direct, [B.ByteString], Class Direct))
90 lookupMethodRecursive name sig clsnames cls =
91   case res of
92     Just x -> return $ Just (x, nextclsn, cls)
93     Nothing -> if thisname == "java/lang/Object"
94       then return Nothing
95       else do
96         supercl <- getClassFile (superClass cls)
97         lookupMethodRecursive name sig nextclsn supercl
98   where
99   res = lookupMethodSig name sig cls
100   thisname = thisClass cls
101   nextclsn :: [B.ByteString]
102   nextclsn = thisname:clsnames
103
104 -- TODO(bernhard): UBERHAX.  ghc patch?
105 foreign import ccall safe "lookupSymbol"
106    c_lookupSymbol :: CString -> IO (Ptr a)
107
108 loadNativeFunction :: String -> IO Word32
109 loadNativeFunction sym = do
110         _ <- loadRawObject "ffi/native.o"
111         -- TODO(bernhard): WTF
112         resolveObjs (return ())
113         ptr <- withCString sym c_lookupSymbol
114         if ptr == nullPtr
115           then error $ "dyn. loading of \"" ++ sym ++ "\" failed."
116           else return $ fromIntegral $ ptrToIntPtr ptr
117
118 -- t_01 :: IO ()
119 -- t_01 = do
120 --   (entry, _) <- testCase "./tests/Fib.class" "fib"
121 --   let int_entry = ((fromIntegral $ ptrToIntPtr entry) :: Word32)
122 --   let mmap = M.insert ("fib" :: String) int_entry M.empty
123 --   mapM_ (\(x,y) -> printf "%s at 0x%08x\n" x y) $ M.toList mmap
124 --   mmap2ptr mmap >>= set_mmap
125 --   demo_mmap -- access Data.Map from C
126
127 addMethodRef :: Word32 -> MethodInfo -> [B.ByteString] -> IO ()
128 addMethodRef entry (MethodInfo mmname _ msig) clsnames = do
129   mmap <- getMethodMap
130   let newmap = foldr (\i -> M.insert (MethodInfo mmname i msig) entry) M.empty clsnames
131   setMethodMap $ mmap `M.union` newmap
132
133
134 compileBB :: MapBB -> MethodInfo -> IO Word32
135 compileBB hmap methodinfo = do
136   tmap <- getTrapMap
137
138   cls <- getClassFile (methClassName methodinfo)
139   let ebb = emitFromBB (methName methodinfo) (methSignature methodinfo) cls hmap
140   (_, Right right) <- runCodeGen ebb () ()
141
142   let ((entry, _, _, new_tmap), _) = right
143   setTrapMap $ tmap `M.union` new_tmap -- prefers elements in tmap
144
145   printfJit "generated code of \"%s\" from \"%s\":\n" (toString $ methName methodinfo) (toString $ methClassName methodinfo)
146   mapM_ (printfJit "%s\n" . showAtt) (snd right)
147   printfJit "\n\n"
148   -- UNCOMMENT NEXT LINES FOR GDB FUN
149   -- if (toString $ methName methodinfo) == "thejavamethodIwant2debug"
150   --   then putStrLn "press CTRL+C now for setting a breakpoint. then `c' and ENTER for continue" >> getLine
151   --   else return "foo"
152   -- (1) build a debug build (see HACKING) and execute `make tests/Fib.gdb'
153   --     for example, where the suffix is important
154   -- (2) on getLine, press CTRL+C
155   -- (3) `br *0x<addr>'; obtain the address from the disasm above
156   -- (4) `cont' and press enter
157   return $ fromIntegral $ ptrToIntPtr entry
158
159
160 executeFuncPtr :: Word32 -> IO ()
161 executeFuncPtr entry =
162   code_void ((castPtrToFunPtr $ intPtrToPtr $ fromIntegral entry) :: FunPtr (IO ()))