Esempio n. 1
0
        private static void Create(CompilerClassLoader loader, string proxy, TypeWrapper[] interfaces)
        {
            List <ProxyMethod> methods;

            try
            {
                methods = CheckAndCollect(loader, interfaces);
            }
            catch (RetargetableJavaException x)
            {
                StaticCompiler.IssueMessage(Message.UnableToCreateProxy, proxy, x.Message);
                return;
            }
            catch (ProxyException x)
            {
                StaticCompiler.IssueMessage(Message.UnableToCreateProxy, proxy, x.Message);
                return;
            }
            CreateNoFail(loader, interfaces, methods);
        }
Esempio n. 2
0
 internal static void Create(CompilerClassLoader loader, string proxy)
 {
     string[]      interfaces = proxy.Split(',');
     TypeWrapper[] wrappers   = new TypeWrapper[interfaces.Length];
     for (int i = 0; i < interfaces.Length; i++)
     {
         try
         {
             wrappers[i] = loader.LoadClassByDottedNameFast(interfaces[i]);
         }
         catch (RetargetableJavaException)
         {
         }
         if (wrappers[i] == null)
         {
             StaticCompiler.IssueMessage(Message.UnableToCreateProxy, proxy, "unable to load interface " + interfaces[i]);
             return;
         }
     }
     Create(loader, proxy, wrappers);
 }
        public void setup()
        {
            BasePath = @"IKVM\ikvm-7.2.4630.5\bin\";
            //IkvmcAssembly = "ikvmc.exe".assembly();

            IkvmcAssembly  = BasePath.add(@"ikvmc.exe").assembly();
            StaticCompiler = IkvmcAssembly.type("StaticCompiler");
            //IkvmRuntime = StaticCompiler.invokeStatic("LoadFile",Environment.CurrentDirectory.pathCombine("IKVM.Runtime.dll"));
            IkvmRuntime = StaticCompiler.invokeStatic("LoadFile", BasePath.add("IKVM.Runtime.dll").assembly().Location);
            PublicDI.reflection.setField((FieldInfo)StaticCompiler.field("runtimeAssembly"), IkvmRuntime);

            //IkvmRuntimeJni = StaticCompiler.invokeStatic("LoadFile",Environment.CurrentDirectory.pathCombine("IKVM.Runtime.JNI.dll"));
            IkvmRuntimeJni = StaticCompiler.invokeStatic("LoadFile", BasePath.add("IKVM.Runtime.JNI.dll").assembly().Location);
            PublicDI.reflection.setField((FieldInfo)StaticCompiler.field("runtimeJniAssembly"), IkvmRuntimeJni);

            IkvmcCompiler = IkvmcAssembly.type("IkvmcCompiler").ctor();

            CompilerOptions = IkvmcAssembly.type("CompilerOptions").ctor();
            PublicDI.reflection.setField((FieldInfo)StaticCompiler.field("toplevel"), CompilerOptions);
            //ensure assemblies are loaded into memory()
            loadCoreIKVMAssemblies();
        }
Esempio n. 4
0
 private static bool Reflection_getCallerClass(EmitIntrinsicContext eic)
 {
     if (eic.Caller.HasCallerID)
     {
         int arg = eic.Caller.GetParametersForDefineMethod().Length - 1;
         if (!eic.Caller.IsStatic)
         {
             arg++;
         }
         eic.Emitter.EmitLdarg(arg);
         MethodWrapper mw;
         if (MatchInvokeStatic(eic, 1, "java.lang.ClassLoader", "getClassLoader", "(Ljava.lang.Class;)Ljava.lang.ClassLoader;"))
         {
             eic.PatchOpCode(1, NormalizedByteCode.__nop);
             mw = [email protected]("getCallerClassLoader", "()Ljava.lang.ClassLoader;", false);
         }
         else
         {
             mw = [email protected]("getCallerClass", "()Ljava.lang.Class;", false);
         }
         mw.Link();
         mw.EmitCallvirt(eic.Emitter);
         return(true);
     }
     else if (DynamicTypeWrapper.RequiresDynamicReflectionCallerClass(eic.ClassFile.Name, eic.Caller.Name, eic.Caller.Signature))
     {
         // since the non-intrinsic version of Reflection.getCallerClass() always throws an exception, we have to redirect to the dynamic version
         MethodWrapper getCallerClass = ClassLoaderWrapper.LoadClassCritical("sun.reflect.Reflection").GetMethodWrapper("getCallerClass", "(I)Ljava.lang.Class;", false);
         getCallerClass.Link();
         eic.Emitter.EmitLdc_I4(2);
         getCallerClass.EmitCall(eic.Emitter);
         return(true);
     }
     else
     {
         StaticCompiler.IssueMessage(Message.ReflectionCallerClassRequiresCallerID, eic.ClassFile.Name, eic.Caller.Name, eic.Caller.Signature);
     }
     return(false);
 }
