Exemple #1
0
        static void TaskFour()
        {
            var module    = ModuleDefinition.CreateModule("taskFour", ModuleKind.Dll);
            var AbyteMult = new TypeDefinition("", "A_int_checked_умножение", TypeAttributes.Public | TypeAttributes.AnsiClass | TypeAttributes.AutoLayout | TypeAttributes.BeforeFieldInit | TypeAttributes.Sealed, module.TypeSystem.Object);

            module.Types.Add(AbyteMult);
            var gg = new MethodDefinition("gg", MethodAttributes.Static | MethodAttributes.Public | MethodAttributes.HideBySig, module.TypeSystem.Int32);

            AbyteMult.Methods.Add(gg);
            var a = new ParameterDefinition("a", ParameterAttributes.None, module.ImportReference(typeof(int)));

            gg.Parameters.Add(a);
            var b = new ParameterDefinition("b", ParameterAttributes.None, module.ImportReference(typeof(int)));

            gg.Parameters.Add(b);
            var cil = gg.Body.GetILProcessor();

            cil.Emit(OpCodes.Ldarg, a);
            cil.Emit(OpCodes.Ldarg, b);
            cil.Emit(OpCodes.Mul_Ovf);

            cil.Emit(OpCodes.Ret);

            module.Write("out4.dll");
            var myInc = (Func <int, int, int>)System.Reflection
                        .Assembly.LoadFrom("out4.dll")
                        .GetType("A_int_checked_умножение")
                        .GetMethod("gg")
                        .CreateDelegate(typeof(Func <int, int, int>));
        }
Exemple #2
0
        public void Compile(ProgramNode program)
        {
            var module = ModuleDefinition.CreateModule(
                Path.GetFileName(BinPath),
                ModuleKind.Console
                );
            var mainClass = new TypeDefinition(
                "", ClassName,
                TypeAttributes.Public | TypeAttributes.Abstract | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit,
                module.TypeSystem.Object
                );

            module.Types.Add(mainClass);
            var method = new MethodDefinition(
                MethodName,
                MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Static,
                module.TypeSystem.Void
                );

            mainClass.Methods.Add(method);
            var compiler = new Compiler(method);

            compiler.CompileProgram(program);
            module.EntryPoint = method;
            module.Write(BinPath);
        }
    public Task ValidPropsFromBase()
    {
        var moduleDefinition = ModuleDefinition.CreateModule("Foo", ModuleKind.Dll);

        var resolver    = new MockAssemblyResolver();
        var innerWeaver = BuildInnerWeaver(moduleDefinition, resolver);

        innerWeaver.SplitUpReferences();

        var weaverEntry = new WeaverEntry
        {
            Element      = "<foo/>",
            AssemblyPath = @"c:\FakePath\Assembly.dll"
        };
        var moduleWeaver = new ValidFromBaseModuleWeaver();

        innerWeaver.SetProperties(weaverEntry, moduleWeaver);
        var verifySettings = new VerifySettings();

        verifySettings.ModifySerialization(settings =>
        {
            settings.IgnoreMembersWithType <ModuleDefinition>();
            settings.IncludeObsoletes();
        });
        verifySettings.UniqueForRuntime();

        return(VerifyXunit.Verifier.Verify(moduleWeaver, verifySettings));
    }
        private ModuleDefinition _CreateDynModule(string name, Type returnType, Type[] parameterTypes)
        {
            ModuleDefinition module = _Module = ModuleDefinition.CreateModule($"DMD:DynModule<{name}>?{GetHashCode()}", new ModuleParameters()
            {
                Kind = ModuleKind.Dll,
#if !CECIL0_9
                ReflectionImporterProvider = MMReflectionImporter.ProviderNoDefault
#endif
            });

            TypeDefinition type = new TypeDefinition(
                "",
                $"DMD<{name}>?{GetHashCode()}",
                Mono.Cecil.TypeAttributes.Public | Mono.Cecil.TypeAttributes.Class
                );

            module.Types.Add(type);

            MethodDefinition def = _Definition = new MethodDefinition(
                name,
                Mono.Cecil.MethodAttributes.Public | Mono.Cecil.MethodAttributes.HideBySig | Mono.Cecil.MethodAttributes.Public | Mono.Cecil.MethodAttributes.Static,
                returnType != null ? module.ImportReference(returnType) : module.TypeSystem.Void
                );

            foreach (Type paramType in parameterTypes)
            {
                def.Parameters.Add(new ParameterDefinition(module.ImportReference(paramType)));
            }
            type.Methods.Add(def);

            return(module);
        }
