methodlookup: unique identifier for methods are name+signature
[mate.git] / Mate.hs
1 {-# LANGUAGE CPP #-}
2 {-# LANGUAGE OverloadedStrings #-}
3 #include "debug.h"
4 module Main where
5
6 import System.Environment
7 import Data.Char
8 import Data.List
9 import Data.List.Split
10 import qualified Data.ByteString.Lazy as B
11
12 #ifdef DEBUG
13 import Text.Printf
14 #endif
15 import JVM.ClassFile
16 import Java.JAR
17
18 import Mate.BasicBlocks
19 import Mate.MethodPool
20 import Mate.Types
21 import Mate.ClassPool
22 import Mate.X86TrapHandling
23
24 main ::  IO ()
25 main = do
26   args <- getArgs
27   register_signal
28   parseArgs args False
29
30 parseArgs :: [String] -> Bool -> IO ()
31 parseArgs ("-jar":jarpath:_) stdcp = do
32   if not stdcp then addClassPath "./" else return ()
33   addClassPathJAR jarpath
34   res <- readMainClass jarpath
35   case res of
36     Nothing -> error "JAR: no MainClass entry found. Try to pass the jar file via -cp instead."
37     Just mc -> do
38       let bclspath = B.pack $ map (fromIntegral . ord) mc
39       cls <- getClassFile bclspath
40       executeMain bclspath cls
41 parseArgs ("-cp":cps) cpset = parseArgs ("-classpath":cps) cpset
42 parseArgs ("-classpath":cps:xs) False = do
43   let paths = splitOn ":" cps
44   mapM_ addStuff paths
45   parseArgs xs True
46   where
47   addStuff :: String -> IO ()
48   addStuff x
49     | ".jar" `isSuffixOf` x = addClassPathJAR x
50     | otherwise = addClassPath $ x ++ "/"
51 parseArgs ("-classpath":xs) _ = parseArgs ("-":xs) True -- usage
52 parseArgs (('-':_):_) _ = error "Usage: mate [-cp|-classpath <cp1:cp2:..>] [<class-file> | -jar <jar-file>]"
53 -- first argument which isn't prefixed by '-' should be a class file
54 parseArgs (clspath:_) stdcp = do
55   if not stdcp then addClassPath "./" else return ()
56   let bclspath = B.pack $ map (fromIntegral . ord) clspath
57   cls <- getClassFile bclspath
58   executeMain bclspath cls
59 parseArgs _ _ = parseArgs ["-"] False
60
61
62 executeMain :: B.ByteString -> Class Direct -> IO ()
63 executeMain bclspath cls = do
64   let methods = classMethods cls; methods :: [Method Direct]
65   case find (\x -> methodName x == "main") methods of
66     Just m -> do
67       let mi = MethodInfo "main" bclspath $ methodSignature m
68       hmap <- parseMethod cls "main" $ methodSignature m
69       case hmap of
70         Just hmap' -> do
71           entry <- compileBB hmap' mi
72           addMethodRef entry mi [bclspath]
73 #ifdef DEBUG
74           printf "executing `main' now:\n"
75 #endif
76           executeFuncPtr entry
77         Nothing -> error "main not found"
78     Nothing -> error "main not found"