Esempio n. 5
0
        internal override void Generate(CodeGenContext context, CodeEmitter ilgen)
        {
            CodeEmitterLocal lb = (CodeEmitterLocal)context[Name];

            if (lb == null)
            {
                if (typeWrapper == null && typeType == null)
                {
                    Debug.Assert(Class == null ^ type == null);
                    if (type != null)
                    {
                        typeType = StaticCompiler.GetTypeForMapXml(context.ClassLoader, type);
                    }
                    else
                    {
                        typeWrapper = context.ClassLoader.LoadClassByDottedName(Class);
                    }
                }
                lb            = ilgen.DeclareLocal(typeType != null ? typeType : typeWrapper.TypeAsTBD);
                context[Name] = lb;
            }
            ilgen.Emit(OpCodes.Stloc, lb);
        }
        internal static bool Emit(DynamicTypeWrapper.FinishContext context, ClassFile classFile, int constantPoolIndex, ClassFile.ConstantPoolItemInvokeDynamic cpi, CodeEmitter ilgen)
        {
            ClassFile.BootstrapMethod bsm = classFile.GetBootstrapMethod(cpi.BootstrapMethod);
            if (!IsLambdaMetafactory(classFile, bsm) && !IsLambdaAltMetafactory(classFile, bsm))
            {
                return(false);
            }
            LambdaMetafactory lmf = context.GetValue <LambdaMetafactory>(constantPoolIndex);

            if (lmf.ctor == null && !lmf.EmitImpl(context, classFile, cpi, bsm, ilgen))
            {
#if STATIC_COMPILER
                if (context.TypeWrapper.GetClassLoader().DisableDynamicBinding)
                {
                    StaticCompiler.IssueMessage(Message.UnableToCreateLambdaFactory);
                }
#endif
                return(false);
            }
            ilgen.Emit(OpCodes.Newobj, lmf.ctor);
            // the CLR verification rules about type merging mean we have to explicitly cast to the interface type here
            ilgen.Emit(OpCodes.Castclass, cpi.GetRetType().TypeAsBaseType);
            return(true);
        }
Esempio n. 7
0
 internal override void Generate(CodeGenContext context, CodeEmitter ilgen)
 {
     // we don't use fw.EmitSet because we don't want automatic unboxing and whatever
     ilgen.Emit(OpCodes.Stsfld, StaticCompiler.GetFieldForMapXml(context.ClassLoader, Class, Name, Sig).GetField());
 }
Esempio n. 8
0
 internal override void Generate(CodeGenContext context, CodeEmitter ilgen)
 {
     ilgen.Emit(OpCodes.Ldflda, StaticCompiler.GetFieldForMapXml(context.ClassLoader, Class, Name, Sig).GetField());
 }
Esempio n. 9
0
 internal sealed override void Generate(CodeGenContext context, CodeEmitter ilgen)
 {
     Debug.Assert(Name != null);
     if (Name == ".ctor")
     {
         Debug.Assert(Class == null && type != null);
         Type[]          argTypes = context.ClassLoader.ArgTypeListFromSig(Sig);
         ConstructorInfo ci       = StaticCompiler.GetTypeForMapXml(context.ClassLoader, type).GetConstructor(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, CallingConventions.Standard, argTypes, null);
         if (ci == null)
         {
             throw new InvalidOperationException("Missing .ctor: " + type + "..ctor" + Sig);
         }
         ilgen.Emit(opcode, ci);
     }
     else
     {
         Debug.Assert(Class == null ^ type == null);
         if (Class != null)
         {
             Debug.Assert(Sig != null);
             MethodWrapper method = context.ClassLoader.LoadClassByDottedName(Class).GetMethodWrapper(Name, Sig, false);
             if (method == null)
             {
                 throw new InvalidOperationException("method not found: " + Class + "." + Name + Sig);
             }
             method.Link();
             // TODO this code is part of what Compiler.CastInterfaceArgs (in compiler.cs) does,
             // it would be nice if we could avoid this duplication...
             TypeWrapper[] argTypeWrappers = method.GetParameters();
             for (int i = 0; i < argTypeWrappers.Length; i++)
             {
                 if (argTypeWrappers[i].IsGhost)
                 {
                     CodeEmitterLocal[] temps = new CodeEmitterLocal[argTypeWrappers.Length + (method.IsStatic ? 0 : 1)];
                     for (int j = temps.Length - 1; j >= 0; j--)
                     {
                         TypeWrapper tw;
                         if (method.IsStatic)
                         {
                             tw = argTypeWrappers[j];
                         }
                         else
                         {
                             if (j == 0)
                             {
                                 tw = method.DeclaringType;
                             }
                             else
                             {
                                 tw = argTypeWrappers[j - 1];
                             }
                         }
                         if (tw.IsGhost)
                         {
                             tw.EmitConvStackTypeToSignatureType(ilgen, null);
                         }
                         temps[j] = ilgen.DeclareLocal(tw.TypeAsSignatureType);
                         ilgen.Emit(OpCodes.Stloc, temps[j]);
                     }
                     for (int j = 0; j < temps.Length; j++)
                     {
                         ilgen.Emit(OpCodes.Ldloc, temps[j]);
                     }
                     break;
                 }
             }
             if (opcode.Value == OpCodes.Call.Value)
             {
                 method.EmitCall(ilgen);
             }
             else if (opcode.Value == OpCodes.Callvirt.Value)
             {
                 method.EmitCallvirt(ilgen);
             }
             else if (opcode.Value == OpCodes.Newobj.Value)
             {
                 method.EmitNewobj(ilgen);
             }
             else
             {
                 // ldftn or ldvirtftn
                 ilgen.Emit(opcode, (MethodInfo)method.GetMethod());
             }
         }
         else
         {
             Type[] argTypes;
             if (Sig.StartsWith("("))
             {
                 argTypes = context.ClassLoader.ArgTypeListFromSig(Sig);
             }
             else if (Sig == "")
             {
                 argTypes = Type.EmptyTypes;
             }
             else
             {
                 string[] types = Sig.Split(';');
                 argTypes = new Type[types.Length];
                 for (int i = 0; i < types.Length; i++)
                 {
                     argTypes[i] = StaticCompiler.GetTypeForMapXml(context.ClassLoader, types[i]);
                 }
             }
             MethodInfo mi = StaticCompiler.GetTypeForMapXml(context.ClassLoader, type).GetMethod(Name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static, null, argTypes, null);
             if (mi == null)
             {
                 throw new InvalidOperationException("Missing method: " + type + "." + Name + Sig);
             }
             ilgen.Emit(opcode, mi);
         }
     }
 }