Exemple #5
0
        public void CreateMethodFromScratch()
        {
            if (!Platform.HasNativePdbSupport)
            {
                Assert.Ignore();
            }

            var module = ModuleDefinition.CreateModule("Pan", ModuleKind.Dll);
            var type   = new TypeDefinition("Pin", "Pon", TypeAttributes.Public | TypeAttributes.Abstract | TypeAttributes.Sealed, module.ImportReference(typeof(object)));

            module.Types.Add(type);

            var method = new MethodDefinition("Pang", MethodAttributes.Public | MethodAttributes.Static, module.ImportReference(typeof(string)));

            type.Methods.Add(method);

            var body = method.Body;

            body.InitLocals = true;

            var il   = body.GetILProcessor();
            var temp = new VariableDefinition(module.ImportReference(typeof(string)));

            body.Variables.Add(temp);

            il.Emit(OpCodes.Nop);
            il.Emit(OpCodes.Ldstr, "hello");
            il.Emit(OpCodes.Stloc, temp);
            il.Emit(OpCodes.Ldloc, temp);
            il.Emit(OpCodes.Ret);

            var sequence_point = new SequencePoint(body.Instructions [0], new Document(@"C:\test.cs"))
            {
                StartLine   = 0,
                StartColumn = 0,
                EndLine     = 0,
                EndColumn   = 4,
            };

            method.DebugInformation.SequencePoints.Add(sequence_point);

            method.DebugInformation.Scope = new ScopeDebugInformation(body.Instructions [0], null)
            {
                Variables = { new VariableDebugInformation(temp, "temp") }
            };

            var file = Path.Combine(Path.GetTempPath(), "Pan.dll");

            module.Write(file, new WriterParameters {
                SymbolWriterProvider = new PdbWriterProvider(),
            });

            module = ModuleDefinition.ReadModule(file, new ReaderParameters {
                SymbolReaderProvider = new PdbReaderProvider(),
            });

            method = module.GetType("Pin.Pon").GetMethod("Pang");

            Assert.AreEqual("temp", method.DebugInformation.Scope.Variables [0].Name);
        }
