/// <summary>
        /// Initializes the runtime compiler and metadata references for dynamic assembly.
        /// </summary>
        public RunTimeCreator()
        {
            usedNameDict = new Dictionary<string, int>();
            // Set references to runtime compiling
            isCompiled = new List<string>();
            var t = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
            metadataRef = new List<MetadataReference>();
            metadataRef.Add(MetadataFileReference.CreateAssemblyReference("mscorlib"));
            metadataRef.Add(new MetadataFileReference(typeof(Strategy.MyMogre).Assembly.Location));
            metadataRef.Add(new MetadataFileReference(typeof(Strategy.Game).Assembly.Location));
            metadataRef.Add(new MetadataFileReference(typeof(GameObjectControl.Game_Objects.StaticGameObjectBox.StaticGameObject).Assembly.Location));
            metadataRef.Add(new MetadataFileReference(typeof(Team).Assembly.Location));
            metadataRef.Add(new MetadataFileReference(typeof(System.Linq.Enumerable).Assembly.Location));
            metadataRef.Add(new MetadataFileReference(typeof(LinkedList<>).Assembly.Location));
            metadataRef.Add(new MetadataFileReference(Path.GetFullPath((new Uri(t + "\\\\Mogre.dll")).LocalPath)));
            metadataRef.Add(new MetadataFileReference(typeof(PropertyManager).Assembly.Location));
            metadataRef.Add(new MetadataFileReference(typeof(GameObjectControl.Game_Objects.StaticGameObjectBox.IStaticGameObject).Assembly.Location));
            metadataRef.Add(new MetadataFileReference(typeof(ActionAnswer).Assembly.Location));
            metadataRef.Add(new MetadataFileReference(typeof(PropertyEnum).Assembly.Location));
            metadataRef.Add(new MetadataFileReference(typeof(XmlLoadException).Assembly.Location));
            metadataRef.Add(new MetadataFileReference(typeof(ConstructorFieldAttribute).Assembly.Location));

            comilationOption = new CompilationOptions(OutputKind.DynamicallyLinkedLibrary);

            assemblyBuilder =
                AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName("DynamicAssembly" + Guid.NewGuid()),
                                                              AssemblyBuilderAccess.RunAndCollect);
            moduleBuilder = assemblyBuilder.DefineDynamicModule("DynamicModule");
        }
Example #2
0
        public Type Compile(string filename, Type type)
        {
            var className = type.Name;
            var newClassName = String.Format("{0}_{1}", className, DateTime.Now.Ticks);
            var code = ReadCodeFile(filename);

            var syntaxTree = SyntaxTree.ParseCompilationUnit(code);

            RenameClass(syntaxTree, className, newClassName);

            var references = GetAssemblyReferencesForType(type);

            var compilationOptions = new CompilationOptions(assemblyKind: AssemblyKind.DynamicallyLinkedLibrary);

            var compilation = Compilation.Create("AssemblyForRecompiledType", compilationOptions, new[] { syntaxTree }, references);

            using (var stream = new MemoryStream())
            {
                var emitResult = compilation.Emit(stream);

                if (!emitResult.Success)
                {
                    TraceCompilaitionDiagnostics(emitResult);
                    return type;
                }

                return Assembly.Load(stream.GetBuffer()).GetTypes().First(t => t.Name.StartsWith(className));
            }
        }
Example #3
0
        public ScriptManager(ICompletionService completionService, IScriptWorkspace scriptWorkspace)
        {
            _completionService = completionService;
            _scriptWorkspace = scriptWorkspace;

            _compilationOptions = new CompilationOptions(OutputKind.DynamicallyLinkedLibrary);
            _parseOptions = new ParseOptions(CompatibilityMode.None, LanguageVersion.CSharp6, true, SourceCodeKind.Script);

            var metadataFileProvider = _scriptWorkspace.CurrentSolution.MetadataFileProvider;
            _references = AssemblyTypes.Select(type => GetReference(metadataFileProvider, type));
        }
