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