Exemple #6
0
        public void TransformValueBoxing(TypeDefinition t)
        {
            foreach (var m in t.Methods.Where(x => x.HasBody))
            {
                for (int idx = 0; idx < m.Body.Instructions.Count; idx++)
                {
                    var i = m.Body.Instructions[idx];

                    // todo: move to own transform
                    if (i.OpCode == OpCodes.Box || i.OpCode == OpCodes.Unbox || i.OpCode == OpCodes.Unbox_Any)
                    {
                        var ilp       = m.Body.GetILProcessor();
                        var mod       = ModuleDefinition.CreateModule("a", ModuleKind.Dll);
                        var orgType   = i.Operand as TypeReference;
                        var boxType   = mod.ImportReference(typeof(ESharpCore.Core.Boxed <int>)).GetElementType();
                        var boxedType = new GenericInstanceType(boxType);
                        boxedType.GenericArguments.Add(orgType);

                        var expanded = ExpandGenericType(boxedType);

                        var boxMethod = expanded.Methods.Single(x => x.Name == i.OpCode.Name.Replace(".", "_").ToLower());

                        ilp.Replace(i, ilp.Create(OpCodes.Call, boxMethod));
                    }
                }
            }
        }
    public void ValidProps()
    {
        var moduleDefinition = ModuleDefinition.CreateModule("Foo", ModuleKind.Dll);

        var resolver    = new MockAssemblyResolver();
        var innerWeaver = new InnerWeaver
        {
            Logger                = new Mock <ILogger>().Object,
            AssemblyFilePath      = "AssemblyFilePath",
            ProjectDirectoryPath  = "ProjectDirectoryPath",
            SolutionDirectoryPath = "SolutionDirectoryPath",
            ReferenceDictionary   = new Dictionary <string, string>
            {
                { "Ref1;Ref2", "Path1" }
            },
            ReferenceCopyLocalPaths = new List <string>
            {
                "CopyRef1",
                "CopyRef2"
            },
            References       = "Ref1;Ref2",
            ModuleDefinition = moduleDefinition,
            DefineConstants  = new List <string>
            {
                "Debug",
                "Release"
            },
            assemblyResolver = resolver
        };

        var weaverEntry = new WeaverEntry
        {
            Element      = "<foo/>",
            AssemblyPath = @"c:\FakePath\Assembly.dll"
        };
        var moduleWeaver = new ValidModuleWeaver();

        innerWeaver.SetProperties(weaverEntry, moduleWeaver, typeof(ValidModuleWeaver).BuildDelegateHolder());

        Assert.IsNotNull(moduleWeaver.LogDebug);
        Assert.IsNotNull(moduleWeaver.LogInfo);
        Assert.IsNotNull(moduleWeaver.LogWarning);
        Assert.IsNotNull(moduleWeaver.LogWarningPoint);
        Assert.IsNotNull(moduleWeaver.LogError);
        Assert.IsNotNull(moduleWeaver.LogErrorPoint);
        Assert.IsNotNull(moduleWeaver.LogMessage);
        Assert.AreEqual("Ref1;Ref2", moduleWeaver.References);
        Assert.AreEqual("CopyRef1", moduleWeaver.ReferenceCopyLocalPaths[0]);
        Assert.AreEqual("CopyRef2", moduleWeaver.ReferenceCopyLocalPaths[1]);
        Assert.AreEqual("Debug", moduleWeaver.DefineConstants[0]);
        Assert.AreEqual("Release", moduleWeaver.DefineConstants[1]);

        // Assert.IsNotEmpty(moduleWeaver.References);
        Assert.AreEqual(moduleDefinition, moduleWeaver.ModuleDefinition);
        Assert.AreEqual(resolver, moduleWeaver.AssemblyResolver);
        Assert.AreEqual(@"c:\FakePath", moduleWeaver.AddinDirectoryPath);
        Assert.AreEqual("AssemblyFilePath", moduleWeaver.AssemblyFilePath);
        Assert.AreEqual("ProjectDirectoryPath", moduleWeaver.ProjectDirectoryPath);
        Assert.AreEqual("SolutionDirectoryPath", moduleWeaver.SolutionDirectoryPath);
    }
    public void ValidProps()
    {
        var moduleWeaver     = new ValidModuleWeaver();
        var moduleDefinition = ModuleDefinition.CreateModule("Foo", ModuleKind.Dll);
        var assemblyResolver = new Mock <IAssemblyResolver>().Object;
        var innerWeaver      = new InnerWeaver
        {
            AssemblyPath = "AssemblyPath"
        };

        var moduleWeaverRunner = new WeaverInitialiser
        {
            ModuleDefinition = moduleDefinition,
            Logger           = new Mock <ILogger>().Object,
            AssemblyResolver = assemblyResolver,
            InnerWeaver      = innerWeaver
        };
        var weaverEntry = new WeaverEntry {
            Element = "<foo/>"
        };

        moduleWeaverRunner.SetProperties(weaverEntry, moduleWeaver);

        Assert.IsNotNull(moduleWeaver.LogInfo);
        Assert.IsNotNull(moduleWeaver.LogWarning);
        Assert.IsNotNull(moduleWeaver.LogWarningPoint);
        Assert.IsNotNull(moduleWeaver.LogError);
        Assert.IsNotNull(moduleWeaver.LogErrorPoint);
        Assert.AreEqual(moduleDefinition, moduleWeaver.ModuleDefinition);
        Assert.AreEqual(assemblyResolver, moduleWeaver.AssemblyResolver);
        Assert.AreEqual("AssemblyPath", moduleWeaver.AssemblyPath);
    }
Exemple #9
0
        internal static IEnumerable <CSharpLanguage> GetDebugLanguages()
        {
            var    context           = new DecompilerContext(ModuleDefinition.CreateModule("dummy", ModuleKind.Dll));
            string lastTransformName = "no transforms";

            foreach (
                Type _transformType in
                TransformationPipeline.CreatePipeline(context).Select(v => v.GetType()).Distinct())
            {
                Type transformType = _transformType; // copy for lambda
                yield return(new CSharpLanguage
                {
                    transformAbortCondition = v => transformType.IsInstanceOfType(v),
                    name = "C# - " + lastTransformName,
                    showAllMembers = true
                });

                lastTransformName = "after " + transformType.Name;
            }
            yield return(new CSharpLanguage
            {
                name = "C# - " + lastTransformName,
                showAllMembers = true
            });
        }
