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