Example #4
0
        static void Main(string[] args)
        {
            var syntaxTree = SyntaxTree.ParseText("namespace DemoNamespace { public class Printer { public void Print() { System.Console.WriteLine(\"Hello World\"); System.Console.ReadLine(); }  } }");

            var references = new List<MetadataReference>()
                             	{
                             		MetadataReference.CreateAssemblyReference((typeof(Console).Assembly.Location))
                             	};

            var compilationOptions = new CompilationOptions(OutputKind.DynamicallyLinkedLibrary);

            var compilation = Compilation.Create("MyDemo", compilationOptions, new[] { syntaxTree }, references);

            // Generate the assembly into a memory stream
            var memStream = new MemoryStream();
            compilation.Emit(memStream);

            var assembly = Assembly.Load(memStream.GetBuffer());
            dynamic instance = Activator.CreateInstance(assembly.GetTypes().First());
            instance.Print();
        }
Example #5
0
        private static Assembly CompileCodeIntoAssemblyUsingRoslyn(string code, string assemblyName)
        {
            var syntaxTree = SyntaxTree.ParseCompilationUnit(code);

            var mscorlib = new AssemblyFileReference(typeof(object).Assembly.Location);

            var compilationOptions = new CompilationOptions(assemblyKind: AssemblyKind.DynamicallyLinkedLibrary);

            var compilation = Compilation.Create(assemblyName, compilationOptions, new[] { syntaxTree }, new[] { mscorlib });

            var memStream = new MemoryStream();
            var emitResult = compilation.Emit(memStream);

            if (!emitResult.Success) {
                foreach (Diagnostic diagnostic in emitResult.Diagnostics) {
                    Console.WriteLine(diagnostic.Info.ToString());
                }
            }

            return Assembly.Load(memStream.GetBuffer());
        }
Example #6
0
        private static Compilation CreateTestCompilation()
        {
            SyntaxTree programTree = SyntaxTree.ParseFile(@"..\..\Program.cs");
            SyntaxTree rewriterTree = SyntaxTree.ParseFile(@"..\..\TypeInferenceRewriter.cs");

            List<SyntaxTree> sourceTrees = new List<SyntaxTree>();
            sourceTrees.Add(programTree);
            sourceTrees.Add(rewriterTree);

            MetadataReference mscorlib = MetadataReference.CreateAssemblyReference("mscorlib");
            MetadataReference roslynCompilers = MetadataReference.CreateAssemblyReference("Roslyn.Compilers");
            MetadataReference csCompiler = MetadataReference.CreateAssemblyReference("Roslyn.Compilers.CSharp");

            List<MetadataReference> references = new List<MetadataReference>();
            references.Add(mscorlib);
            references.Add(roslynCompilers);
            references.Add(csCompiler);

            CompilationOptions compilationOptions = new CompilationOptions(OutputKind.ConsoleApplication);

            return Compilation.Create("TransformationCS", compilationOptions, sourceTrees, references);
        }