Exemple #10
0
    static void ExportClassesToDll(List <JavaClass> classes, string outputPath)
    {
        ModuleDefinition module;

        bool exists = File.Exists(outputPath);

        if (exists)
        {
            var parameters = new ReaderParameters(ReadingMode.Deferred);
            parameters.ReadWrite = true;
            module = ModuleDefinition.ReadModule(outputPath, parameters);
        }
        else
        {
            module = ModuleDefinition.CreateModule(Path.GetFileName(outputPath), ModuleKind.Dll);
        }
        (new DotNetImporter(module)).Merge(classes);

        if (exists)
        {
            module.Write();
        }
        else
        {
            module.Write(outputPath);
        }
    }
Exemple #11
0
        static void TaskOne()
        {
            var module     = ModuleDefinition.CreateModule("taskOne", ModuleKind.Dll);
            var ASbyteComp = new TypeDefinition("", "A_sbyte_меньше_или_равно", TypeAttributes.Public | TypeAttributes.AnsiClass | TypeAttributes.AutoLayout | TypeAttributes.BeforeFieldInit | TypeAttributes.Sealed, module.TypeSystem.Object);

            module.Types.Add(ASbyteComp);
            var gg = new MethodDefinition("gg", MethodAttributes.Static | MethodAttributes.Public | MethodAttributes.HideBySig, module.TypeSystem.Boolean);

            ASbyteComp.Methods.Add(gg);
            var a = new ParameterDefinition("a", ParameterAttributes.None, module.ImportReference(typeof(sbyte)));

            gg.Parameters.Add(a);
            var b = new ParameterDefinition("b", ParameterAttributes.None, module.ImportReference(typeof(sbyte)));

            gg.Parameters.Add(b);
            var cil = gg.Body.GetILProcessor();

            cil.Emit(OpCodes.Ldarg, a);
            cil.Emit(OpCodes.Ldarg, b);
            cil.Emit(OpCodes.Cgt);
            cil.Emit(OpCodes.Ldc_I4, 0);
            cil.Emit(OpCodes.Ceq);

            cil.Emit(OpCodes.Ret);

            module.Write("out1.dll");
            var myInc = (Func <sbyte, sbyte, bool>)System.Reflection
                        .Assembly.LoadFrom("out1.dll")
                        .GetType("A_sbyte_меньше_или_равно")
                        .GetMethod("gg")
                        .CreateDelegate(typeof(Func <sbyte, sbyte, bool>));
        }
Exemple #12
0
        static void TaskFive()
        {
            var module    = ModuleDefinition.CreateModule("taskFive", ModuleKind.Dll);
            var AbyteMult = new TypeDefinition("", "A_decimal_меньше", TypeAttributes.Public | TypeAttributes.AnsiClass | TypeAttributes.AutoLayout | TypeAttributes.BeforeFieldInit | TypeAttributes.Sealed, module.TypeSystem.Object);

            module.Types.Add(AbyteMult);
            var gg = new MethodDefinition("gg", MethodAttributes.Static | MethodAttributes.Public | MethodAttributes.HideBySig, module.TypeSystem.Boolean);

            AbyteMult.Methods.Add(gg);
            var a = new ParameterDefinition("a", ParameterAttributes.None, module.ImportReference(typeof(decimal)));

            gg.Parameters.Add(a);
            var b = new ParameterDefinition("b", ParameterAttributes.None, module.ImportReference(typeof(decimal)));

            gg.Parameters.Add(b);
            var cil = gg.Body.GetILProcessor();

            cil.Emit(OpCodes.Ldarg, a);
            cil.Emit(OpCodes.Ldarg, b);
            cil.Emit(OpCodes.Call, module.ImportReference(typeof(decimal).GetMethod("op_LessThan", new Type[] { typeof(decimal), typeof(decimal) })));

            cil.Emit(OpCodes.Ret);

            module.Write("out5.dll");
            var myInc = (Func <decimal, decimal, bool>)System.Reflection
                        .Assembly.LoadFrom("out5.dll")
                        .GetType("A_decimal_меньше")
                        .GetMethod("gg")
                        .CreateDelegate(typeof(Func <decimal, decimal, bool>));
        }