Esempio n. 10
0
    static int Main(string[] args)
    {
        IKVM.Internal.Tracer.EnableTraceConsoleListener();
        IKVM.Internal.Tracer.EnableTraceForDebug();
        string        assemblyNameOrPath = null;
        bool          continueOnError    = false;
        bool          autoLoadSharedClassLoaderAssemblies = false;
        List <string> references = new List <string>();
        List <string> libpaths   = new List <string>();
        bool          nostdlib   = false;
        bool          bootstrap  = false;
        string        outputFile = null;
        bool          forwarders = false;

        foreach (string s in args)
        {
            if (s.StartsWith("-") || assemblyNameOrPath != null)
            {
                if (s == "-serialver")
                {
                    Console.Error.WriteLine("The -serialver option is deprecated and will be removed in the future. Use -japi instead.");
                    includeSerialVersionUID = true;
                }
                else if (s == "-japi")
                {
                    includeSerialVersionUID    = true;
                    includeNonPublicInterfaces = true;
                    includeNonPublicMembers    = true;
                }
                else if (s == "-skiperror")
                {
                    continueOnError = true;
                }
                else if (s == "-shared")
                {
                    autoLoadSharedClassLoaderAssemblies = true;
                }
                else if (s.StartsWith("-r:") || s.StartsWith("-reference:"))
                {
                    references.Add(s.Substring(s.IndexOf(':') + 1));
                }
                else if (s == "-nostdlib")
                {
                    nostdlib = true;
                }
                else if (s.StartsWith("-lib:"))
                {
                    libpaths.Add(s.Substring(5));
                }
                else if (s == "-bootstrap")
                {
                    bootstrap = true;
                }
                else if (s.StartsWith("-out:"))
                {
                    outputFile = s.Substring(5);
                }
                else if (s.StartsWith("-namespace:"))
                {
                    namespaces.Add(s.Substring(11) + ".");
                }
                else if (s == "-forwarders")
                {
                    forwarders = true;
                }
                else if (s == "-parameters")
                {
                    includeParameterNames = true;
                }
                else
                {
                    // unrecognized option, or multiple assemblies, print usage message and exit
                    assemblyNameOrPath = null;
                    break;
                }
            }
            else
            {
                assemblyNameOrPath = s;
            }
        }
        if (assemblyNameOrPath == null)
        {
            Console.Error.WriteLine(GetVersionAndCopyrightInfo());
            Console.Error.WriteLine();
            Console.Error.WriteLine("usage: ikvmstub [-options] <assemblyNameOrPath>");
            Console.Error.WriteLine();
            Console.Error.WriteLine("options:");
            Console.Error.WriteLine("    -out:<outputfile>          Specify the output filename");
            Console.Error.WriteLine("    -reference:<filespec>      Reference an assembly (short form -r:<filespec>)");
            Console.Error.WriteLine("    -japi                      Generate jar suitable for comparison with japitools");
            Console.Error.WriteLine("    -skiperror                 Continue when errors are encountered");
            Console.Error.WriteLine("    -shared                    Process all assemblies in shared group");
            Console.Error.WriteLine("    -nostdlib                  Do not reference standard libraries");
            Console.Error.WriteLine("    -lib:<dir>                 Additional directories to search for references");
            Console.Error.WriteLine("    -namespace:<ns>            Only include types from specified namespace");
            Console.Error.WriteLine("    -forwarders                Export forwarded types too");
            Console.Error.WriteLine("    -parameters                Emit Java 8 classes with parameter names");
            return(1);
        }
        if (File.Exists(assemblyNameOrPath) && nostdlib)
        {
            // Add the target assembly to the references list, to allow it to be considered as "System.Runtime".
            // This allows "ikvmstub -nostdlib \...\mscorlib.dll" to work.
            references.Add(assemblyNameOrPath);
        }
        StaticCompiler.Resolver.Warning += new AssemblyResolver.WarningEvent(Resolver_Warning);
        StaticCompiler.Resolver.Init(StaticCompiler.Universe, nostdlib, references, libpaths);
        Dictionary <string, Assembly> cache = new Dictionary <string, Assembly>();

        foreach (string reference in references)
        {
            Assembly[] dummy = null;
            if (!StaticCompiler.Resolver.ResolveReference(cache, ref dummy, reference))
            {
                Console.Error.WriteLine("Error: reference not found {0}", reference);
                return(1);
            }
        }
        Assembly assembly = null;

        try
        {
            file = new FileInfo(assemblyNameOrPath);
        }
        catch (System.Exception x)
        {
            Console.Error.WriteLine("Error: unable to load \"{0}\"\n  {1}", assemblyNameOrPath, x.Message);
            return(1);
        }
        if (file != null && file.Exists)

        {
            Console.Error.WriteLine($"Located file and loading assembly at {assemblyNameOrPath}");
            assembly = StaticCompiler.LoadFile(assemblyNameOrPath);
        }
        else
        {
            Console.Error.WriteLine($"Trying to locate and load {assemblyNameOrPath}");
            assembly = StaticCompiler.Resolver.LoadWithPartialName(assemblyNameOrPath);
        }
        int rc = 0;

        if (assembly == null)
        {
            Console.Error.WriteLine("Error: Assembly \"{0}\" not found", assemblyNameOrPath);
        }
        else
        {
            if (bootstrap)
            {
                StaticCompiler.runtimeAssembly = StaticCompiler.LoadFile(typeof(NetExp).Assembly.Location);
                ClassLoaderWrapper.SetBootstrapClassLoader(new BootstrapBootstrapClassLoader());
            }
            else
            {
                StaticCompiler.LoadFile(typeof(NetExp).Assembly.Location);
                StaticCompiler.runtimeAssembly = StaticCompiler.LoadFile(Path.Combine(typeof(NetExp).Assembly.Location, "../IKVM.Runtime.dll"));
                JVM.CoreAssembly = StaticCompiler.LoadFile(Path.Combine(typeof(NetExp).Assembly.Location, "../IKVM.OpenJDK.Core.dll"));
            }
            if (AttributeHelper.IsJavaModule(assembly.ManifestModule))
            {
                Console.Error.WriteLine("Warning: Running ikvmstub on ikvmc compiled assemblies is not supported.");
            }
            if (outputFile == null)
            {
                outputFile = assembly.GetName().Name + ".jar";
            }
            try
            {
                using (zipFile = new ZipOutputStream(new FileStream(outputFile, FileMode.Create)))
                {
                    zipFile.SetComment(GetVersionAndCopyrightInfo());
                    try
                    {
                        List <Assembly> assemblies = new List <Assembly>();
                        assemblies.Add(assembly);
                        if (autoLoadSharedClassLoaderAssemblies)
                        {
                            LoadSharedClassLoaderAssemblies(assembly, assemblies);
                        }
                        foreach (Assembly asm in assemblies)
                        {
                            if (ProcessTypes(asm.GetTypes(), continueOnError) != 0)
                            {
                                rc = 1;
                                if (!continueOnError)
                                {
                                    break;
                                }
                            }
                            if (forwarders && ProcessTypes(asm.ManifestModule.__GetExportedTypes(), continueOnError) != 0)
                            {
                                rc = 1;
                                if (!continueOnError)
                                {
                                    break;
                                }
                            }
                        }
                    }
                    catch (System.Exception x)
                    {
                        Console.Error.WriteLine(x);

                        if (!continueOnError)
                        {
                            Console.Error.WriteLine("Warning: Assembly reflection encountered an error. Resultant JAR may be incomplete.");
                        }

                        rc = 1;
                    }
                }
            }
            catch (ZipException x)
            {
                rc = 1;
                if (zipCount == 0)
                {
                    Console.Error.WriteLine("Error: Assembly contains no public IKVM.NET compatible types");
                }
                else
                {
                    Console.Error.WriteLine("Error: {0}", x.Message);
                }
            }
        }
        return(rc);
    }