Example #7
0
        public object Execute(string command, string classes)
        {
            if (!Validator.Validate(command) || !Validator.Validate(classes))
            {
                return "Not supported";
            }

            var sandbox = SecureAppDomainFactory.Create();

            // Load basic .NET assemblies into our sandbox
            var mscorlib = sandbox.Load("mscorlib,Version=4.0.0.0,Culture=neutral,PublicKeyToken=b77a5c561934e089");
            var system = sandbox.Load("System,Version=4.0.0.0,Culture=neutral,PublicKeyToken=b77a5c561934e089");
            var core = sandbox.Load("System.Core,Version=4.0.0.0,Culture=neutral,PublicKeyToken=b77a5c561934e089");

            var script = "public static object Eval() {" + command + "}";

            var options = new CompilationOptions(assemblyKind: AssemblyKind.ConsoleApplication, usings: ReadOnlyArray<string>.CreateFrom(Namespaces));

            var compilation = Compilation.Create(Guid.NewGuid().ToString("N"), options,
                new[]
                {
                    SyntaxTree.ParseCompilationUnit(EntryPoint),
                    // This is the syntax tree represented in the `Script` variable.
                    SyntaxTree.ParseCompilationUnit(script, options: new ParseOptions(kind: SourceCodeKind.Interactive)),
                    SyntaxTree.ParseCompilationUnit(classes ?? string.Empty, options: new ParseOptions(kind: SourceCodeKind.Script))
                },
                new MetadataReference[] {
                    new AssemblyFileReference(core.Location),
                    new AssemblyFileReference(system.Location),
                    new AssemblyFileReference(mscorlib.Location)
                });

            byte[] compiledAssembly;
            using (var output = new MemoryStream())
            {
                var emitResult = compilation.Emit(output);

                if (!emitResult.Success)
                {
                    var errors = emitResult.Diagnostics.Select(x => x.Info.GetMessage().Replace("Eval()", "<Factory>()")).ToArray();
                    return string.Join(", ", errors);
                }

                compiledAssembly = output.ToArray();
            }

            if (compiledAssembly.Length == 0)
            {
                // Not sure how this would happen?
                return "Incorrect data";
            }

            var loader = (ByteCodeLoader)Activator.CreateInstance(sandbox, typeof(ByteCodeLoader).Assembly.FullName, typeof(ByteCodeLoader).FullName).Unwrap();

            bool unloaded = false;
            object result = null;
            var timeout = TimeSpan.FromSeconds(5);
            try
            {
                var task = Task.Factory
                               .StartNew(() =>
                                         {
                                             try
                                             {
                                                 result = loader.Run("EntryPoint", "Result", compiledAssembly);
                                             }
                                             catch (Exception ex) {
                                                 result = ex.Message;
                                             }
                                         });

                if (!task.Wait(timeout))
                {
                    AppDomain.Unload(sandbox);
                    unloaded = true;
                    result = "[Execution timed out after 5 seconds]";
                }
            }
            catch (Exception ex)
            {
                result = ex.Message;
            }

            if (!unloaded)
            {
                AppDomain.Unload(sandbox);
            }

            if (result == null || string.IsNullOrEmpty(result.ToString()))
            {
                result = "null";
            }

            return result;
        }
        public Compilation RoslynCompile(string compilationName, params SyntaxTree[] syntaxTrees)
        {
            if (string.IsNullOrEmpty(compilationName))
            {
                throw new ArgumentNullException("compilationName");
            }

            var options =
                new CompilationOptions(OutputKind.DynamicallyLinkedLibrary)
                    .WithOverflowChecks(true)
                    .WithOptimizations(true)
                    .WithUsings(DefaultNamespaces);

            var metadata = new[]
                           {
                               MetadataReference.Create("mscorlib"),
                               MetadataReference.Create("System"),
                               MetadataReference.Create("System.Core")
                           };

            var compilation = Compilation.Create(compilationName, options, syntaxTrees,  metadata);

            return compilation;
        }
		public virtual ScriptResult Execute(string code, string[] scriptArgs, IEnumerable<string> references, IEnumerable<string> namespaces, ScriptPackSession scriptPackSession)
		{
			Guard.AgainstNullArgument("scriptPackSession", scriptPackSession);

			_logger.Info("Starting to create execution components");
			_logger.Debug("Creating script host");

			var session = GetSession(references, namespaces, scriptPackSession);

			_logger.Info("Starting execution");

			var fileName = new FileInfo(FileName).Name + ".dll";
			var codeDir = Path.Combine(_fileSystem.CurrentDirectory, "code");
			var dllPath = Path.Combine(codeDir, fileName);
			var dllExists = _fileSystem.FileExists(dllPath);

			if (!_fileSystem.DirectoryExists(codeDir))
				_fileSystem.CreateDirectory(codeDir);

			var scriptResult = new ScriptResult();

			if (!dllExists) {
				_logger.Debug("Compiling submission");

				var referencesForCompilation = session.References.Union(new[] { "mscorlib", "System", "System.Core", "Microsoft.CSharp" }).Distinct().Select(MetadataReference.CreateAssemblyReference).ToList();
				var namespacesForCompilation = ReadOnlyArray<string>.CreateFrom(session.Namespaces);
				var parseOptions = new ParseOptions(CompatibilityMode.None, LanguageVersion.CSharp6, true, SourceCodeKind.Script);

				var syntaxTree = SyntaxTree.ParseText(code, options: parseOptions);

				var options = new CompilationOptions(OutputKind.DynamicallyLinkedLibrary)
					.WithUsings(namespacesForCompilation.ToList());

				var compilation = Compilation.Create(AssemblyNamePrefix, options, new[] { syntaxTree }, referencesForCompilation);

				using (var exeStream = new MemoryStream()) {
					var result = compilation.Emit(exeStream);

					if (result.Success) {
						_logger.Debug("Compilation was successful.");
						var exeBytes = exeStream.ToArray();

						_fileSystem.WriteAllBytes(dllPath, exeBytes);
						dllExists = true;
					} else {
						var errors = String.Join(Environment.NewLine, result.Diagnostics.Select(x => x.ToString()));
						_logger.ErrorFormat("Error occurred when compiling: {0})", errors);

						scriptResult.CompileException = new CompilationException(result.Diagnostics);
					}
				}
			}

			if (dllExists) {
				_logger.Debug("Creating Executify Sandbox AppDomain");

				var evidence = new Evidence();
				evidence.AddHostEvidence(new Zone(SecurityZone.Untrusted));

				var permissions = SecurityManager.GetStandardSandbox(evidence);
				permissions.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));
				permissions.AddPermission(new WebPermission(PermissionState.Unrestricted));
				permissions.AddPermission(new DnsPermission(PermissionState.Unrestricted));
				permissions.AddPermission(new NetworkInformationPermission(NetworkInformationAccess.Ping));

				var setup = AppDomain.CurrentDomain.SetupInformation;
				var domain = AppDomain.CreateDomain("ExecutifySandbox", evidence, setup, permissions, null);

				_logger.Debug("Retrieving compiled script method (reflection).");

				try {
					_logger.Debug("Invoking method.");
					Activator.CreateInstanceFrom(domain, dllPath, "Script");

					scriptResult.ReturnValue = null;
				} catch (Exception exc) {
					_logger.Error("An error occurred when executing the scripts.");
					_logger.ErrorFormat("Exception Message: {0} {1}Stack Trace:{2}",
						exc.InnerException.Message,
						Environment.NewLine,
						exc.InnerException.StackTrace);

					scriptResult.ExecuteException = exc;
				}
			}

			return scriptResult;
		}
