public void Test() { var primaryAssembly = AssemblyCompiler.Compile(primaryAssemblyCode); var assemblyName = primaryAssembly.GetName().Name; CopyAssemblyToTestDirectory(primaryAssembly); CopyAssemblyToTestDirectory(typeof(IContainer).Assembly); CopyAssemblyToTestDirectory(Assembly.GetExecutingAssembly()); CopyAssemblyToTestDirectory(typeof(Assert).Assembly); GetInvoker().DoCallBack(assemblyName, delegate(string s) { var f = new ContainerFactory() .WithAssembliesFilter(x => x.Name.StartsWith("tmp_")) .WithTypesFromDefaultBinDirectory(false); var type = Type.GetType("A1.ISomeInterface, " + s); Assert.That(type, Is.Not.Null); using (var c = f.Build()) { var exception = Assert.Throws <SimpleContainerException>(() => c.Get(type)); var assemblies = new[] { "SimpleContainer", s }.OrderBy(x => x).Select(x => "\t" + x).JoinStrings("\r\n"); const string expectedMessage = "no instances for [ISomeInterface]\r\n\r\n!" + "ISomeInterface - has no implementations\r\n" + "scanned assemblies\r\n"; Assert.That(exception.Message, Is.EqualTo(expectedMessage + assemblies)); } }); }
public void ApplicationAssemblyInclusion_DependsOnAttribute() { string compiledAssemblyPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "NonApplicationMarkedAssembly.dll"); try { AppDomainRunner.Run( delegate(object[] args) { var path = (string)args[0]; ApplicationAssemblyLoaderFilter filter = ApplicationAssemblyLoaderFilter.Instance; Assert.That(filter.ShouldIncludeAssembly(typeof(AttributeAssemblyLoaderFilterTest).Assembly), Is.True); Assert.That(filter.ShouldIncludeAssembly(typeof(TestFixtureAttribute).Assembly), Is.True); Assert.That(filter.ShouldIncludeAssembly(typeof(ApplicationAssemblyLoaderFilter).Assembly), Is.True); Assert.That(filter.ShouldIncludeAssembly(typeof(object).Assembly), Is.True); Assert.That(filter.ShouldIncludeAssembly(typeof(Uri).Assembly), Is.True); var assemblyCompiler = new AssemblyCompiler(@"Reflection\TypeDiscovery\TestAssemblies\NonApplicationMarkedAssembly", path, typeof(NonApplicationAssemblyAttribute).Assembly.Location); assemblyCompiler.Compile(); Assert.That(filter.ShouldIncludeAssembly(assemblyCompiler.CompiledAssembly), Is.False); }, compiledAssemblyPath); } finally { if (File.Exists(compiledAssemblyPath)) { FileUtility.DeleteAndWaitForCompletion(compiledAssemblyPath); } } }
private static void CommonCode(string input) { AssemblyCompiler compiler = new AssemblyCompiler(input, true); compiler.Compile(true); compiler.RunAssembly(); }
private Assembly Generate() { var assemblyPath = Path.GetDirectoryName(this.assembly.Location); var trees = new ConcurrentBag<SyntaxTree>(); var allowUnsafe = false; Parallel.ForEach(assembly.GetExportedTypes() .Where(_ => string.IsNullOrWhiteSpace(_.Validate(this.options.Serialization, new AssemblyNameGenerator(_))) && !typeof(Array).IsAssignableFrom(_) && !typeof(Enum).IsAssignableFrom(_) && !typeof(ValueType).IsAssignableFrom(_) && !typeof(Delegate).IsAssignableFrom(_)), _ => { var builder = new AssemblyBuilder(_, new ReadOnlyDictionary<int, ReadOnlyCollection<HandlerInformation>>( new Dictionary<int, ReadOnlyCollection<HandlerInformation>>()), new SortedSet<string>(), this.options); builder.Build(); trees.Add(builder.Tree); allowUnsafe |= builder.IsUnsafe; }); var referencedAssemblies = this.assembly.GetReferencedAssemblies().Select(_ => Assembly.Load(_)).ToList(); referencedAssemblies.Add(this.assembly); var compiler = new AssemblyCompiler(trees, this.options.Optimization, new AssemblyNameGenerator(this.assembly).AssemblyName, referencedAssemblies.AsReadOnly(), currentDirectory, allowUnsafe, this.options.AllowWarnings); compiler.Compile(); return compiler.Result; }
public static void Main(string[] args) { if (args.Length == 0) { Console.WriteLine("You should pass at least one parameter!"); return; } string sourceModelPath = args[0]; List <string> passedRefsPaths = args.Skip(1).ToList(); if (!passedRefsPaths.Any()) { passedRefsPaths = Compiler.AssemblyCompiler.DefaultRefs.ToList(); } try { FileInfo modelFile; List <FileInfo> libraries; modelFile = GetFile(sourceModelPath); libraries = new List <FileInfo>(); foreach (var passedRef in passedRefsPaths) { libraries.Add(GetFile(passedRef)); } AssemblyCompiler compiler = new AssemblyCompiler(modelFile, libraries); compiler.Compile(false); } catch (ArgumentException e) { Console.WriteLine(e.Message); } }
private static void CommonCode(string input) { AssemblyCompiler compiler = new AssemblyCompiler(input, true); compiler.Compile(true); Console.WriteLine(GenerationUtils.PrintCodeObject(compiler.CompileUnit)); }
public static void Run(string input) { AssemblyCompiler compiler = new AssemblyCompiler(input, true); //Set this to false to generate exe in default folder compiler.Compile(true); compiler.RunAssembly(); }
private static void CommonCode(string input) { input = Defaults.DefUsing + input; AssemblyCompiler compiler = new AssemblyCompiler(input, true); compiler.Compile(true); compiler.RunAssembly(); }
/// <summary> /// Runs the given source text /// </summary> /// <param name="source">The source to execute</param> /// <param name="memorySize">The size the memory should have</param> /// <returns>The return value of the program</returns> public static BigInteger Run(string source, int memorySize = 43) { var instructions = AssemblyCompiler.Compile(source); var emulator = new Emulator(memorySize); emulator.Execute(instructions); return(emulator.GetReturnValue()); }
private Assembly CompileTestAssemblyInMemory(string assemblyName, params string[] referencedAssemblies) { AssemblyCompiler assemblyCompiler = AssemblyCompiler.CreateInMemoryAssemblyCompiler( c_testAssemblySourceDirectoryRoot + "\\" + assemblyName, ArrayUtility.Combine(new[] { typeof(MarkerAttribute).Module.Name }, referencedAssemblies)); assemblyCompiler.Compile(); return(assemblyCompiler.CompiledAssembly); }
private static void CommonCode(string input) { input = Defaults.DefUsing + input; AssemblyCompiler compiler = new AssemblyCompiler(input, true); compiler.Compile(true); Assert.Pass(GenerationUtils.PrintCodeObject(compiler.CompileUnit)); }
public void Test() { var referencedAssembly = AssemblyCompiler.Compile(referencedCode); var assembly = AssemblyCompiler.Compile(code, referencedAssembly); var factory = new ContainerFactory().WithTypesFromAssemblies(new[] { assembly }); using (var container = factory.Build()) { var interfaceType = referencedAssembly.GetType("A1.ISomeInterface"); Assert.That(container.Get(interfaceType).GetType().Name, Is.EqualTo("SomeInterfaceImpl")); } }
public void Test() { var assembly = AssemblyCompiler.Compile(testCode); File.WriteAllText(configFileName, "A.parameter->11"); var factory = new ContainerFactory() .WithAssembliesFilter(x => x.Name.StartsWith("tmp_")) .WithConfigFile(configFileName) .WithTypesFromAssemblies(new[] { assembly }); var e = Assert.Throws <SimpleContainerException>(() => factory.Build()); Assert.That(e.Message, Is.EqualTo("for name [A] more than one type found [A1.A], [A2.A]")); }
private string Compile(string sourceDirectory, string outputAssemblyName, bool generateExecutable, string compilerOptions) { var compiler = new AssemblyCompiler( sourceDirectory, outputAssemblyName, typeof(FilteringAssemblyLoader).Assembly.Location, typeof(Remotion.Logging.LogManager).Assembly.Location); compiler.CompilerParameters.GenerateExecutable = generateExecutable; compiler.CompilerParameters.CompilerOptions = compilerOptions; compiler.Compile(); return(compiler.OutputAssemblyPath); }
/// <summary> /// Compile an assembly into a dex file. /// </summary> private static void CompileAssembly(CommandLineOptions options, NameConverter nsConverter) { // Load resource type usage info file var usedTypeNames = LoadResourceTypeUsageInformation(options); // Load assemblies var assemblies = new List <AssemblyDefinition>(); var module = new XModule(); var classLoader = new AssemblyClassLoader(module.OnClassLoaded); var resolver = new AssemblyResolver(options.ReferenceFolders, classLoader, module.OnAssemblyLoaded); var readerParameters = new ReaderParameters(ReadingMode.Immediate) { AssemblyResolver = resolver, SymbolReaderProvider = new SafeSymbolReaderProvider(), ReadSymbols = true }; foreach (var asmPath in options.Assemblies) { var asm = resolver.Load(asmPath, readerParameters); module.OnAssemblyLoaded(asm); classLoader.LoadAssembly(asm); assemblies.Add(asm); } // Load references var references = new List <AssemblyDefinition>(); foreach (var refPath in options.References) { var asm = resolver.Load(refPath, readerParameters); module.OnAssemblyLoaded(asm); classLoader.LoadAssembly(asm); references.Add(asm); } // Load resources Table table; using (var stream = new FileStream(options.InputResources, FileMode.Open, FileAccess.Read)) { table = new Table(stream); } // Create compiler var compiler = new AssemblyCompiler(options.CompilationMode, assemblies, references, table, nsConverter, options.DebugInfo, classLoader, usedTypeNames, module); compiler.Compile(); compiler.Save(options.OutputFolder, options.FreeAppsKeyPath); }
public void Test() { var referencedAssembly = AssemblyCompiler.Compile(referencedCode); var a1 = AssemblyCompiler.Compile(code1, referencedAssembly); var a2 = AssemblyCompiler.Compile(code2, referencedAssembly); var factory = new ContainerFactory() .WithTypesFromAssemblies(new[] { a1, a2 }) .WithAssembliesFilter(x => x.Name == a2.GetName().Name); using (var container = factory.Build()) { var interfaceType = referencedAssembly.GetType("A1.ISomeInterface"); Assert.That(container.Get(interfaceType).GetType().Name, Is.EqualTo("TestClass2")); } }
static void Main(string[] args) { AssemblyCompiler asm = new AssemblyCompiler(TargetFramework.x86, 0x001C0000); byte[] code = asm.Compile( "start:", "mov eax,[eax*4+100]", "mov eax,[eax*4]", mov(eax, ~eax * 4 + 100) ); Console.WriteLine(BytesToString(code)); Console.ReadLine(); }
public void CheckILVerifier_IsFunctional() { const string dummyCode = @"using System; public class DummyClass { public int SimpleAdd() { var a = 2; var b = 3; return a + b; } }"; var validAssembly = new MemoryStream(); var dummyAssembly = AssemblyCompiler.Compile("DummyLib", dummyCode); dummyAssembly.Write(validAssembly); var typ = dummyAssembly.MainModule.GetType("DummyClass"); var testMethod = typ.Methods.FirstOrDefault(m => m.Name == "SimpleAdd"); if (testMethod != null) { var processor = testMethod.Body.GetILProcessor(); // Break IL codes by injecting a line that loads string to stack while adding 2 integers processor.Body.Instructions.Insert(2, processor.Create(OpCodes.Ldstr, "AElf")); } var invalidAssembly = new MemoryStream(); dummyAssembly.Write(invalidAssembly); // Ensure contract auditor doesn't throw any exception Should.NotThrow(() => _auditorFixture.Audit(validAssembly.ToArray())); // Ensure ILVerifier is doing its job Should.Throw <InvalidCodeException>(() => _auditorFixture.Audit(invalidAssembly.ToArray())) .Findings.FirstOrDefault(f => f is ILVerifierResult).ShouldNotBeNull(); }
public void Test() { var referencedAssemblyV2 = AssemblyCompiler.Compile(referencedAssemblyCodeV2); AssemblyCompiler.Compile(referencedAssemblyCodeV1, Path.Combine(testDirectory, Path.GetFileName(referencedAssemblyV2.Location))); var primaryAssembly = AssemblyCompiler.Compile(primaryAssemblyCode, referencedAssemblyV2); CopyAssemblyToTestDirectory(primaryAssembly); CopyAssemblyToTestDirectory(typeof(IContainer).Assembly); CopyAssemblyToTestDirectory(Assembly.GetExecutingAssembly()); var exceptionText = GetInvoker().CreateCointainerWithCrash(); Assert.That(exceptionText, Is.StringContaining("A1.ISomeInterface.Do")); const string englishText = "Unable to load one or more of the requested types"; const string russianText = "Не удается загрузить один или более запрошенных типов"; Assert.That(exceptionText, Is.StringContaining(englishText).Or.StringContaining(russianText)); Assert.That(exceptionText, Is.StringContaining(primaryAssembly.GetName().Name)); }
public void RunDefault() { _parameters.AssemblyOutputDirectory = "MixerRunnerTest"; _parameters.BaseDirectory = "MixerRunnerTest_Input"; var assemblyPath = Path.Combine(_parameters.AssemblyOutputDirectory, "Remotion.Mixins.Persistent.1.dll"); Assert.That(Directory.Exists(_parameters.AssemblyOutputDirectory), Is.False); Assert.That(File.Exists(assemblyPath), Is.False); Assert.That(Directory.Exists(_parameters.BaseDirectory), Is.False); try { Directory.CreateDirectory(_parameters.BaseDirectory); var compiler = new AssemblyCompiler( @"Core\MixerTools\SampleAssembly", Path.Combine(_parameters.BaseDirectory, "SampleAssembly.dll"), typeof(Mixin).Assembly.Location); compiler.Compile(); var runner = new MixerRunner(_parameters); runner.Run(); Assert.That(Directory.Exists(_parameters.AssemblyOutputDirectory), Is.True); Assert.That(File.Exists(assemblyPath), Is.True); } finally { if (Directory.Exists(_parameters.BaseDirectory)) { Directory.Delete(_parameters.BaseDirectory, true); } if (Directory.Exists(_parameters.AssemblyOutputDirectory)) { Directory.Delete(_parameters.AssemblyOutputDirectory, true); } } }
/// <summary> /// Compile an assembly into a dex file. /// </summary> private static void CompileAssembly(CommandLineOptions options, NameConverter nsConverter) { // Load resource type usage info file var usedTypeNames = LoadResourceTypeUsageInformation(options); // Load assemblies List <AssemblyDefinition> assemblies = new List <AssemblyDefinition>(); List <AssemblyDefinition> references = new List <AssemblyDefinition>(); var dxJarCompiler = options.EnableDxJarCompilation ? new DxClassfileMethodBodyCompiler(options.OutputFolder, options.DebugInfo) : null; Action <ClassSource> jarLoaded = dxJarCompiler != null ? dxJarCompiler.PreloadJar : (Action <ClassSource>)null; var module = new XModule(); var classLoader = new AssemblyClassLoader(module.OnClassLoaded); var resolver = new AssemblyResolver(options.ReferenceFolders, classLoader, module.OnAssemblyLoaded); // initialize compiler cache in background. var ccache = options.EnableCompilerCache ? new DexMethodBodyCompilerCache(options.OutputFolder, resolver.GetFileName) : new DexMethodBodyCompilerCache(); var readerParameters = new ReaderParameters { AssemblyResolver = resolver, SymbolReaderProvider = new SafeSymbolReaderProvider(), ReadSymbols = true, ReadingMode = ReadingMode.Immediate }; // load assemblies var toLoad = options.Assemblies.Select(path => new { path, target = assemblies }) .Concat(options.References.Select(path => new { path, target = references })) // Some micro optimizations... // Our startup is IO bound until we have loaded first assembly from disk. // So just load from smallest to largest. .Select(load => new { load.path, load.target, length = new FileInfo(resolver.ResolvePath(load.path)).Length }) .OrderBy(load => load.length) .ToList(); using (AssemblyCompiler.Profile("for loading assemblies")) { toLoad.AsParallel().ForAll( //toLoad.ForEach( load => { var assm = resolver.Load(load.path, readerParameters); lock (load.target) load.target.Add(assm); }); } // Load resources Table table; using (var stream = new FileStream(options.InputResources, FileMode.Open, FileAccess.Read)) { table = new Table(stream); } // Create compiler var compiler = new AssemblyCompiler(options.CompilationMode, assemblies, references, table, nsConverter, options.DebugInfo, classLoader, resolver.GetFileName, ccache, usedTypeNames, module, options.GenerateSetNextInstructionCode); compiler.DxClassfileMethodBodyCompiler = dxJarCompiler; using (AssemblyCompiler.Profile("total compilation time", true)) compiler.Compile(); ccache.PrintStatistics(); using (AssemblyCompiler.Profile("saving results")) compiler.Save(options.OutputFolder, options.FreeAppsKeyPath); }
public override void DecompileMethod(Mono.Cecil.MethodDefinition method, ICSharpCode.Decompiler.ITextOutput output, DecompilationOptions options) { var declaringType = method.DeclaringType; var assembly = declaringType.Module.Assembly; if ((compiler == null) || (compiler.Assembly != assembly)) { compiler = null; var c = new AssemblyCompiler(assembly, new NamespaceConverter("pkg.name", "")); c.Compile(); compiler = c; } var cmethod = compiler.GetMethod(method); if ((cmethod != null) && (cmethod.DexMethod != null)) { var body = cmethod.DexMethod.Body; body.UpdateInstructionOffsets(); var targetInstructions = body.Instructions.Select(x => x.Operand).OfType <Instruction>().ToList(); targetInstructions.AddRange(body.Exceptions.Select(x => x.TryStart)); targetInstructions.AddRange(body.Exceptions.Select(x => x.TryEnd)); targetInstructions.AddRange(body.Exceptions.SelectMany(x => x.Catches, (h, y) => y.Instruction)); targetInstructions.AddRange(body.Exceptions.Select(x => x.CatchAll)); foreach (var ins in body.Instructions) { if (targetInstructions.Contains(ins) || (ins.Offset == 0)) { output.Write(string.Format("D_{0:X4}:", ins.Offset)); output.WriteLine(); } output.Indent(); output.Write(ins.ToString()); output.WriteLine(); output.Unindent(); } if (body.Exceptions.Any()) { output.WriteLine(); output.Write("Exception handlers:"); output.WriteLine(); output.Indent(); foreach (var handler in body.Exceptions) { output.Write(string.Format("{0:x4}-{1:x4}", handler.TryStart.Offset, handler.TryEnd.Offset)); output.WriteLine(); output.Indent(); foreach (var c in handler.Catches) { output.Write(string.Format("{0} => {1:x4}", c.Type, c.Instruction.Offset)); output.WriteLine(); } if (handler.CatchAll != null) { output.Write(string.Format("{0} => {1:x4}", "<any>", handler.CatchAll.Offset)); output.WriteLine(); } output.Unindent(); } output.Unindent(); } } else { output.Write("Method not found in dex"); output.WriteLine(); } }
public override void DecompileMethod(Mono.Cecil.MethodDefinition method, ICSharpCode.Decompiler.ITextOutput output, DecompilationOptions options) { var declaringType = method.DeclaringType; var assembly = declaringType.Module.Assembly; if ((compiler == null) || (compiler.Assembly != assembly)) { compiler = null; var c = new AssemblyCompiler(assembly, new NamespaceConverter("pkg.name", "")); c.Compile(); compiler = c; } var cmethod = compiler.GetMethod(method); if ((cmethod != null) && (cmethod.RLBody != null)) { var body = cmethod.RLBody; var basicBlocks = BasicBlock.Find(body); foreach (var block in basicBlocks) { output.Write(string.Format("D_{0:X4}:", block.Entry.Index)); output.WriteLine(); output.Indent(); foreach (var ins in block.Instructions) { output.Write(ins.ToString()); output.WriteLine(); } output.Unindent(); } if (body.Exceptions.Any()) { output.WriteLine(); output.Write("Exception handlers:"); output.WriteLine(); output.Indent(); foreach (var handler in body.Exceptions) { output.Write(string.Format("{0:x4}-{1:x4}", handler.TryStart.Index, handler.TryEnd.Index)); output.WriteLine(); output.Indent(); foreach (var c in handler.Catches) { output.Write(string.Format("{0} => {1:x4}", c.Type, c.Instruction.Index)); output.WriteLine(); } if (handler.CatchAll != null) { output.Write(string.Format("{0} => {1:x4}", "<any>", handler.CatchAll.Index)); output.WriteLine(); } output.Unindent(); } output.Unindent(); } } else { output.Write("Method not found in dex"); output.WriteLine(); } }