ikvm-fork/ikvmc/Compiler.cs

475 строки
14 KiB
C#
Исходник Обычный вид История

2002-12-18 19:00:25 +03:00
/*
2004-04-02 12:13:01 +04:00
Copyright (C) 2002, 2003, 2004 Jeroen Frijters
2002-12-18 19:00:25 +03:00
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
Jeroen Frijters
jeroen@frijters.net
*/
using System;
using System.Collections;
using System.IO;
using System.Reflection;
2003-01-08 16:35:05 +03:00
using ICSharpCode.SharpZipLib.Zip;
2002-12-18 19:00:25 +03:00
2003-04-26 16:13:02 +04:00
class Compiler
2002-12-18 19:00:25 +03:00
{
2003-12-20 01:19:18 +03:00
private static string manifestMainClass;
2004-01-28 14:28:16 +03:00
private static int itemsProcessed;
2004-02-02 12:46:13 +03:00
private static ArrayList classes = new ArrayList();
private static Hashtable resources = new Hashtable();
2003-12-20 01:19:18 +03:00
2002-12-18 19:00:25 +03:00
private static ArrayList GetArgs(string[] args)
{
ArrayList arglist = new ArrayList();
foreach(string s in args)
{
if(s.StartsWith("@"))
{
using(StreamReader sr = new StreamReader(s.Substring(1)))
{
string line;
while((line = sr.ReadLine()) != null)
{
arglist.Add(line);
}
}
}
else
{
arglist.Add(s);
}
}
return arglist;
}
2004-05-25 11:14:39 +04:00
static void Main(string[] args)
{
// FXBUG if we run a static initializer that starts a thread, we would never end,
// so we force an exit here
Environment.Exit(RealMain(args));
}
static int RealMain(string[] args)
2002-12-18 19:00:25 +03:00
{
2004-03-16 20:10:09 +03:00
AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
2004-03-08 18:18:47 +03:00
System.Threading.Thread.CurrentThread.Name = "compiler";
Tracer.EnableTraceForDebug();
2002-12-18 19:00:25 +03:00
System.Reflection.Emit.PEFileKinds target = System.Reflection.Emit.PEFileKinds.ConsoleApplication;
2003-12-20 01:19:18 +03:00
bool guessFileKind = true;
2002-12-18 19:00:25 +03:00
string assemblyname = null;
string outputfile = null;
2004-01-11 16:14:42 +03:00
string version = "0.0.0.0";
string keyfile = null;
bool targetIsModule = false;
2002-12-18 19:00:25 +03:00
string main = null;
2004-03-08 18:18:47 +03:00
string defaultAssemblyName = null;
string remapfile = null;
2002-12-18 19:00:25 +03:00
bool nojni = false;
2003-08-21 14:06:34 +04:00
ArrayList classesToExclude = new ArrayList();
2002-12-18 19:00:25 +03:00
ArrayList references = new ArrayList();
ArrayList arglist = GetArgs(args);
if(arglist.Count == 0)
{
Console.Error.WriteLine("usage: ikvmc [-options] <classOrJar1> ... <classOrJarN>");
Console.Error.WriteLine();
Console.Error.WriteLine("options:");
2003-12-20 01:19:18 +03:00
Console.Error.WriteLine(" -out:<outputfile> Specify the output filename");
Console.Error.WriteLine(" -assembly:<name> Specify assembly name");
2002-12-18 19:00:25 +03:00
Console.Error.WriteLine(" -target:exe Build a console executable");
Console.Error.WriteLine(" -target:winexe Build a windows executable");
Console.Error.WriteLine(" -target:library Build a library");
2004-01-11 16:14:42 +03:00
Console.Error.WriteLine(" -target:module Build a module for use by the linker");
Console.Error.WriteLine(" -keyfile:keyfilename Use keyfile to sign the assembly");
Console.Error.WriteLine(" -version:M.m.b.r Assembly version");
2003-12-20 01:19:18 +03:00
Console.Error.WriteLine(" -main:<class> Specify the class containing the main method");
2003-08-28 17:19:39 +04:00
Console.Error.WriteLine(" -reference:<filespec> Reference an assembly");
2002-12-18 19:00:25 +03:00
Console.Error.WriteLine(" -recurse:<filespec> Recurse directory and include matching files");
Console.Error.WriteLine(" -nojni Do not generate JNI stub for native methods");
2003-02-25 18:43:25 +03:00
Console.Error.WriteLine(" -resource:<name>=<path> Include file as Java resource");
2003-08-21 14:06:34 +04:00
Console.Error.WriteLine(" -exclude:<filename> A file containing a list of classes to exclude");
Console.Error.WriteLine(" -debug Creates debugging information for the output file");
2004-03-26 13:19:21 +03:00
Console.Error.WriteLine(" -srcpath:<path> Prepend path and package name to source file");
2004-03-08 18:18:47 +03:00
Console.Error.WriteLine(" -Xtrace:<string> Displays all tracepoints with the given name");
Console.Error.WriteLine(" -Xmethodtrace:<string> Builds method trace into the specified output methods");
2002-12-18 19:00:25 +03:00
return 1;
}
foreach(string s in arglist)
{
if(s[0] == '-')
{
if(s.StartsWith("-out:"))
{
outputfile = s.Substring(5);
}
2004-03-08 18:18:47 +03:00
else if(s.StartsWith("-Xtrace:"))
{
Tracer.SetTraceLevel(s.Substring(8));
}
else if(s.StartsWith("-Xmethodtrace:"))
{
Tracer.HandleMethodTrace(s.Substring(14));
}
2002-12-18 19:00:25 +03:00
else if(s.StartsWith("-assembly:"))
{
assemblyname = s.Substring(10);
}
else if(s.StartsWith("-target:"))
{
switch(s)
{
case "-target:exe":
target = System.Reflection.Emit.PEFileKinds.ConsoleApplication;
2003-12-20 01:19:18 +03:00
guessFileKind = false;
2002-12-18 19:00:25 +03:00
break;
case "-target:winexe":
target = System.Reflection.Emit.PEFileKinds.WindowApplication;
2003-12-20 01:19:18 +03:00
guessFileKind = false;
2002-12-18 19:00:25 +03:00
break;
2004-01-11 16:14:42 +03:00
case "-target:module":
targetIsModule = true;
target = System.Reflection.Emit.PEFileKinds.Dll;
guessFileKind = false;
break;
2002-12-18 19:00:25 +03:00
case "-target:library":
target = System.Reflection.Emit.PEFileKinds.Dll;
2003-12-20 01:19:18 +03:00
guessFileKind = false;
break;
default:
Console.Error.WriteLine("Warning: unrecognized option: {0}", s);
2002-12-18 19:00:25 +03:00
break;
}
}
else if(s.StartsWith("-main:"))
{
main = s.Substring(6);
}
else if(s.StartsWith("-reference:"))
{
2004-02-06 22:09:32 +03:00
string r = s.Substring(11);
string path = Path.GetDirectoryName(r);
string[] files = Directory.GetFiles(path == "" ? "." : path, Path.GetFileName(r));
if(files.Length == 0)
{
Console.Error.WriteLine("Error: reference not found: {0}", r);
return 1;
}
2003-08-28 17:19:39 +04:00
foreach(string f in files)
{
references.Add(f);
}
2002-12-18 19:00:25 +03:00
}
else if(s.StartsWith("-recurse:"))
{
string spec = s.Substring(9);
2003-04-26 16:13:02 +04:00
if(Directory.Exists(spec))
{
2004-03-16 20:10:09 +03:00
// NOTE we're appending a DirectorySeparatorChar to make sure that dir.FullName always
// ends with a separator (multiple separators are automatically collapsed into one).
// This is important because later on we will be using baseDir.FullName to make
// an absolute path relative again.
DirectoryInfo dir = new DirectoryInfo(spec + Path.DirectorySeparatorChar);
2004-02-02 12:46:13 +03:00
Recurse(dir, dir, "*");
2003-04-26 16:13:02 +04:00
}
else
{
2004-03-16 20:10:09 +03:00
// see comment above about Path.DirectorySeparatorChar
DirectoryInfo dir = new DirectoryInfo(Path.GetDirectoryName(spec) + Path.DirectorySeparatorChar);
2004-02-02 12:46:13 +03:00
Recurse(dir, dir, Path.GetFileName(spec));
2003-04-26 16:13:02 +04:00
}
2002-12-18 19:00:25 +03:00
}
2003-02-25 18:43:25 +03:00
else if(s.StartsWith("-resource:"))
{
string[] spec = s.Substring(10).Split('=');
if(resources.ContainsKey(spec[0]))
{
Console.Error.WriteLine("Warning: skipping resource (name clash): " + spec[0]);
}
else
{
using(FileStream fs = new FileStream(spec[1], FileMode.Open))
{
byte[] b = new byte[fs.Length];
fs.Read(b, 0, b.Length);
resources.Add(spec[0], b);
}
}
}
2002-12-18 19:00:25 +03:00
else if(s == "-nojni")
{
nojni = true;
}
2003-08-21 14:06:34 +04:00
else if(s.StartsWith("-exclude:"))
{
ProcessExclusionFile(classesToExclude, s.Substring(9));
}
2004-01-11 16:14:42 +03:00
else if(s.StartsWith("-version:"))
{
version = s.Substring(9);
}
else if(s.StartsWith("-keyfile:"))
{
keyfile = s.Substring(9);
}
2003-08-21 14:06:34 +04:00
else if(s == "-debug")
{
JVM.Debug = true;
}
2004-03-26 13:19:21 +03:00
else if(s.StartsWith("-srcpath:"))
{
JVM.SourcePath = s.Substring(9);
}
2004-03-08 18:18:47 +03:00
else if(s.StartsWith("-remap:"))
{
remapfile = s.Substring(7);
}
2002-12-18 19:00:25 +03:00
else
{
2003-12-20 01:19:18 +03:00
Console.Error.WriteLine("Warning: unrecognized option: {0}", s);
2002-12-18 19:00:25 +03:00
}
}
else
{
2004-03-08 18:18:47 +03:00
if(defaultAssemblyName == null)
2003-12-20 01:19:18 +03:00
{
2004-03-08 18:18:47 +03:00
defaultAssemblyName = new FileInfo(Path.GetFileName(s)).Name;
2003-12-20 01:19:18 +03:00
}
2003-04-26 16:13:02 +04:00
string path = Path.GetDirectoryName(s);
string[] files = Directory.GetFiles(path == "" ? "." : path, Path.GetFileName(s));
2003-12-20 01:19:18 +03:00
if(files.Length == 0)
{
Console.Error.WriteLine("Error: file not found: {0}", s);
return 1;
}
2003-04-26 16:13:02 +04:00
foreach(string f in files)
{
2004-02-02 12:46:13 +03:00
ProcessFile(null, f);
2003-04-26 16:13:02 +04:00
}
2002-12-18 19:00:25 +03:00
}
}
2004-01-28 14:28:16 +03:00
if(itemsProcessed == 0)
2002-12-18 19:00:25 +03:00
{
2003-12-20 01:19:18 +03:00
Console.Error.WriteLine("Error: at least one class or jar must be specified");
2002-12-18 19:00:25 +03:00
return 1;
}
if(assemblyname == null)
{
2004-03-08 18:18:47 +03:00
string basename = outputfile == null ? defaultAssemblyName : new FileInfo(outputfile).Name;
2003-12-20 01:19:18 +03:00
int idx = basename.LastIndexOf('.');
2002-12-18 19:00:25 +03:00
if(idx > 0)
{
2003-12-20 01:19:18 +03:00
assemblyname = basename.Substring(0, idx);
2002-12-18 19:00:25 +03:00
}
else
{
2003-12-20 01:19:18 +03:00
assemblyname = basename;
2002-12-18 19:00:25 +03:00
}
}
2003-12-20 01:19:18 +03:00
if(outputfile != null && guessFileKind)
2002-12-18 19:00:25 +03:00
{
2003-12-20 01:19:18 +03:00
if(outputfile.ToLower().EndsWith(".dll"))
{
target = System.Reflection.Emit.PEFileKinds.Dll;
}
guessFileKind = false;
}
2004-04-02 12:13:01 +04:00
if(main == null && manifestMainClass != null && (guessFileKind || target != System.Reflection.Emit.PEFileKinds.Dll))
2003-12-20 01:19:18 +03:00
{
Console.Error.WriteLine("Note: using main class {0} based on jar manifest", manifestMainClass);
main = manifestMainClass;
2002-12-18 19:00:25 +03:00
}
2003-02-20 17:18:38 +03:00
try
{
2004-03-08 18:18:47 +03:00
JVM.Compile(outputfile, keyfile, version, targetIsModule, assemblyname, main, target, guessFileKind, (byte[][])classes.ToArray(typeof(byte[])), (string[])references.ToArray(typeof(string)), nojni, resources, (string[])classesToExclude.ToArray(typeof(string)), remapfile);
2003-02-20 17:18:38 +03:00
return 0;
}
catch(Exception x)
{
Console.Error.WriteLine(x);
return 1;
}
2002-12-18 19:00:25 +03:00
}
2003-01-08 16:35:05 +03:00
private static byte[] ReadFromZip(ZipFile zf, ZipEntry ze)
{
byte[] buf = new byte[ze.Size];
int pos = 0;
Stream s = zf.GetInputStream(ze);
while(pos < buf.Length)
{
pos += s.Read(buf, pos, buf.Length - pos);
}
return buf;
}
2004-02-02 12:46:13 +03:00
private static void ProcessZipFile(string file)
{
ZipFile zf = new ZipFile(file);
try
{
foreach(ZipEntry ze in zf)
{
if(ze.Name.ToLower().EndsWith(".class"))
{
classes.Add(ReadFromZip(zf, ze));
itemsProcessed++;
}
else
{
// if it's not a class, we treat it as a resource and the manifest
// is examined to find the Main-Class
if(ze.Name == "META-INF/MANIFEST.MF" && manifestMainClass == null)
{
// read main class from manifest
// TODO find out if we can use other information from manifest
StreamReader rdr = new StreamReader(zf.GetInputStream(ze));
string line;
while((line = rdr.ReadLine()) != null)
{
if(line.StartsWith("Main-Class: "))
{
manifestMainClass = line.Substring(12);
break;
}
}
}
if(resources.ContainsKey(ze.Name))
{
Console.Error.WriteLine("Warning: skipping resource (name clash): " + ze.Name);
}
else
{
resources.Add(ze.Name, ReadFromZip(zf, ze));
itemsProcessed++;
}
}
}
}
finally
{
zf.Close();
}
}
private static void ProcessFile(DirectoryInfo baseDir, string file)
2002-12-18 19:00:25 +03:00
{
2003-04-26 16:13:02 +04:00
switch(new FileInfo(file).Extension.ToLower())
2002-12-18 19:00:25 +03:00
{
2003-04-26 16:13:02 +04:00
case ".class":
using(FileStream fs = new FileStream(file, FileMode.Open))
2002-12-18 19:00:25 +03:00
{
2003-04-26 16:13:02 +04:00
byte[] b = new byte[fs.Length];
fs.Read(b, 0, b.Length);
2004-01-28 14:28:16 +03:00
itemsProcessed++;
2003-04-26 16:13:02 +04:00
classes.Add(b);
}
break;
case ".jar":
case ".zip":
try
{
2004-02-02 12:46:13 +03:00
ProcessZipFile(file);
2002-12-18 19:00:25 +03:00
}
2004-02-02 12:46:13 +03:00
catch(ICSharpCode.SharpZipLib.ZipException x)
2003-04-26 16:13:02 +04:00
{
2004-02-02 12:46:13 +03:00
Console.Error.WriteLine("Warning: error reading {0}: {1}", file, x.Message);
2003-04-26 16:13:02 +04:00
}
break;
default:
2003-08-08 16:37:14 +04:00
{
if(baseDir == null)
{
2003-12-20 01:19:18 +03:00
Console.Error.WriteLine("Warning: unknown file type: {0}", file);
2003-08-08 16:37:14 +04:00
}
else
{
// include as resource
2003-08-21 14:06:34 +04:00
try
2003-08-08 16:37:14 +04:00
{
2003-08-21 14:06:34 +04:00
using(FileStream fs = new FileStream(file, FileMode.Open))
{
byte[] b = new byte[fs.Length];
fs.Read(b, 0, b.Length);
// HACK very lame way to extract the resource name (by chopping off the base directory)
2004-03-16 20:10:09 +03:00
string name = file.Substring(baseDir.FullName.Length);
2003-08-21 14:06:34 +04:00
name = name.Replace('\\', '/');
resources.Add(name, b);
2004-01-28 14:28:16 +03:00
itemsProcessed++;
2003-08-21 14:06:34 +04:00
}
}
catch(UnauthorizedAccessException)
{
2003-12-20 01:19:18 +03:00
Console.Error.WriteLine("Warning: error reading file {0}: Access Denied", file);
2003-08-08 16:37:14 +04:00
}
}
2003-04-26 16:13:02 +04:00
break;
2003-08-08 16:37:14 +04:00
}
2002-12-18 19:00:25 +03:00
}
}
2004-02-02 12:46:13 +03:00
private static void Recurse(DirectoryInfo baseDir, DirectoryInfo dir, string spec)
2002-12-18 19:00:25 +03:00
{
foreach(FileInfo file in dir.GetFiles(spec))
{
2004-02-02 12:46:13 +03:00
ProcessFile(baseDir, file.FullName);
2002-12-18 19:00:25 +03:00
}
foreach(DirectoryInfo sub in dir.GetDirectories())
{
2004-02-02 12:46:13 +03:00
Recurse(baseDir, sub, spec);
2002-12-18 19:00:25 +03:00
}
}
2003-08-21 14:06:34 +04:00
//This processes an exclusion file with a single regular expression per line
private static void ProcessExclusionFile(ArrayList classesToExclude, String filename)
{
try
{
using(StreamReader file = new StreamReader(filename))
{
String line;
while((line = file.ReadLine()) != null)
{
line = line.Trim();
if(!line.StartsWith("//") && line.Length != 0)
{
classesToExclude.Add(line);
}
}
}
}
catch(FileNotFoundException)
{
2003-12-20 01:19:18 +03:00
Console.Error.WriteLine("Warning: could not find exclusion file '{0}'", filename);
2003-08-21 14:06:34 +04:00
}
}
2004-03-16 20:10:09 +03:00
private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
// make sure all the referenced assemblies are visible (they are loaded with LoadFrom, so
// they end up in the LoadFrom context [unless they happen to be available in one of the probe paths])
foreach(Assembly a in AppDomain.CurrentDomain.GetAssemblies())
{
if(a.FullName == args.Name)
{
return a;
}
}
return null;
}
2002-12-18 19:00:25 +03:00
}