Exemple #13
0
        static Type CreateSharedStateType()
        {
            using var module = ModuleDefinition.CreateModule(name, new ModuleParameters()
            {
                Kind = ModuleKind.Dll, ReflectionImporterProvider = MMReflectionImporter.Provider
            });
            var attr    = Mono.Cecil.TypeAttributes.Public | Mono.Cecil.TypeAttributes.Abstract | Mono.Cecil.TypeAttributes.Sealed | Mono.Cecil.TypeAttributes.Class;
            var typedef = new TypeDefinition("", name, attr)
            {
                BaseType = module.TypeSystem.Object
            };

            module.Types.Add(typedef);

            typedef.Fields.Add(new FieldDefinition(
                                   "state",
                                   Mono.Cecil.FieldAttributes.Public | Mono.Cecil.FieldAttributes.Static,
                                   module.ImportReference(typeof(Dictionary <MethodBase, byte[]>))
                                   ));

            typedef.Fields.Add(new FieldDefinition(
                                   "originals",
                                   Mono.Cecil.FieldAttributes.Public | Mono.Cecil.FieldAttributes.Static,
                                   module.ImportReference(typeof(Dictionary <MethodInfo, MethodBase>))
                                   ));

            typedef.Fields.Add(new FieldDefinition(
                                   "version",
                                   Mono.Cecil.FieldAttributes.Public | Mono.Cecil.FieldAttributes.Static,
                                   module.ImportReference(typeof(int))
                                   ));

            return(ReflectionHelper.Load(module).GetType(name));
        }
Exemple #14
0
        static void TaskTwo()
        {
            var module     = ModuleDefinition.CreateModule("taskTwo", ModuleKind.Dll);
            var AUshortSum = new TypeDefinition("", "A_ushort_сложение", TypeAttributes.Public | TypeAttributes.AnsiClass | TypeAttributes.AutoLayout | TypeAttributes.BeforeFieldInit | TypeAttributes.Sealed, module.TypeSystem.Object);

            module.Types.Add(AUshortSum);
            var gg = new MethodDefinition("gg", MethodAttributes.Static | MethodAttributes.Public | MethodAttributes.HideBySig, module.TypeSystem.UInt16);

            AUshortSum.Methods.Add(gg);
            var a = new ParameterDefinition("a", ParameterAttributes.None, module.ImportReference(typeof(ushort)));

            gg.Parameters.Add(a);
            var b = new ParameterDefinition("b", ParameterAttributes.None, module.ImportReference(typeof(ushort)));

            gg.Parameters.Add(b);
            var cil = gg.Body.GetILProcessor();

            cil.Emit(OpCodes.Ldarg, a);
            cil.Emit(OpCodes.Ldarg, b);
            cil.Emit(OpCodes.Add);
            cil.Emit(OpCodes.Conv_U2);

            cil.Emit(OpCodes.Ret);

            module.Write("out2.dll");
            var myInc = (Func <ushort, ushort, ushort>)System.Reflection
                        .Assembly.LoadFrom("out2.dll")
                        .GetType("A_ushort_сложение")
                        .GetMethod("gg")
                        .CreateDelegate(typeof(Func <ushort, ushort, ushort>));
        }
        public void ContractTransaction_EmptyModule_Failure()
        {
            // Ensure fixture is funded.
            this.node1.MineBlocks(1);

            double  amount = 25;
            Money   senderBalanceBefore = this.node1.WalletSpendableBalance;
            uint256 currentHash         = this.node1.GetLastBlock().GetHash();

            // Create transaction with empty module
            var module = ModuleDefinition.CreateModule("SmartContract", ModuleKind.Dll);

            byte[] emptyModule;

            using (var ms = new MemoryStream())
            {
                module.Write(ms);
                emptyModule = ms.ToArray();
            }

            Assert.Single(module.Types);
            Assert.Equal("<Module>", module.Types[0].Name);

            BuildCreateContractTransactionResponse response = this.node1.SendCreateContractTransaction(emptyModule, amount);

            this.node2.WaitMempoolCount(1);
            this.node2.MineBlocks(1);
            NBitcoin.Block lastBlock = this.node1.GetLastBlock();

            // Blocks progressed
            Assert.NotEqual(currentHash, lastBlock.GetHash());

            // Contract wasn't created
            Assert.Null(this.node2.GetCode(response.NewContractAddress));

            // Block contains a refund transaction
            Assert.Equal(3, lastBlock.Transactions.Count);
            Transaction refundTransaction = lastBlock.Transactions[2];
            uint160     refundReceiver    = this.senderRetriever.GetAddressFromScript(refundTransaction.Outputs[0].ScriptPubKey).Sender;

            Assert.Equal(this.node1.MinerAddress.Address, refundReceiver.ToBase58Address(this.mockChain.Network));
            Assert.Equal(new Money((long)amount, MoneyUnit.BTC), refundTransaction.Outputs[0].Value);
            Money fee = lastBlock.Transactions[0].Outputs[0].Value - new Money(50, MoneyUnit.BTC);

            // Amount was refunded to wallet, minus fee
            Assert.Equal(senderBalanceBefore - this.node1.WalletSpendableBalance, fee);

            // Receipt is correct
            ReceiptResponse receipt = this.node1.GetReceipt(response.TransactionId.ToString());

            Assert.Equal(lastBlock.GetHash().ToString(), receipt.BlockHash);
            Assert.Equal(response.TransactionId.ToString(), receipt.TransactionHash);
            Assert.Empty(receipt.Logs);
            Assert.False(receipt.Success);
            Assert.Equal(GasPriceList.CreateCost, receipt.GasUsed);
            Assert.Null(receipt.NewContractAddress);
            Assert.Equal(this.node1.MinerAddress.Address, receipt.From);
            Assert.Null(receipt.To);
        }
        public MethodReference GetConstructorReferenceInternal(Expression <Action> expression)
        {
            var info = SymbolExtensions.GetCtorInfo(expression);

            var m = ModuleDefinition.CreateModule("t", ModuleKind.Dll).Import(info);

            return(m);
        }
 public void SetUp()
 {
     module = ModuleDefinition.CreateModule("foo", new ModuleParameters()
     {
         AssemblyResolver = new MockAssemblyResolver(),
         Kind             = ModuleKind.Dll,
     });
 }