Esempio n. 11
0
    static int Main(string[] args)
    {
        IKVM.Internal.Tracer.EnableTraceConsoleListener();
        IKVM.Internal.Tracer.EnableTraceForDebug();
        string        assemblyNameOrPath = null;
        bool          continueOnError    = false;
        bool          autoLoadSharedClassLoaderAssemblies = false;
        List <string> references = new List <string>();
        List <string> libpaths   = new List <string>();
        bool          nostdlib   = false;
        bool          bootstrap  = false;

        foreach (string s in args)
        {
            if (s.StartsWith("-") || assemblyNameOrPath != null)
            {
                if (s == "-serialver")
                {
                    includeSerialVersionUID = true;
                }
                else if (s == "-skiperror")
                {
                    continueOnError = true;
                }
                else if (s == "-shared")
                {
                    autoLoadSharedClassLoaderAssemblies = true;
                }
                else if (s.StartsWith("-r:") || s.StartsWith("-reference:"))
                {
                    references.Add(s.Substring(s.IndexOf(':') + 1));
                }
                else if (s == "-nostdlib")
                {
                    nostdlib = true;
                }
                else if (s.StartsWith("-lib:"))
                {
                    libpaths.Add(s.Substring(5));
                }
                else if (s == "-bootstrap")
                {
                    bootstrap = true;
                }
                else
                {
                    // unrecognized option, or multiple assemblies, print usage message and exit
                    assemblyNameOrPath = null;
                    break;
                }
            }
            else
            {
                assemblyNameOrPath = s;
            }
        }
        if (assemblyNameOrPath == null)
        {
            Console.Error.WriteLine(GetVersionAndCopyrightInfo());
            Console.Error.WriteLine();
            Console.Error.WriteLine("usage: ikvmstub [-serialver] [-skiperror] [-reference:<assembly>] [-lib:<dir>] <assemblyNameOrPath>");
            return(1);
        }
        if (File.Exists(assemblyNameOrPath) && nostdlib)
        {
            // Add the target assembly to the references list, to allow it to be considered as "mscorlib".
            // This allows "ikvmstub -nostdlib \...\mscorlib.dll" to work.
            references.Add(assemblyNameOrPath);
        }
        StaticCompiler.Resolver.Warning += new AssemblyResolver.WarningEvent(Resolver_Warning);
        StaticCompiler.Resolver.Init(StaticCompiler.Universe, nostdlib, references, libpaths);
        Dictionary <string, Assembly> cache = new Dictionary <string, Assembly>();

        foreach (string reference in references)
        {
            Assembly[] dummy = null;
            int        rc1   = StaticCompiler.Resolver.ResolveReference(cache, ref dummy, reference);
            if (rc1 != 0)
            {
                return(rc1);
            }
        }
        Assembly assembly = null;

        try
        {
            file = new FileInfo(assemblyNameOrPath);
        }
        catch (System.Exception x)
        {
            Console.Error.WriteLine("Error: unable to load \"{0}\"\n  {1}", assemblyNameOrPath, x.Message);
            return(1);
        }
        if (file != null && file.Exists)
        {
            assembly = StaticCompiler.LoadFile(assemblyNameOrPath);
        }
        else
        {
            assembly = StaticCompiler.Resolver.LoadWithPartialName(assemblyNameOrPath);
        }
        int rc = 0;

        if (assembly == null)
        {
            Console.Error.WriteLine("Error: Assembly \"{0}\" not found", assemblyNameOrPath);
        }
        else
        {
            if (bootstrap)
            {
                StaticCompiler.runtimeAssembly = StaticCompiler.LoadFile(typeof(NetExp).Assembly.Location);
                ClassLoaderWrapper.SetBootstrapClassLoader(new BootstrapBootstrapClassLoader());
            }
            else
            {
                StaticCompiler.LoadFile(typeof(NetExp).Assembly.Location);
                StaticCompiler.runtimeAssembly = StaticCompiler.LoadFile(Path.Combine(typeof(NetExp).Assembly.Location, "../IKVM.Runtime.dll"));
                JVM.CoreAssembly = StaticCompiler.LoadFile(Path.Combine(typeof(NetExp).Assembly.Location, "../IKVM.OpenJDK.Core.dll"));
            }
            if (AttributeHelper.IsJavaModule(assembly.ManifestModule))
            {
                Console.Error.WriteLine("Warning: Running ikvmstub on ikvmc compiled assemblies is not supported.");
            }
            try
            {
                using (zipFile = new ZipOutputStream(new FileStream(assembly.GetName().Name + ".jar", FileMode.Create)))
                {
                    zipFile.SetComment(GetVersionAndCopyrightInfo());
                    try
                    {
                        List <Assembly> assemblies = new List <Assembly>();
                        assemblies.Add(assembly);
                        if (autoLoadSharedClassLoaderAssemblies)
                        {
                            LoadSharedClassLoaderAssemblies(assembly, assemblies);
                        }
                        foreach (Assembly asm in assemblies)
                        {
                            if (ProcessAssembly(asm, continueOnError) != 0)
                            {
                                rc = 1;
                                if (!continueOnError)
                                {
                                    break;
                                }
                            }
                        }
                    }
                    catch (TypeLoadException x)
                    {
                        Console.WriteLine(x);
                    }
                    catch (System.Exception x)
                    {
                        Console.WriteLine(x);

                        if (!continueOnError)
                        {
                            Console.Error.WriteLine("Warning: Assembly reflection encountered an error. Resultant JAR may be incomplete.");
                        }

                        rc = 1;
                    }
                }
            }
            catch (ZipException x)
            {
                rc = 1;
                if (zipCount == 0)
                {
                    Console.Error.WriteLine("Error: Assembly contains no public IKVM.NET compatible types");
                }
                else
                {
                    Console.Error.WriteLine("Error: {0}", x.Message);
                }
            }
        }
        return(rc);
    }