Example #10
0
        private static Assembly CompileCodeIntoAssembly(string code, string virtualPath)
        {
            // Parse the source file using Roslyn
            SyntaxTree syntaxTree = SyntaxTree.ParseText(code);

            // Add all the references we need for the compilation
            var references = new List<MetadataReference>();
            foreach (Assembly referencedAssembly in BuildManager.GetReferencedAssemblies())
            {
                references.Add(new MetadataFileReference(referencedAssembly.Location));
            }

            var compilationOptions = new CompilationOptions(outputKind: OutputKind.DynamicallyLinkedLibrary);

            // Note: using a fixed assembly name, which doesn't matter as long as we don't expect cross references of generated assemblies
            var compilation = Compilation.Create("SomeAssemblyName", compilationOptions, new[] { syntaxTree }, references);

            // Generate the assembly into a memory stream
            var memStream = new MemoryStream();
            EmitResult emitResult = compilation.Emit(memStream);

            if (!emitResult.Success)
            {
                Diagnostic diagnostic = emitResult.Diagnostics.First();
                string message = diagnostic.Info.ToString();
                LinePosition linePosition = diagnostic.Location.GetLineSpan(usePreprocessorDirectives: true).StartLinePosition;

                throw new HttpParseException(message, null, virtualPath, null, linePosition.Line + 1);
            }

            return Assembly.Load(memStream.GetBuffer());
        }
        public Compilation Compile(string compilationName, params SyntaxTree[] syntaxTrees)
        {
            if (string.IsNullOrEmpty(compilationName))
            {
                throw new ArgumentNullException("compilationName");
            }

            var options = new CompilationOptions(assemblyKind: AssemblyKind.ConsoleApplication,
                                                 usings: DefaultNamespaces);

            // Load basic .NET assemblies into our sandbox
            var mscorlib = Assembly.Load("mscorlib,Version=4.0.0.0,Culture=neutral,PublicKeyToken=b77a5c561934e089");
            var system = Assembly.Load("System,Version=4.0.0.0,Culture=neutral,PublicKeyToken=b77a5c561934e089");
            var core = Assembly.Load("System.Core,Version=4.0.0.0,Culture=neutral,PublicKeyToken=b77a5c561934e089");

            var compilation = Compilation.Create(compilationName, options, syntaxTrees,
                                                 new MetadataReference[] {
                                                     new AssemblyFileReference(core.Location),
                                                     new AssemblyFileReference(system.Location),
                                                     new AssemblyFileReference(mscorlib.Location)
                                                 });

            return compilation;
        }