Exemple #18
0
        public static void SourceImplementation(MethodDefinition method, string code)
        {
            var mod  = ModuleDefinition.CreateModule("bla", ModuleKind.Dll);
            var blob = CreateBlob(code);
            var ctor = new CustomAttribute(mod.ImportReference((typeof(CustomSource))).Resolve().Methods.First(x => x.IsConstructor), blob.ToArray());

            method.CustomAttributes.Add(ctor);
        }
Exemple #19
0
        /*
         * public override void DecompileMethod(MethodDefinition method, ITextOutput output, DecompilationOptions options)
         * {
         *      if (!method.HasBody) {
         *              return;
         *      }
         *
         *      ILAstBuilder astBuilder = new ILAstBuilder();
         *      ILBlock ilMethod = new ILBlock();
         *      DecompilerContext context = new DecompilerContext(method.Module) { CurrentType = method.DeclaringType, CurrentMethod = method };
         *      ilMethod.Body = astBuilder.Build(method, inlineVariables, context);
         *
         *      if (abortBeforeStep != null) {
         *              new ILAstOptimizer().Optimize(context, ilMethod, abortBeforeStep.Value);
         *      }
         *
         *      if (context.CurrentMethodIsAsync)
         *              output.WriteLine("async/await");
         *
         *      var allVariables = ilMethod.GetSelfAndChildrenRecursive<ILExpression>().Select(e => e.Operand as ILVariable)
         *              .Where(v => v != null && !v.IsParameter).Distinct();
         *      foreach (ILVariable v in allVariables) {
         *              output.WriteDefinition(v.Name, v);
         *              if (v.Type != null) {
         *                      output.Write(" : ");
         *                      if (v.IsPinned)
         *                              output.Write("pinned ");
         *                      v.Type.WriteTo(output, ILNameSyntax.ShortTypeName);
         *              }
         *              if (v.IsGenerated) {
         *                      output.Write(" [generated]");
         *              }
         *              output.WriteLine();
         *      }
         *      output.WriteLine();
         *
         *      foreach (ILNode node in ilMethod.Body) {
         *              node.WriteTo(output);
         *              output.WriteLine();
         *      }
         * }*/

        internal static IEnumerable <ILAstLanguage> GetDebugLanguages()
        {
            yield return(new TypedIL());

            CSharpDecompiler decompiler = new CSharpDecompiler(ModuleDefinition.CreateModule("Dummy", ModuleKind.Dll), new DecompilerSettings());

            yield return(new BlockIL(decompiler.ILTransforms.ToList()));
        }