Esempio n. 12
0
 internal static Type LoadType(System.Type type)
 {
     return(StaticCompiler.GetRuntimeType(type.FullName));
 }
Esempio n. 13
0
    int ContinueParseCommandLine(IEnumerator <string> arglist, List <CompilerOptions> targets, CompilerOptions options)
    {
        while (arglist.MoveNext())
        {
            string s = arglist.Current;
            if (s == "{")
            {
                nonleaf = true;
                IkvmcCompiler nestedLevel = new IkvmcCompiler();
                nestedLevel.manifestMainClass   = manifestMainClass;
                nestedLevel.classes             = new Dictionary <string, byte[]>(classes);
                nestedLevel.resources           = CompilerOptions.Copy(resources);
                nestedLevel.defaultAssemblyName = defaultAssemblyName;
                nestedLevel.classesToExclude    = new List <string>(classesToExclude);
                int rc = nestedLevel.ContinueParseCommandLine(arglist, targets, options.Copy());
                if (rc != 0)
                {
                    return(rc);
                }
            }
            else if (s == "}")
            {
                break;
            }
            else if (nonleaf)
            {
                Console.Error.WriteLine("Error: you can only specify options before any child levels");
                return(1);
            }
            else if (s[0] == '-')
            {
                if (s.StartsWith("-out:"))
                {
                    options.path = s.Substring(5);
                }
                else if (s.StartsWith("-Xtrace:"))
                {
                    Tracer.SetTraceLevel(s.Substring(8));
                }
                else if (s.StartsWith("-Xmethodtrace:"))
                {
                    Tracer.HandleMethodTrace(s.Substring(14));
                }
                else if (s.StartsWith("-assembly:"))
                {
                    options.assembly = s.Substring(10);
                }
                else if (s.StartsWith("-target:"))
                {
                    switch (s)
                    {
                    case "-target:exe":
                        options.target        = PEFileKinds.ConsoleApplication;
                        options.guessFileKind = false;
                        break;

                    case "-target:winexe":
                        options.target        = PEFileKinds.WindowApplication;
                        options.guessFileKind = false;
                        break;

                    case "-target:module":
                        options.targetIsModule = true;
                        options.target         = PEFileKinds.Dll;
                        options.guessFileKind  = false;
                        break;

                    case "-target:library":
                        options.target        = PEFileKinds.Dll;
                        options.guessFileKind = false;
                        break;

                    default:
                        Console.Error.WriteLine("Warning: unrecognized option: {0}", s);
                        break;
                    }
                }
                else if (s.StartsWith("-platform:"))
                {
                    switch (s)
                    {
                    case "-platform:x86":
                        options.pekind           = PortableExecutableKinds.ILOnly | PortableExecutableKinds.Required32Bit;
                        options.imageFileMachine = ImageFileMachine.I386;
                        break;

                    case "-platform:Itanium":
                        options.pekind           = PortableExecutableKinds.ILOnly | PortableExecutableKinds.PE32Plus;
                        options.imageFileMachine = ImageFileMachine.IA64;
                        break;

                    case "-platform:x64":
                        options.pekind           = PortableExecutableKinds.ILOnly | PortableExecutableKinds.PE32Plus;
                        options.imageFileMachine = ImageFileMachine.AMD64;
                        break;

                    case "-platform:anycpu":
                        options.pekind           = PortableExecutableKinds.ILOnly;
                        options.imageFileMachine = ImageFileMachine.I386;
                        break;

                    default:
                        Console.Error.WriteLine("Warning: unrecognized option: {0}", s);
                        break;
                    }
                }
                else if (s.StartsWith("-apartment:"))
                {
                    switch (s)
                    {
                    case "-apartment:sta":
                        options.apartment = ApartmentState.STA;
                        break;

                    case "-apartment:mta":
                        options.apartment = ApartmentState.MTA;
                        break;

                    case "-apartment:none":
                        options.apartment = ApartmentState.Unknown;
                        break;

                    default:
                        Console.Error.WriteLine("Warning: unrecognized option: {0}", s);
                        break;
                    }
                }
                else if (s == "-noglobbing")
                {
                    options.noglobbing = true;
                }
                else if (s.StartsWith("-D"))
                {
                    string[] keyvalue = s.Substring(2).Split('=');
                    if (keyvalue.Length != 2)
                    {
                        keyvalue = new string[] { keyvalue[0], "" };
                    }
                    options.props[keyvalue[0]] = keyvalue[1];
                }
                else if (s == "-ea" || s == "-enableassertions")
                {
                    options.props["ikvm.assert.default"] = "true";
                }
                else if (s == "-da" || s == "-disableassertions")
                {
                    options.props["ikvm.assert.default"] = "false";
                }
                else if (s.StartsWith("-ea:") || s.StartsWith("-enableassertions:"))
                {
                    options.props["ikvm.assert.enable"] = s.Substring(s.IndexOf(':') + 1);
                }
                else if (s.StartsWith("-da:") || s.StartsWith("-disableassertions:"))
                {
                    options.props["ikvm.assert.disable"] = s.Substring(s.IndexOf(':') + 1);
                }
                else if (s == "-removeassertions")
                {
                    options.codegenoptions |= CodeGenOptions.RemoveAsserts;
                }
                else if (s.StartsWith("-main:"))
                {
                    options.mainClass = s.Substring(6);
                }
                else if (s.StartsWith("-reference:") || s.StartsWith("-r:"))
                {
                    string r = s.Substring(s.IndexOf(':') + 1);
                    if (r == "")
                    {
                        Console.Error.WriteLine("Error: missing file specification for '{0}' option", s);
                        return(1);
                    }
                    ArrayAppend(ref options.unresolvedReferences, r);
                }
                else if (s.StartsWith("-recurse:"))
                {
                    string spec   = s.Substring(9);
                    bool   exists = false;
                    // MONOBUG On Mono 1.0.2, Directory.Exists throws an exception if we pass an invalid directory name
                    try
                    {
                        exists = Directory.Exists(spec);
                    }
                    catch (IOException)
                    {
                    }
                    if (exists)
                    {
                        DirectoryInfo dir = new DirectoryInfo(spec);
                        Recurse(dir, dir, "*");
                    }
                    else
                    {
                        try
                        {
                            DirectoryInfo dir = new DirectoryInfo(Path.GetDirectoryName(spec));
                            if (dir.Exists)
                            {
                                Recurse(dir, dir, Path.GetFileName(spec));
                            }
                            else
                            {
                                RecurseJar(spec);
                            }
                        }
                        catch (PathTooLongException)
                        {
                            Console.Error.WriteLine("Error: path too long: {0}", spec);
                            return(1);
                        }
                        catch (DirectoryNotFoundException)
                        {
                            Console.Error.WriteLine("Error: path not found: {0}", spec);
                            return(1);
                        }
                        catch (ArgumentException)
                        {
                            Console.Error.WriteLine("Error: invalid path: {0}", spec);
                            return(1);
                        }
                    }
                }
                else if (s.StartsWith("-resource:"))
                {
                    string[] spec = s.Substring(10).Split('=');
                    try
                    {
                        using (FileStream fs = new FileStream(spec[1], FileMode.Open, FileAccess.Read))
                        {
                            byte[] b = new byte[fs.Length];
                            fs.Read(b, 0, b.Length);
                            string name = spec[0];
                            if (name.StartsWith("/"))
                            {
                                // a leading slash is not required, so strip it
                                name = name.Substring(1);
                            }
                            AddResource(null, name, b, null);
                        }
                    }
                    catch (Exception x)
                    {
                        Console.Error.WriteLine("Error: {0}: {1}", x.Message, spec[1]);
                        return(1);
                    }
                }
                else if (s.StartsWith("-externalresource:"))
                {
                    string[] spec = s.Substring(18).Split('=');
                    if (!File.Exists(spec[1]))
                    {
                        Console.Error.WriteLine("Error: external resource file does not exist: {0}", spec[1]);
                        return(1);
                    }
                    if (Path.GetFileName(spec[1]) != spec[1])
                    {
                        Console.Error.WriteLine("Error: external resource file may not include path specification: {0}", spec[1]);
                        return(1);
                    }
                    if (options.externalResources == null)
                    {
                        options.externalResources = new Dictionary <string, string>();
                    }
                    // TODO resource name clashes should be tested
                    options.externalResources.Add(spec[0], spec[1]);
                }
                else if (s == "-nojni")
                {
                    options.codegenoptions |= CodeGenOptions.NoJNI;
                }
                else if (s.StartsWith("-exclude:"))
                {
                    ProcessExclusionFile(classesToExclude, s.Substring(9));
                }
                else if (s.StartsWith("-version:"))
                {
                    string str = s.Substring(9);
                    if (!TryParseVersion(s.Substring(9), out options.version))
                    {
                        Console.Error.WriteLine("Error: Invalid version specified: {0}", str);
                        return(1);
                    }
                }
                else if (s.StartsWith("-fileversion:"))
                {
                    options.fileversion = s.Substring(13);
                }
                else if (s.StartsWith("-win32icon:"))
                {
                    options.iconfile = s.Substring(11);
                }
                else if (s.StartsWith("-keyfile:"))
                {
                    options.keyfile = s.Substring(9);
                }
                else if (s.StartsWith("-key:"))
                {
                    options.keycontainer = s.Substring(5);
                }
                else if (s == "-delaysign")
                {
                    options.delaysign = true;
                }
                else if (s == "-debug")
                {
                    options.codegenoptions |= CodeGenOptions.Debug;
                }
                else if (s.StartsWith("-srcpath:"))
                {
                    options.sourcepath = s.Substring(9);
                }
                else if (s.StartsWith("-remap:"))
                {
                    options.remapfile = s.Substring(7);
                }
                else if (s == "-nostacktraceinfo")
                {
                    options.codegenoptions |= CodeGenOptions.NoStackTraceInfo;
                }
                else if (s == "-opt:fields")
                {
                    options.removeUnusedFields = true;
                }
                else if (s == "-compressresources")
                {
                    options.compressedResources = true;
                }
                else if (s == "-strictfinalfieldsemantics")
                {
                    options.codegenoptions |= CodeGenOptions.StrictFinalFieldSemantics;
                }
                else if (s.StartsWith("-privatepackage:"))
                {
                    string prefix = s.Substring(16);
                    ArrayAppend(ref options.privatePackages, prefix);
                }
                else if (s.StartsWith("-publicpackage:"))
                {
                    string prefix = s.Substring(15);
                    ArrayAppend(ref options.publicPackages, prefix);
                }
                else if (s.StartsWith("-nowarn:"))
                {
                    foreach (string w in s.Substring(8).Split(','))
                    {
                        string ws = w;
                        // lame way to chop off the leading zeroes
                        while (ws.StartsWith("0"))
                        {
                            ws = ws.Substring(1);
                        }
                        options.suppressWarnings[ws] = ws;
                    }
                }
                else if (s.StartsWith("-warnaserror:"))
                {
                    foreach (string w in s.Substring(13).Split(','))
                    {
                        string ws = w;
                        // lame way to chop off the leading zeroes
                        while (ws.StartsWith("0"))
                        {
                            ws = ws.Substring(1);
                        }
                        options.errorWarnings[ws] = ws;
                    }
                }
                else if (s.StartsWith("-runtime:"))
                {
                    // NOTE this is an undocumented option
                    runtimeAssembly = s.Substring(9);
                }
                else if (s == "-time")
                {
                    time = true;
                }
                else if (s.StartsWith("-classloader:"))
                {
                    options.classLoader = s.Substring(13);
                }
                else if (s == "-sharedclassloader")
                {
                    if (options.sharedclassloader == null)
                    {
                        options.sharedclassloader = new List <CompilerClassLoader>();
                    }
                }
                else if (s.StartsWith("-baseaddress:"))
                {
                    string baseAddress = s.Substring(13);
                    ulong  baseAddressParsed;
                    if (baseAddress.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
                    {
                        baseAddressParsed = UInt64.Parse(baseAddress.Substring(2), System.Globalization.NumberStyles.AllowHexSpecifier);
                    }
                    else
                    {
                        // note that unlike CSC we don't support octal
                        baseAddressParsed = UInt64.Parse(baseAddress);
                    }
                    options.baseAddress = (long)(baseAddressParsed & 0xFFFFFFFFFFFF0000UL);
                }
                else if (s == "-nopeercrossreference")
                {
                    options.crossReferenceAllPeers = false;
                }
                else if (s == "-nostdlib")
                {
                    // this is a global option
                    nostdlib = true;
                }
                else if (s.StartsWith("-lib:"))
                {
                    // this is a global option
                    libpaths.Add(s.Substring(5));
                }
                else if (s == "-noautoserialization")
                {
                    options.codegenoptions |= CodeGenOptions.NoAutomagicSerialization;
                }
                else if (s.StartsWith("-writeSuppressWarningsFile:"))
                {
                    options.writeSuppressWarningsFile = s.Substring(27);
                    try
                    {
                        File.Delete(options.writeSuppressWarningsFile);
                    }
                    catch (Exception x)
                    {
                        Console.Error.WriteLine("Error: invalid option: {0}{1}\t({2})", s, Environment.NewLine, x.Message);
                        return(1);
                    }
                }
                else
                {
                    Console.Error.WriteLine("Error: unrecognized option: {0}", s);
                    return(1);
                }
            }
            else
            {
                if (defaultAssemblyName == null)
                {
                    try
                    {
                        defaultAssemblyName = new FileInfo(Path.GetFileName(s)).Name;
                    }
                    catch (ArgumentException)
                    {
                        // if the filename contains a wildcard (or any other invalid character), we ignore
                        // it as a potential default assembly name
                    }
                }
                string[] files;
                try
                {
                    string path = Path.GetDirectoryName(s);
                    files = Directory.GetFiles(path == "" ? "." : path, Path.GetFileName(s));
                }
                catch (Exception)
                {
                    Console.Error.WriteLine("Error: invalid filename: {0}", s);
                    return(1);
                }
                if (files.Length == 0)
                {
                    Console.Error.WriteLine("Error: file not found: {0}", s);
                    return(1);
                }
                foreach (string f in files)
                {
                    ProcessFile(null, f);
                }
            }
            if (options.targetIsModule && options.sharedclassloader != null)
            {
                Console.Error.WriteLine("Error: -target:module and -sharedclassloader options cannot be combined.");
                return(1);
            }
        }
        if (nonleaf)
        {
            return(0);
        }
        if (options.assembly == null)
        {
            string basename = options.path == null ? defaultAssemblyName : new FileInfo(options.path).Name;
            if (basename == null)
            {
                Console.Error.WriteLine("Error: no output file specified");
                return(1);
            }
            int idx = basename.LastIndexOf('.');
            if (idx > 0)
            {
                options.assembly = basename.Substring(0, idx);
            }
            else
            {
                options.assembly = basename;
            }
        }
        if (options.path != null && options.guessFileKind)
        {
            if (options.path.ToLower().EndsWith(".dll"))
            {
                options.target = PEFileKinds.Dll;
            }
            options.guessFileKind = false;
        }
        if (options.mainClass == null && manifestMainClass != null && (options.guessFileKind || options.target != PEFileKinds.Dll))
        {
            StaticCompiler.IssueMessage(options, Message.MainMethodFromManifest, manifestMainClass);
            options.mainClass = manifestMainClass;
        }
        options.classes          = classes;
        options.resources        = resources;
        options.classesToExclude = classesToExclude.ToArray();
        targets.Add(options);
        return(0);
    }
Esempio n. 14
0
 internal override void Generate(CodeGenContext context, CodeEmitter ilgen)
 {
     ilgen.Emit(OpCodes.Ldtoken, StaticCompiler.GetType(context.ClassLoader, type));
 }