7a0cda170964a761e50affbfe0a3c31d43e940d0
[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   setTrapMap $ M.delete w32_from tmap
54   case M.lookup mi' mmap of
55     Nothing -> do
56       cls <- getClassFile cm
57       printfMp "getMethodEntry(from 0x%08x): no method \"%s\" found. compile it\n" w32_from (show mi')
58       mm <- lookupMethodRecursive method sig [] cls
59       case mm of
60         Just (mm', clsnames, cls') -> do
61             let flags = methodAccessFlags mm'
62             if S.member ACC_NATIVE flags
63               then do
64                 -- TODO(bernhard): cleaner please... *do'h*
65                 let sym1 = replace "/" "_" $ toString cm
66                     parenth = replace "(" "_" $ replace ")" "_" $ toString $ encode sig
67                     sym2 = replace ";" "_" $ replace "/" "_" parenth
68                     symbol = sym1 ++ "__" ++ toString method ++ "__" ++ sym2
69                 printfMp "native-call: symbol: %s\n" symbol
70                 nf <- loadNativeFunction symbol
71                 let w32_nf = fromIntegral nf
72                 setMethodMap $ M.insert mi' w32_nf mmap
73                 return nf
74               else do
75                 hmap <- parseMethod cls' method sig
76                 case hmap of
77                   Just hmap' -> do
78                     entry <- compileBB hmap' (MethodInfo method (thisClass cls') sig)
79                     addMethodRef entry mi' clsnames
80                     return $ fromIntegral entry
81                   Nothing -> error $ show method ++ " not found. abort"
82         Nothing -> error $ show method ++ " not found. abort"
83     Just w32 -> return (fromIntegral w32)
84
85 lookupMethodRecursive :: B.ByteString -> MethodSignature -> [B.ByteString] -> Class Direct
86                          -> IO (Maybe (Method Direct, [B.ByteString], Class Direct))
87 lookupMethodRecursive name sig clsnames cls =
88   case res of
89     Just x -> return $ Just (x, nextclsn, cls)
90     Nothing -> if thisname == "java/lang/Object"
91       then return Nothing
92       else do
93         supercl <- getClassFile (superClass cls)
94         lookupMethodRecursive name sig nextclsn supercl
95   where
96   res = lookupMethodSig name sig cls
97   thisname = thisClass cls
98   nextclsn :: [B.ByteString]
99   nextclsn = thisname:clsnames
100
101 -- TODO(bernhard): UBERHAX.  ghc patch?
102 foreign import ccall safe "lookupSymbol"
103    c_lookupSymbol :: CString -> IO (Ptr a)
104
105 loadNativeFunction :: String -> IO CUInt
106 loadNativeFunction sym = do
107         _ <- loadRawObject "ffi/native.o"
108         -- TODO(bernhard): WTF
109         resolveObjs (return ())
110         ptr <- withCString sym c_lookupSymbol
111         if ptr == nullPtr
112           then error $ "dyn. loading of \"" ++ sym ++ "\" failed."
113           else return $ fromIntegral $ ptrToIntPtr ptr
114
115 -- t_01 :: IO ()
116 -- t_01 = do
117 --   (entry, _) <- testCase "./tests/Fib.class" "fib"
118 --   let int_entry = ((fromIntegral $ ptrToIntPtr entry) :: Word32)
119 --   let mmap = M.insert ("fib" :: String) int_entry M.empty
120 --   mapM_ (\(x,y) -> printf "%s at 0x%08x\n" x y) $ M.toList mmap
121 --   mmap2ptr mmap >>= set_mmap
122 --   demo_mmap -- access Data.Map from C
123
124 addMethodRef :: Word32 -> MethodInfo -> [B.ByteString] -> IO ()
125 addMethodRef entry (MethodInfo mmname _ msig) clsnames = do
126   mmap <- getMethodMap
127   let newmap = M.fromList $ map (\x -> (MethodInfo mmname x msig, entry)) clsnames
128   setMethodMap $ mmap `M.union` newmap
129
130
131 compileBB :: MapBB -> MethodInfo -> IO Word32
132 compileBB hmap methodinfo = do
133   tmap <- getTrapMap
134
135   cls <- getClassFile (methClassName methodinfo)
136   let ebb = emitFromBB (methName methodinfo) (methSignature methodinfo) cls hmap
137   (_, Right right) <- runCodeGen ebb () ()
138
139   let ((entry, _, _, new_tmap), _) = right
140   setTrapMap $ tmap `M.union` new_tmap -- prefers elements in tmap
141
142   printfJit "generated code of \"%s\" from \"%s\":\n" (toString $ methName methodinfo) (toString $ methClassName methodinfo)
143   mapM_ (printfJit "%s\n" . showAtt) (snd right)
144   printfJit "\n\n"
145   -- UNCOMMENT NEXT LINES FOR GDB FUN
146   --if (toString $ methName methodinfo) == "thejavamethodIwant2debug"
147   --  then getLine
148   --  else return "foo"
149   -- (1) start it with `gdb ./mate' and then `run <classfile>'
150   -- (2) on getLine, press ctrl+c
151   -- (3) `br *0x<addr>'; obtain the address from the disasm above
152   -- (4) `cont' and press enter
153   return $ fromIntegral $ ptrToIntPtr entry
154
155
156 executeFuncPtr :: Word32 -> IO ()
157 executeFuncPtr entry =
158   code_void ((castPtrToFunPtr $ intPtrToPtr $ fromIntegral entry) :: FunPtr (IO ()))