Exemple #20
0
        public APITests () {
            TestModule = ModuleDefinition.CreateModule("TestModule", ModuleKind.NetModule);
            MetadataScope = TestModule;

            T1 = new TypeReference("namespace", "Type1", TestModule, MetadataScope);
            T1_2 = new TypeReference("namespace", "Type1", TestModule, MetadataScope);
            T2 = new TypeReference("namespace", "Type2", TestModule, MetadataScope);
            T3 = new TypeReference("namespace2", "Type1", TestModule, MetadataScope);
        }
Exemple #21
0
        public void CreateModuleEscapesAssemblyName()
        {
            var module = ModuleDefinition.CreateModule("Test.dll", ModuleKind.Dll);

            Assert.AreEqual("Test", module.Assembly.Name.Name);

            module = ModuleDefinition.CreateModule("Test.exe", ModuleKind.Console);
            Assert.AreEqual("Test", module.Assembly.Name.Name);
        }
        public void ImportMethodOnOpenGeneric()
        {
            var generic = typeof(Generic <>).ToDefinition();
            var module  = ModuleDefinition.CreateModule("foo", ModuleKind.Dll);

            var method = module.Import(generic.GetMethod("Method"));

            Assert.AreEqual("T Mono.Cecil.Tests.ImportCecilTests/Generic`1::Method(T)", method.FullName);
        }
Exemple #23
0
        static ModuleDefinition CreateModule(string name)
        {
            var resolver = new DefaultAssemblyResolver();

            resolver.AddSearchDirectory(Path.GetDirectoryName(typeof(ImportCecilTests).Assembly.Location));
            return(ModuleDefinition.CreateModule(name, new ModuleParameters {
                Kind = ModuleKind.Dll, AssemblyResolver = resolver
            }));
        }
Exemple #24
0
        public static AssemblyDefinition CreateMultiModuleAssemblyDefinition()
        {
            AssemblyDefinition corlib = AssemblyDefinition.ReadAssembly(typeof(object).Module.FullyQualifiedName);

            AssemblyDefinition assemblyDefinition = AssemblyDefinitionObjectMother.CreateAssemblyDefinition("TestAssembly");

            assemblyDefinition.MainModule.AssemblyReferences.Add(corlib.Name);
            assemblyDefinition.Name.Version = new Version("1.0.0.0");

            ModuleDefinition secondModule        = ModuleDefinition.CreateModule("TestSecondModule.netmodule", ModuleKind.NetModule);
            TypeReference    typereference       = secondModule.Import(typeof(void));
            TypeReference    typereferenceObject = secondModule.Import(typeof(object));


            TypeDefinition   type   = new TypeDefinition("TestSpace", "TestType", TypeAttributes.Public | TypeAttributes.Class, assemblyDefinition.MainModule.Import(typeof(object)));
            MethodDefinition method = new MethodDefinition("TestMethod", MethodAttributes.Public | MethodAttributes.HideBySig, typereference);
            var il = method.Body.GetILProcessor();

            il.Emit(OpCodes.Ret);

            type.Methods.Add(method);
            method.DeclaringType = type;
            assemblyDefinition.MainModule.Types.Add(type);


            TypeDefinition   secondType   = new TypeDefinition("TestSpace", "TestSecondType", TypeAttributes.Public | TypeAttributes.Class, secondModule.Import(typeof(object)));
            MethodDefinition secondMethod = new MethodDefinition("TestSecondMethod", MethodAttributes.Public | MethodAttributes.HideBySig, typereference);

            il = secondMethod.Body.GetILProcessor();
            il.Emit(OpCodes.Ret);

            secondType.Methods.Add(secondMethod);
            secondModule.Types.Add(secondType);
            secondMethod.DeclaringType = secondType;
            assemblyDefinition.Modules.Add(secondModule);
            assemblyDefinition.MainModule.ModuleReferences.Add(secondModule);

            ExportedType e = new ExportedType("TestSpace", "TestSecondType", new ModuleReference(secondModule.Name));

            assemblyDefinition.MainModule.ExportedTypes.Add(e);

            var testingDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"temp\testing");

            if (!Directory.Exists(testingDirectory))
            {
                Directory.CreateDirectory(testingDirectory);
            }

            assemblyDefinition.Write(Path.Combine(testingDirectory, "test.mainmodule"));
            secondModule.Write(Path.Combine(testingDirectory, "test.module"));
            assemblyDefinition = AssemblyDefinition.ReadAssembly(Path.Combine(testingDirectory, "test.mainmodule"));

            return(assemblyDefinition);
        }
        public void SetUp()
        {
            resolver = new XamlCAssemblyResolver();
            resolver.AddAssembly(Uri.UnescapeDataString((new UriBuilder(typeof(ModuleDefinitionExtensionsTests).Assembly.CodeBase)).Path));
            resolver.AddAssembly(Uri.UnescapeDataString((new UriBuilder(typeof(byte).Assembly.CodeBase)).Path));

            module = ModuleDefinition.CreateModule("foo", new ModuleParameters {
                AssemblyResolver = resolver,
                Kind             = ModuleKind.Dll
            });
        }
Exemple #26
0
        public void FQN_Matches()
        {
            var type = typeof(TypeConversionTests);

            var module = ModuleDefinition.CreateModule("main", ModuleKind.Dll);
            var tr     = module.Import(type);

            var fqn1 = FQN.FromType(type);
            var fqn2 = FQN.FromTypeReference(tr);

            Assert.AreEqual(fqn1.ToString(), fqn2.ToString());
        }
Exemple #27
0
        public void Closed_Generic_FQN_Matches()
        {
            var type = typeof(TestType <List <int> > .TestClass <string, short>);

            var module = ModuleDefinition.CreateModule("main", ModuleKind.Dll);
            var tr     = module.Import(type);

            var fqn1 = FQN.FromType(type);
            var fqn2 = FQN.FromTypeReference(tr);

            Assert.AreEqual(fqn1.ToString(), fqn2.ToString());
        }
Exemple #28
0
        public void SetUp()
        {
            resolver = new XamlCAssemblyResolver();
            resolver.AddAssembly(typeof(ModuleDefinitionExtensionsTests).Assembly.Location);
            resolver.AddAssembly(typeof(byte).Assembly.Location);

            module = ModuleDefinition.CreateModule("foo", new ModuleParameters
            {
                AssemblyResolver = resolver,
                Kind             = ModuleKind.Dll
            });
        }
Exemple #29
0
        private void TestJitHookMissingMethodStep()
        {
            int    id         = ID++;
            string @namespace = "MonoMod.UnitTest";
            string @name      = "JitHookRegressionTestHelper" + id;
            string @fullName  = @namespace + "." + @name;

            Assembly asm;

            using (ModuleDefinition module = ModuleDefinition.CreateModule(@fullName, new ModuleParameters()
            {
                Kind = ModuleKind.Dll,
                ReflectionImporterProvider = MMReflectionImporter.Provider
            })) {
                TypeDefinition type = new TypeDefinition(
                    @namespace,
                    @name,
                    MC.TypeAttributes.Public | MC.TypeAttributes.Abstract | MC.TypeAttributes.Sealed
                    )
                {
                    BaseType = module.TypeSystem.Object
                };
                module.Types.Add(type);

                MethodDefinition method = new MethodDefinition(@name,
                                                               MC.MethodAttributes.Public | MC.MethodAttributes.Static | MC.MethodAttributes.HideBySig,
                                                               module.TypeSystem.Void
                                                               );
                type.Methods.Add(method);

                ILProcessor il = method.Body.GetILProcessor();
                il.Emit(OpCodes.Call, module.ImportReference(
                            new MethodReference(
                                "MissingMethod" + id,
                                module.TypeSystem.Void,
                                new TypeReference(
                                    "TotallyNotReal", "MissingType",
                                    module,
                                    new AssemblyNameReference("TotallyNotReal", new Version(0, 0, 0, 0))
                                    )
                                )
                            ));
                il.Emit(OpCodes.Ret);

                asm = ReflectionHelper.Load(module);
            }

            try {
                (asm.GetType(@fullName).GetMethod(@name).CreateDelegate <Action>())();
            } catch (TypeLoadException) {
            }
        }
Exemple #30
0
        static void Main()
        {
            var sourceFile      = SourceFile.Read("../../code.txt");
            var programNode     = CheckedParse(sourceFile);
            var module          = ModuleDefinition.CreateModule("out", ModuleKind.Console);
            var allTypes        = new AllTypes(module);
            var programCompiler = new ProgramCompiler(allTypes, programNode, "Program", "Main");

            programCompiler.Compile();
            module.EntryPoint = programCompiler.MainMethod;
            module.Write("out.exe");
            Assembly.LoadFrom("out.exe").GetType("Program").GetMethod("Main").Invoke(null, new object[] { });
        }